fivetran-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fivetran_cli/client.py ADDED
@@ -0,0 +1,159 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+ from dataclasses import dataclass
9
+ from typing import Any
10
+
11
+
12
+ DEFAULT_BASE_URL = "https://api.fivetran.com"
13
+
14
+
15
+ class CliError(Exception):
16
+ """User-facing CLI error."""
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class ClientConfig:
21
+ api_key: str | None
22
+ api_secret: str | None
23
+ base_url: str = DEFAULT_BASE_URL
24
+ verbose: bool = False
25
+
26
+
27
+ class FivetranClient:
28
+ def __init__(self, config: ClientConfig) -> None:
29
+ self.config = config
30
+ self.base_url = config.base_url.rstrip("/")
31
+
32
+ def request(
33
+ self,
34
+ method: str,
35
+ path: str,
36
+ *,
37
+ query: dict[str, Any] | None = None,
38
+ body: Any = None,
39
+ auth_required: bool = True,
40
+ ) -> Any:
41
+ if auth_required and (not self.config.api_key or not self.config.api_secret):
42
+ raise CliError(
43
+ "Missing Fivetran API credentials. Set FIVETRAN_API_KEY and "
44
+ "FIVETRAN_API_SECRET, pass --api-key/--api-secret, or use --profile."
45
+ )
46
+
47
+ url = self._url(path, query)
48
+ data: bytes | None = None
49
+ headers = {"Accept": "application/json"}
50
+ if body is not None:
51
+ data = json.dumps(body, separators=(",", ":")).encode("utf-8")
52
+ headers["Content-Type"] = "application/json"
53
+
54
+ if auth_required:
55
+ token = f"{self.config.api_key}:{self.config.api_secret}".encode("utf-8")
56
+ headers["Authorization"] = "Basic " + base64.b64encode(token).decode("ascii")
57
+
58
+ request = urllib.request.Request(url, data=data, headers=headers, method=method)
59
+
60
+ try:
61
+ with urllib.request.urlopen(request) as response:
62
+ raw = response.read()
63
+ return _decode_response(raw)
64
+ except urllib.error.HTTPError as exc:
65
+ raw = exc.read()
66
+ payload = _decode_response(raw)
67
+ message = _error_message(exc.code, payload, raw)
68
+ raise CliError(message) from exc
69
+ except urllib.error.URLError as exc:
70
+ raise CliError(f"Request failed: {exc.reason}") from exc
71
+
72
+ def paginated_request(
73
+ self,
74
+ method: str,
75
+ path: str,
76
+ *,
77
+ query: dict[str, Any] | None = None,
78
+ auth_required: bool = True,
79
+ ) -> Any:
80
+ merged: Any | None = None
81
+ cursor = query.get("cursor") if query else None
82
+
83
+ while True:
84
+ page_query = dict(query or {})
85
+ if cursor:
86
+ page_query["cursor"] = cursor
87
+ page = self.request(
88
+ method,
89
+ path,
90
+ query=page_query,
91
+ auth_required=auth_required,
92
+ )
93
+ merged = _merge_page(merged, page)
94
+ cursor = _next_cursor(page)
95
+ if not cursor:
96
+ return merged
97
+
98
+ def _url(self, path: str, query: dict[str, Any] | None) -> str:
99
+ clean_query = {
100
+ key: value
101
+ for key, value in (query or {}).items()
102
+ if value is not None and value is not False
103
+ }
104
+ query_string = urllib.parse.urlencode(clean_query)
105
+ url = f"{self.base_url}{path}"
106
+ if query_string:
107
+ return f"{url}?{query_string}"
108
+ return url
109
+
110
+
111
+ def _decode_response(raw: bytes) -> Any:
112
+ if not raw:
113
+ return None
114
+ text = raw.decode("utf-8")
115
+ try:
116
+ return json.loads(text)
117
+ except json.JSONDecodeError:
118
+ return text
119
+
120
+
121
+ def _error_message(status: int, payload: Any, raw: bytes) -> str:
122
+ if isinstance(payload, dict):
123
+ message = payload.get("message") or payload.get("error")
124
+ code = payload.get("code")
125
+ if code and message:
126
+ return f"HTTP {status}: {code}: {message}"
127
+ if message:
128
+ return f"HTTP {status}: {message}"
129
+ if raw:
130
+ return f"HTTP {status}: {raw.decode('utf-8', errors='replace')}"
131
+ return f"HTTP {status}"
132
+
133
+
134
+ def _merge_page(merged: Any | None, page: Any) -> Any:
135
+ if merged is None:
136
+ return page
137
+ if not isinstance(merged, dict) or not isinstance(page, dict):
138
+ return page
139
+
140
+ merged_data = merged.get("data")
141
+ page_data = page.get("data")
142
+ if isinstance(merged_data, dict) and isinstance(page_data, dict):
143
+ merged_items = merged_data.get("items")
144
+ page_items = page_data.get("items")
145
+ if isinstance(merged_items, list) and isinstance(page_items, list):
146
+ merged_items.extend(page_items)
147
+ merged_data["next_cursor"] = page_data.get("next_cursor")
148
+ return merged
149
+ return page
150
+
151
+
152
+ def _next_cursor(page: Any) -> str | None:
153
+ if not isinstance(page, dict):
154
+ return None
155
+ data = page.get("data")
156
+ if isinstance(data, dict):
157
+ cursor = data.get("next_cursor")
158
+ return str(cursor) if cursor else None
159
+ return None
fivetran_cli/output.py ADDED
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Any, TextIO
6
+
7
+ from .client import CliError
8
+
9
+
10
+ def emit_output(
11
+ payload: Any,
12
+ *,
13
+ output_format: str,
14
+ output_path: str | None,
15
+ quiet: bool,
16
+ stdout: TextIO,
17
+ ) -> None:
18
+ if quiet or payload is None:
19
+ return
20
+ rendered = render(payload, output_format)
21
+ if output_path:
22
+ try:
23
+ Path(output_path).write_text(rendered + "\n", encoding="utf-8")
24
+ except OSError as exc:
25
+ raise CliError(f"Could not write output file {output_path}: {exc}") from exc
26
+ return
27
+ stdout.write(rendered + "\n")
28
+
29
+
30
+ def render(payload: Any, output_format: str) -> str:
31
+ if output_format == "json":
32
+ return json.dumps(payload, indent=2, sort_keys=True)
33
+ if output_format == "yaml":
34
+ return _to_yaml(payload)
35
+ if output_format == "table":
36
+ return _to_table(payload)
37
+ raise ValueError(f"Unsupported output format: {output_format}")
38
+
39
+
40
+ def _to_yaml(value: Any, indent: int = 0) -> str:
41
+ prefix = " " * indent
42
+ if isinstance(value, dict):
43
+ lines: list[str] = []
44
+ for key, item in value.items():
45
+ if isinstance(item, (dict, list)):
46
+ lines.append(f"{prefix}{key}:")
47
+ lines.append(_to_yaml(item, indent + 2))
48
+ else:
49
+ lines.append(f"{prefix}{key}: {_yaml_scalar(item)}")
50
+ return "\n".join(lines)
51
+ if isinstance(value, list):
52
+ lines = []
53
+ for item in value:
54
+ if isinstance(item, (dict, list)):
55
+ lines.append(f"{prefix}-")
56
+ lines.append(_to_yaml(item, indent + 2))
57
+ else:
58
+ lines.append(f"{prefix}- {_yaml_scalar(item)}")
59
+ return "\n".join(lines)
60
+ return f"{prefix}{_yaml_scalar(value)}"
61
+
62
+
63
+ def _yaml_scalar(value: Any) -> str:
64
+ if value is None:
65
+ return "null"
66
+ if isinstance(value, bool):
67
+ return "true" if value else "false"
68
+ if isinstance(value, (int, float)):
69
+ return str(value)
70
+ return json.dumps(str(value))
71
+
72
+
73
+ def _to_table(payload: Any) -> str:
74
+ rows = _table_rows(payload)
75
+ if not rows:
76
+ return ""
77
+ if not all(isinstance(row, dict) for row in rows):
78
+ return json.dumps(payload, indent=2, sort_keys=True)
79
+
80
+ columns = _columns(rows)
81
+ widths = {
82
+ column: max(len(column), *(len(_cell(row.get(column))) for row in rows))
83
+ for column in columns
84
+ }
85
+ header = " ".join(column.ljust(widths[column]) for column in columns)
86
+ separator = " ".join("-" * widths[column] for column in columns)
87
+ body = [
88
+ " ".join(_cell(row.get(column)).ljust(widths[column]) for column in columns)
89
+ for row in rows
90
+ ]
91
+ return "\n".join([header, separator, *body])
92
+
93
+
94
+ def _table_rows(payload: Any) -> list[Any]:
95
+ if isinstance(payload, dict):
96
+ data = payload.get("data")
97
+ if isinstance(data, dict) and isinstance(data.get("items"), list):
98
+ return data["items"]
99
+ if isinstance(data, list):
100
+ return data
101
+ if isinstance(data, dict):
102
+ return [data]
103
+ if isinstance(payload, list):
104
+ return payload
105
+ return []
106
+
107
+
108
+ def _columns(rows: list[dict[str, Any]]) -> list[str]:
109
+ preferred = ["id", "name", "service", "schema", "group_id", "created_at"]
110
+ available = {key for row in rows for key in row}
111
+ ordered = [column for column in preferred if column in available]
112
+ ordered.extend(sorted(available - set(ordered)))
113
+ return ordered
114
+
115
+
116
+ def _cell(value: Any) -> str:
117
+ if value is None:
118
+ return ""
119
+ if isinstance(value, (dict, list)):
120
+ return json.dumps(value, sort_keys=True)
121
+ return str(value)
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: fivetran-cli
3
+ Version: 0.1.0
4
+ Summary: Command line wrapper for the Fivetran REST API
5
+ Author: Fivetran
6
+ License-Expression: MIT
7
+ Classifier: Environment :: Console
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.11
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Requires-Python: >=3.11
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Dynamic: license-file
16
+
17
+ # fivetran-cli
18
+
19
+ Thin command line wrapper around the Fivetran REST API.
20
+
21
+ ```text
22
+ fivetran [global-options] <resource> <operation> [arguments] [options]
23
+ ```
24
+
25
+ Credentials default to `FIVETRAN_API_KEY` and `FIVETRAN_API_SECRET`.
26
+
27
+ ```bash
28
+ fivetran --api-key "$FIVETRAN_API_KEY" --api-secret "$FIVETRAN_API_SECRET" connection list
29
+ fivetran connection create --data-file connection.json
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ Global options may be placed before or after the resource command.
35
+
36
+ ```bash
37
+ fivetran connection list --api-key "$FIVETRAN_API_KEY" --api-secret "$FIVETRAN_API_SECRET"
38
+ fivetran connection-schema get connection_id
39
+ fivetran connector-metadata get google_ads
40
+ fivetran public-connector list
41
+ ```
42
+
43
+ Output defaults to JSON. Use `--format table`, `--format yaml`, or `--output path` when needed.
44
+
45
+ Request body commands accept either raw JSON or a JSON file:
46
+
47
+ ```bash
48
+ fivetran private-link create --data-file private-link.json
49
+ fivetran connection-schema column update connection_id schema table column --data '{"enabled":false}'
50
+ ```
51
+
52
+ Destructive commands require `--yes` in non-interactive mode.
53
+
54
+ ## Included Commands
55
+
56
+ Core resources:
57
+
58
+ - `account get`
59
+ - `connection list|get|create|update|delete|sync|resync|test`
60
+ - `destination list|get|create|update|delete|test`
61
+ - `group list|get|create|update|delete`
62
+ - `group connection list`
63
+ - `group user list|add|remove`
64
+ - `group public-key get`
65
+ - `group service-account get`
66
+
67
+ Access management:
68
+
69
+ - `user list|get|invite|update|delete`
70
+ - `user account-role remove`
71
+ - `user connection list|get|add|update|remove`
72
+ - `user group list|get|add|update|remove`
73
+ - `team list|get|create|update|delete`
74
+ - `team account-role remove`
75
+ - `team connection list|get|add|update|remove`
76
+ - `team group list|get|add|update|remove`
77
+ - `team user list|get|add|update|remove`
78
+ - `role list`
79
+ - `system-key list|get|create|update|delete|rotate`
80
+
81
+ Schemas and metadata:
82
+
83
+ - `connection-schema get|setup|update|reload|resync-table`
84
+ - `connection-schema schema update`
85
+ - `connection-schema table update`
86
+ - `connection-schema column list|update|drop|drop-blocked`
87
+ - `connector-metadata list|get`
88
+ - `public-connector list`
89
+
90
+ Networking:
91
+
92
+ - `hybrid-deployment-agent list|get|create|delete|regenerate-auth|reset-credentials`
93
+ - `proxy-agent list|get|create|delete|regenerate-secrets`
94
+ - `proxy-agent connection list`
95
+ - `private-link list|get|create|update|delete`
96
+
97
+ Transformations:
98
+
99
+ - `transformation list`
100
+
101
+ ## Not Included Yet
102
+
103
+ These API areas are still intentionally not implemented:
104
+
105
+ - Certificates and fingerprints
106
+ - Connector SDK packages
107
+ - Log services
108
+ - Webhooks
109
+ - Transformation create/get/update/delete/run/cancel/upgrade
110
+ - Transformation package metadata
111
+ - Transformation projects
112
+ - Hub registration
113
+ - Group destination listing, pending confirmation of a supported REST endpoint
114
+ - Interactive connector setup workflows
115
+ - File upload/download handling for Connector SDK packages
116
+ - High-quality resource-specific table formats beyond the generic table renderer
117
+
118
+ ## Build And Publish
119
+
120
+ Package artifacts are controlled by `pyproject.toml` and `MANIFEST.in`. The source distribution intentionally excludes local agent/project-planning files:
121
+
122
+ - `AGENTS.md`
123
+ - `plans/`
124
+
125
+ Install local packaging tools with `pipx`:
126
+
127
+ ```bash
128
+ pipx install build
129
+ pipx install twine
130
+ ```
131
+
132
+ This exposes `pyproject-build` and `twine` on your PATH. If you install these tools into a virtual environment instead, use `python3 -m build` and `python3 -m twine` in place of the commands below.
133
+
134
+ Build source and wheel distributions:
135
+
136
+ ```bash
137
+ pyproject-build
138
+ ```
139
+
140
+ Validate the generated artifacts:
141
+
142
+ ```bash
143
+ twine check dist/*
144
+ ```
145
+
146
+ Upload to TestPyPI first:
147
+
148
+ ```bash
149
+ twine upload --repository testpypi dist/*
150
+ ```
151
+
152
+ Install from TestPyPI in a clean environment:
153
+
154
+ ```bash
155
+ python3 -m pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ fivetran-cli
156
+ fivetran --help
157
+ ```
158
+
159
+ Upload to PyPI after the TestPyPI package is verified:
160
+
161
+ ```bash
162
+ twine upload dist/*
163
+ ```
164
+
165
+ These upload commands assume `~/.pypirc` is configured with the `pypi` and `testpypi` repositories. If `~/.pypirc` is not configured, set `TWINE_USERNAME=__token__` and `TWINE_PASSWORD=<api-token>` before running `twine upload`.
166
+
167
+ PyPI files are immutable for a published version. If an upload is wrong, bump the version in `pyproject.toml`, rebuild, re-check, and upload the new version.
@@ -0,0 +1,11 @@
1
+ fivetran_cli/__init__.py,sha256=MJaAT0U45TFotKU2sNcRFx8wISXJjqfTyhps30eYf6M,51
2
+ fivetran_cli/__main__.py,sha256=PSQ4rpL0dG6f-qH4N7H-gD9igQkdHzH4yVZDcW8lfZo,80
3
+ fivetran_cli/cli.py,sha256=DyY7m8oAvShfyJIcjzNu5re15mUavEmM8b96Viv9rQk,47548
4
+ fivetran_cli/client.py,sha256=rY_zPh3B1-Yk7VRIbHXMAOm6n9wQhuazqGy68Q5v6hA,4910
5
+ fivetran_cli/output.py,sha256=K6sPy79rbH5uGE9_RQ74YmNNhQ1O-0g0gTpbaxnqs1U,3725
6
+ fivetran_cli-0.1.0.dist-info/licenses/LICENSE,sha256=8u5SmFMJwBaX9Qh0Nm9J6eZEkIb79gUyVAStZV1lPzk,1065
7
+ fivetran_cli-0.1.0.dist-info/METADATA,sha256=ih1nUq67vMoYKVVpacSwJdjlYkbm6-CrUGccLJZfu1k,4838
8
+ fivetran_cli-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ fivetran_cli-0.1.0.dist-info/entry_points.txt,sha256=vhb-xRrS8kxCBqOGS6DPnCDmSg3PK8QKB6BjbRFjVGI,51
10
+ fivetran_cli-0.1.0.dist-info/top_level.txt,sha256=-B4QNe8Zpu58LFUDAxov_1XSrzKnQo07EleDwlCiYo8,13
11
+ fivetran_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fivetran = fivetran_cli.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fivetran
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ fivetran_cli