adstack 0.2.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.
- adstack/__init__.py +3 -0
- adstack/__main__.py +3 -0
- adstack/cli.py +476 -0
- adstack/config.py +141 -0
- adstack/engine.py +178 -0
- adstack/errors.py +17 -0
- adstack/mcp_server.py +330 -0
- adstack/plan.py +177 -0
- adstack/providers/__init__.py +23 -0
- adstack/providers/base.py +62 -0
- adstack/providers/google_ads/__init__.py +40 -0
- adstack/providers/google_ads/api.py +342 -0
- adstack/providers/google_ads/planner.py +710 -0
- adstack/providers/google_ads/sandbox.py +342 -0
- adstack/providers/google_ads/schema.py +258 -0
- adstack/scaffold.py +44 -0
- adstack/validation.py +82 -0
- adstack-0.2.0.dist-info/METADATA +235 -0
- adstack-0.2.0.dist-info/RECORD +23 -0
- adstack-0.2.0.dist-info/WHEEL +5 -0
- adstack-0.2.0.dist-info/entry_points.txt +2 -0
- adstack-0.2.0.dist-info/licenses/LICENSE +177 -0
- adstack-0.2.0.dist-info/top_level.txt +1 -0
adstack/__init__.py
ADDED
adstack/__main__.py
ADDED
adstack/cli.py
ADDED
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"""The ``adstack`` command line: a Terraform-style workflow for advertising campaigns.
|
|
2
|
+
|
|
3
|
+
adstack init create a starter configuration
|
|
4
|
+
adstack validate check the configuration (offline)
|
|
5
|
+
adstack plan show what would change; optionally save the plan
|
|
6
|
+
adstack apply apply a saved plan, or plan and apply after approval
|
|
7
|
+
adstack destroy pause every campaign Adstack manages
|
|
8
|
+
adstack show display a saved plan
|
|
9
|
+
adstack state list list what Adstack manages in the account
|
|
10
|
+
adstack report performance and search-term reports
|
|
11
|
+
adstack mcp run the MCP server for AI assistants
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from . import __version__
|
|
24
|
+
from . import plan as plans
|
|
25
|
+
from .config import load
|
|
26
|
+
from .engine import Workspace, apply, connect, create_plan, missing_permissions, target_label, verify
|
|
27
|
+
from .errors import AdstackError, ConfigError, PlanError
|
|
28
|
+
from .plan import GATES
|
|
29
|
+
from .providers import get_provider
|
|
30
|
+
from .scaffold import STARTER_CONFIG
|
|
31
|
+
|
|
32
|
+
EXIT_OK = 0
|
|
33
|
+
EXIT_ERROR = 1
|
|
34
|
+
EXIT_CHANGES = 2
|
|
35
|
+
|
|
36
|
+
DOCS_URL = "https://github.com/markwroberts0/adstack"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Ui:
|
|
40
|
+
def __init__(self, color: bool):
|
|
41
|
+
self.color = color
|
|
42
|
+
|
|
43
|
+
def out(self, text: str = "") -> None:
|
|
44
|
+
print(text)
|
|
45
|
+
|
|
46
|
+
def info(self, text: str) -> None:
|
|
47
|
+
"""Progress messages go to stderr so that --json output stays parseable."""
|
|
48
|
+
print(text, file=sys.stderr)
|
|
49
|
+
|
|
50
|
+
def paint(self, text: str, code: str) -> str:
|
|
51
|
+
return f"\033[{code}m{text}\033[0m" if self.color else text
|
|
52
|
+
|
|
53
|
+
def success(self, text: str) -> None:
|
|
54
|
+
self.out(self.paint(text, "1;32"))
|
|
55
|
+
|
|
56
|
+
def error(self, text: str) -> None:
|
|
57
|
+
print(self.paint("Error: ", "1;31") + text, file=sys.stderr)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def main(argv: list[str] | None = None) -> int:
|
|
61
|
+
args = build_parser().parse_args(argv)
|
|
62
|
+
no_color = getattr(args, "no_color", False) or "NO_COLOR" in os.environ
|
|
63
|
+
ui = Ui(color=not no_color and sys.stdout.isatty())
|
|
64
|
+
try:
|
|
65
|
+
return args.handler(args, ui)
|
|
66
|
+
except AdstackError as exc:
|
|
67
|
+
ui.error(str(exc))
|
|
68
|
+
return EXIT_ERROR
|
|
69
|
+
except OSError as exc:
|
|
70
|
+
ui.error(f"{exc.filename or ''}: {exc.strerror or exc}".lstrip(": "))
|
|
71
|
+
return EXIT_ERROR
|
|
72
|
+
except KeyboardInterrupt:
|
|
73
|
+
ui.error("interrupted")
|
|
74
|
+
return 130
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# -- Commands ---------------------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cmd_init(args: argparse.Namespace, ui: Ui) -> int:
|
|
81
|
+
directory = Path(args.directory)
|
|
82
|
+
target = directory / "adstack.yaml"
|
|
83
|
+
if target.exists():
|
|
84
|
+
raise ConfigError(f"{target} already exists")
|
|
85
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
target.write_text(STARTER_CONFIG, encoding="utf-8")
|
|
87
|
+
ui.success(f"Created {target}")
|
|
88
|
+
where = "" if directory == Path(".") else f" {directory}"
|
|
89
|
+
ui.out(
|
|
90
|
+
"\nNext steps:\n"
|
|
91
|
+
f" 1. Edit {target}: set your namespace, currency, ads and keywords.\n"
|
|
92
|
+
f" 2. adstack validate{where}\n"
|
|
93
|
+
f" 3. adstack plan{where} --sandbox # try it against a local sandbox account\n"
|
|
94
|
+
f" 4. adstack plan{where} --out first.plan.json\n"
|
|
95
|
+
" adstack apply first.plan.json\n"
|
|
96
|
+
"\nAdd .adstack/ and *.plan.json to .gitignore: they hold local state, plans and receipts."
|
|
97
|
+
)
|
|
98
|
+
return EXIT_OK
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cmd_validate(args: argparse.Namespace, ui: Ui) -> int:
|
|
102
|
+
try:
|
|
103
|
+
config = load(args.path)
|
|
104
|
+
except ConfigError as exc:
|
|
105
|
+
if args.json:
|
|
106
|
+
ui.out(json.dumps({"valid": False, "error": str(exc)}, indent=2))
|
|
107
|
+
return EXIT_ERROR
|
|
108
|
+
raise
|
|
109
|
+
if args.json:
|
|
110
|
+
ui.out(json.dumps({"valid": True, "provider": config.provider, "summary": config.summary()}, indent=2))
|
|
111
|
+
else:
|
|
112
|
+
ui.success("Success! The configuration is valid.")
|
|
113
|
+
ui.out(f"{get_provider(config.provider).title}: {config.summary()}")
|
|
114
|
+
return EXIT_OK
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def cmd_plan(args: argparse.Namespace, ui: Ui) -> int:
|
|
118
|
+
workspace = _workspace(args)
|
|
119
|
+
config = load(args.path)
|
|
120
|
+
if args.out and Path(args.out).exists():
|
|
121
|
+
raise PlanError(f"{args.out} already exists; plan files are never overwritten, choose a new name")
|
|
122
|
+
backend = connect(config, workspace)
|
|
123
|
+
ui.info(f"Reading the {target_label(config.provider, backend)}...")
|
|
124
|
+
plan = create_plan(config, workspace, prune=args.prune, destroy=args.destroy, backend=backend)
|
|
125
|
+
validated = False
|
|
126
|
+
if args.validate and plan["operations"] and not plan["blockers"]:
|
|
127
|
+
backend.mutate(plan["operations"], validate_only=True)
|
|
128
|
+
validated = True
|
|
129
|
+
ui.out(json.dumps(plan, indent=2, ensure_ascii=False) if args.json else plans.render(plan, color=ui.color))
|
|
130
|
+
if plan["blockers"]:
|
|
131
|
+
raise PlanError("the plan is blocked; resolve the blockers above, or re-plan with --prune where suggested")
|
|
132
|
+
if validated:
|
|
133
|
+
ui.info(f"{get_provider(config.provider).title} validated these changes. Nothing was changed.")
|
|
134
|
+
if args.out:
|
|
135
|
+
plans.save(plan, args.out)
|
|
136
|
+
ui.info(f"\nSaved the plan to {args.out}. To apply exactly this plan, run:\n adstack apply {args.out}")
|
|
137
|
+
elif plan["operations"] and not args.json:
|
|
138
|
+
ui.info(
|
|
139
|
+
"\nNote: you didn't use --out, so Adstack can't guarantee that exactly these actions will be "
|
|
140
|
+
"taken if you run 'adstack apply' now."
|
|
141
|
+
)
|
|
142
|
+
return EXIT_CHANGES if args.detailed_exitcode and plan["operations"] else EXIT_OK
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def cmd_apply(args: argparse.Namespace, ui: Ui) -> int:
|
|
146
|
+
workspace = _workspace(args)
|
|
147
|
+
allow = {gate for gate in GATES if getattr(args, gate, False)}
|
|
148
|
+
target = Path(args.target)
|
|
149
|
+
if plans.is_plan_file(target):
|
|
150
|
+
if args.prune or args.destroy:
|
|
151
|
+
raise PlanError("--prune and --destroy can't be used with a saved plan; they were set when it was created")
|
|
152
|
+
saved = plans.load(target)
|
|
153
|
+
if args.sandbox and saved.get("backend") != "sandbox":
|
|
154
|
+
raise PlanError("this plan was made against the real platform, not the sandbox")
|
|
155
|
+
ui.info(f"Verifying {target} against the current state of the {saved.get('target', 'account')}...")
|
|
156
|
+
fresh, backend = verify(saved, workspace)
|
|
157
|
+
ui.out(plans.render(fresh, color=ui.color))
|
|
158
|
+
verified: Any = (fresh, backend)
|
|
159
|
+
plan = fresh
|
|
160
|
+
else:
|
|
161
|
+
config = load(target)
|
|
162
|
+
backend = connect(config, workspace)
|
|
163
|
+
ui.info(f"Reading the {target_label(config.provider, backend)}...")
|
|
164
|
+
plan = create_plan(config, workspace, prune=args.prune, destroy=args.destroy, backend=backend)
|
|
165
|
+
ui.out(plans.render(plan, color=ui.color))
|
|
166
|
+
verified = None # re-verified after approval, in case the account changed meanwhile
|
|
167
|
+
if plan["blockers"]:
|
|
168
|
+
raise PlanError("the plan is blocked; resolve the blockers above, or re-plan with --prune where suggested")
|
|
169
|
+
if not plan["operations"]:
|
|
170
|
+
return EXIT_OK
|
|
171
|
+
missing = missing_permissions(plan, allow)
|
|
172
|
+
if missing:
|
|
173
|
+
flags = " ".join(f"--{gate.replace('_', '-')}" for gate in missing)
|
|
174
|
+
raise PlanError(f"this plan needs explicit permission; review it, then add {flags}")
|
|
175
|
+
if verified is None and not args.auto_approve:
|
|
176
|
+
_confirm(ui, plan)
|
|
177
|
+
result = apply(plan, workspace, allow=allow, verified=verified)
|
|
178
|
+
if result is None:
|
|
179
|
+
return EXIT_OK
|
|
180
|
+
receipt, path = result
|
|
181
|
+
total = receipt["summary"]
|
|
182
|
+
ui.success(
|
|
183
|
+
f"\nApply complete! Resources: {total['add']} added, {total['change']} changed, {total['remove']} removed."
|
|
184
|
+
)
|
|
185
|
+
ui.out(f"Receipt: {_relative(path)}")
|
|
186
|
+
return EXIT_OK
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cmd_destroy(args: argparse.Namespace, ui: Ui) -> int:
|
|
190
|
+
args.target, args.prune, args.destroy = args.path, False, True
|
|
191
|
+
args.allow_enable = args.allow_budget_increase = False
|
|
192
|
+
return cmd_apply(args, ui)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def cmd_show(args: argparse.Namespace, ui: Ui) -> int:
|
|
196
|
+
plan = plans.load(args.plan)
|
|
197
|
+
if args.json:
|
|
198
|
+
ui.out(json.dumps(plan, indent=2, ensure_ascii=False))
|
|
199
|
+
return EXIT_OK
|
|
200
|
+
ui.out(plans.render(plan, color=ui.color))
|
|
201
|
+
ui.out(
|
|
202
|
+
f"\nCreated {plan.get('created_at')} by adstack {plan.get('adstack_version')} from "
|
|
203
|
+
f"{', '.join(plan['config']['files'])} ({plan['config'].get('summary')})."
|
|
204
|
+
)
|
|
205
|
+
return EXIT_OK
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def cmd_state_list(args: argparse.Namespace, ui: Ui) -> int:
|
|
209
|
+
workspace = _workspace(args)
|
|
210
|
+
config = load(args.path)
|
|
211
|
+
provider = get_provider(config.provider)
|
|
212
|
+
backend = connect(config, workspace)
|
|
213
|
+
target = target_label(config.provider, backend)
|
|
214
|
+
records = provider.inventory(config.desired, backend.read())
|
|
215
|
+
if args.json:
|
|
216
|
+
ui.out(json.dumps({"target": target, "resources": records}, indent=2, ensure_ascii=False))
|
|
217
|
+
return EXIT_OK
|
|
218
|
+
if not records:
|
|
219
|
+
ui.out(f"Adstack manages nothing in the {target} yet.")
|
|
220
|
+
return EXIT_OK
|
|
221
|
+
ui.out(f"Managed resources in the {target}:\n")
|
|
222
|
+
for line in render_inventory(records):
|
|
223
|
+
ui.out(line)
|
|
224
|
+
return EXIT_OK
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def cmd_report(args: argparse.Namespace, ui: Ui) -> int:
|
|
228
|
+
workspace = _workspace(args)
|
|
229
|
+
config = load(args.path)
|
|
230
|
+
backend = connect(config, workspace)
|
|
231
|
+
rows = backend.report(args.kind.replace("-", "_"), args.days, all_campaigns=args.all_campaigns)
|
|
232
|
+
if args.json:
|
|
233
|
+
ui.out(json.dumps(rows, indent=2, ensure_ascii=False))
|
|
234
|
+
return EXIT_OK
|
|
235
|
+
currency = config.desired.get("currency", "")
|
|
236
|
+
title = args.kind.replace("-", " ").capitalize()
|
|
237
|
+
ui.out(f"{title}, last {args.days} days ({target_label(config.provider, backend)}, cost in {currency}):\n")
|
|
238
|
+
if not rows:
|
|
239
|
+
ui.out("No data.")
|
|
240
|
+
return EXIT_OK
|
|
241
|
+
for line in render_table(rows):
|
|
242
|
+
ui.out(line)
|
|
243
|
+
return EXIT_OK
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def cmd_mcp(args: argparse.Namespace, ui: Ui) -> int:
|
|
247
|
+
try:
|
|
248
|
+
from .mcp_server import serve
|
|
249
|
+
except ModuleNotFoundError as exc:
|
|
250
|
+
if exc.name and exc.name.split(".")[0] == "mcp":
|
|
251
|
+
raise AdstackError(
|
|
252
|
+
f"the MCP server needs the 'mcp' package: install Adstack with the [mcp] extra (see {DOCS_URL}#install)"
|
|
253
|
+
) from None
|
|
254
|
+
raise
|
|
255
|
+
allow_apply = args.allow_apply or _env_flag("ADSTACK_MCP_ALLOW_APPLY")
|
|
256
|
+
serve(root=Path(args.root).resolve(), sandbox=args.sandbox, allow_apply=allow_apply)
|
|
257
|
+
return EXIT_OK
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def cmd_version(args: argparse.Namespace, ui: Ui) -> int:
|
|
261
|
+
ui.out(f"adstack {__version__}")
|
|
262
|
+
return EXIT_OK
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# -- Helpers ---------------------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _relative(path: Path) -> Path:
|
|
269
|
+
try:
|
|
270
|
+
return path.relative_to(Path.cwd())
|
|
271
|
+
except ValueError:
|
|
272
|
+
return path
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def _env_flag(name: str) -> bool:
|
|
276
|
+
return os.environ.get(name, "").strip().lower() in ("1", "true", "yes", "on")
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _workspace(args: argparse.Namespace) -> Workspace:
|
|
280
|
+
return Workspace(root=Path.cwd(), sandbox=args.sandbox, env=os.environ)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _confirm(ui: Ui, plan: dict[str, Any]) -> None:
|
|
284
|
+
if not sys.stdin.isatty():
|
|
285
|
+
raise PlanError(
|
|
286
|
+
"apply needs approval: run it in an interactive terminal, apply a saved plan file, or pass --auto-approve"
|
|
287
|
+
)
|
|
288
|
+
ui.out(
|
|
289
|
+
f"\nDo you want to perform these actions in the {plan['target']}?\n Only 'yes' will be accepted to approve.\n"
|
|
290
|
+
)
|
|
291
|
+
if input(" Enter a value: ").strip() != "yes":
|
|
292
|
+
raise PlanError("Apply cancelled.")
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def render_inventory(records: list[dict[str, Any]]) -> list[str]:
|
|
296
|
+
lines = []
|
|
297
|
+
for record in records:
|
|
298
|
+
kind = record["resource"]
|
|
299
|
+
if kind == "campaign":
|
|
300
|
+
depth, title = 0, f"campaign {record['campaign']}"
|
|
301
|
+
elif kind == "ad_group":
|
|
302
|
+
depth, title = 1, f"ad group {record['ad_group']}"
|
|
303
|
+
elif kind == "ad":
|
|
304
|
+
depth, title = 2, record["name"]
|
|
305
|
+
else:
|
|
306
|
+
depth, title = (2 if record.get("ad_group") else 1), f"{kind.replace('_', ' ')} {record['name']}"
|
|
307
|
+
details = f" {record['details']}" if record.get("details") else ""
|
|
308
|
+
lines.append(f"{' ' * depth}{title} [{record.get('status')}]{details}")
|
|
309
|
+
return lines
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def render_table(rows: list[dict[str, Any]]) -> list[str]:
|
|
313
|
+
columns = list(rows[0])
|
|
314
|
+
cells = [[str(row.get(column, "")) for column in columns] for row in rows]
|
|
315
|
+
widths = [max(len(column), *(len(row[i]) for row in cells)) for i, column in enumerate(columns)]
|
|
316
|
+
numeric = [all(_is_number(row[i]) for row in cells) for i in range(len(columns))]
|
|
317
|
+
|
|
318
|
+
def fmt(values: list[str]) -> str:
|
|
319
|
+
cells = zip(values, widths, numeric, strict=True)
|
|
320
|
+
return " ".join(v.rjust(w) if n else v.ljust(w) for v, w, n in cells).rstrip()
|
|
321
|
+
|
|
322
|
+
return [fmt(columns), fmt(["-" * w for w in widths]), *(fmt(row) for row in cells)]
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _is_number(value: str) -> bool:
|
|
326
|
+
try:
|
|
327
|
+
float(value)
|
|
328
|
+
except ValueError:
|
|
329
|
+
return False
|
|
330
|
+
return True
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# -- Parser ----------------------------------------------------------------------------------------
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
337
|
+
parser = argparse.ArgumentParser(
|
|
338
|
+
prog="adstack",
|
|
339
|
+
description="Advertising campaigns as code: declare campaigns in YAML, review a plan, apply it.",
|
|
340
|
+
epilog=f"Run 'adstack <command> --help' for a command's options. Documentation: {DOCS_URL}",
|
|
341
|
+
)
|
|
342
|
+
parser.add_argument("--version", action="version", version=f"adstack {__version__}")
|
|
343
|
+
commands = parser.add_subparsers(dest="command", required=True, metavar="<command>")
|
|
344
|
+
|
|
345
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
346
|
+
common.add_argument("--no-color", action="store_true", help="disable colored output (or set NO_COLOR)")
|
|
347
|
+
account = argparse.ArgumentParser(add_help=False)
|
|
348
|
+
account.add_argument(
|
|
349
|
+
"--sandbox",
|
|
350
|
+
action="store_true",
|
|
351
|
+
default=_env_flag("ADSTACK_SANDBOX"),
|
|
352
|
+
help="use a local sandbox account (.adstack/sandbox) instead of the real ad platform "
|
|
353
|
+
"(or set ADSTACK_SANDBOX=1)",
|
|
354
|
+
)
|
|
355
|
+
path_help = "configuration file or directory (default: the current directory)"
|
|
356
|
+
|
|
357
|
+
p = commands.add_parser(
|
|
358
|
+
"init",
|
|
359
|
+
parents=[common],
|
|
360
|
+
help="create a starter configuration",
|
|
361
|
+
description="Write an annotated starter configuration to DIRECTORY/adstack.yaml.",
|
|
362
|
+
)
|
|
363
|
+
p.add_argument("directory", nargs="?", default=".", help="where to create adstack.yaml (default: .)")
|
|
364
|
+
p.set_defaults(handler=cmd_init)
|
|
365
|
+
|
|
366
|
+
p = commands.add_parser(
|
|
367
|
+
"validate",
|
|
368
|
+
parents=[common],
|
|
369
|
+
help="check the configuration (offline)",
|
|
370
|
+
description="Validate the configuration without contacting the ad platform.",
|
|
371
|
+
)
|
|
372
|
+
p.add_argument("path", nargs="?", default=".", help=path_help)
|
|
373
|
+
p.add_argument("--json", action="store_true", help="print the result as JSON")
|
|
374
|
+
p.set_defaults(handler=cmd_validate)
|
|
375
|
+
|
|
376
|
+
p = commands.add_parser(
|
|
377
|
+
"plan",
|
|
378
|
+
parents=[common, account],
|
|
379
|
+
help="show what would change",
|
|
380
|
+
description="Read the account, compare it with the configuration and show the changes. Changes nothing.",
|
|
381
|
+
)
|
|
382
|
+
p.add_argument("path", nargs="?", default=".", help=path_help)
|
|
383
|
+
p.add_argument("-o", "--out", metavar="FILE", help="save the plan to FILE for 'adstack apply FILE'")
|
|
384
|
+
p.add_argument(
|
|
385
|
+
"--prune", action="store_true", help="pause or remove managed resources that are no longer in the configuration"
|
|
386
|
+
)
|
|
387
|
+
p.add_argument("--destroy", action="store_true", help="plan to pause every managed campaign")
|
|
388
|
+
p.add_argument(
|
|
389
|
+
"--validate",
|
|
390
|
+
action="store_true",
|
|
391
|
+
help="also ask the platform to validate the changes (validate-only; changes nothing)",
|
|
392
|
+
)
|
|
393
|
+
p.add_argument(
|
|
394
|
+
"--detailed-exitcode",
|
|
395
|
+
action="store_true",
|
|
396
|
+
help="exit 0 when there are no changes, 2 when there are changes, 1 on errors",
|
|
397
|
+
)
|
|
398
|
+
p.add_argument("--json", action="store_true", help="print the plan as JSON")
|
|
399
|
+
p.set_defaults(handler=cmd_plan)
|
|
400
|
+
|
|
401
|
+
gates = argparse.ArgumentParser(add_help=False)
|
|
402
|
+
gates.add_argument("--auto-approve", action="store_true", help="skip the interactive approval prompt")
|
|
403
|
+
gates.add_argument("--allow-live-changes", action="store_true", help="allow changes to campaigns that are serving")
|
|
404
|
+
|
|
405
|
+
p = commands.add_parser(
|
|
406
|
+
"apply",
|
|
407
|
+
parents=[common, account, gates],
|
|
408
|
+
help="apply a saved plan, or plan and apply after approval",
|
|
409
|
+
description="Apply a saved plan file (after verifying it is still current), or plan from a configuration "
|
|
410
|
+
"and apply after interactive approval.",
|
|
411
|
+
)
|
|
412
|
+
p.add_argument("target", nargs="?", default=".", help="a saved plan file, or a configuration file or directory")
|
|
413
|
+
p.add_argument(
|
|
414
|
+
"--prune",
|
|
415
|
+
action="store_true",
|
|
416
|
+
help="when planning: pause or remove resources that are not in the configuration",
|
|
417
|
+
)
|
|
418
|
+
p.add_argument("--destroy", action="store_true", help=argparse.SUPPRESS)
|
|
419
|
+
p.add_argument("--allow-enable", action="store_true", help="allow a paused campaign to start serving")
|
|
420
|
+
p.add_argument("--allow-budget-increase", action="store_true", help="allow budget or bid increases")
|
|
421
|
+
p.set_defaults(handler=cmd_apply)
|
|
422
|
+
|
|
423
|
+
p = commands.add_parser(
|
|
424
|
+
"destroy",
|
|
425
|
+
parents=[common, account, gates],
|
|
426
|
+
help="pause every campaign Adstack manages",
|
|
427
|
+
description="Plan to pause every campaign in the namespace, then apply after approval. Adstack never "
|
|
428
|
+
"deletes campaigns; remove them in the ad platform's interface if you need to.",
|
|
429
|
+
)
|
|
430
|
+
p.add_argument("path", nargs="?", default=".", help=path_help)
|
|
431
|
+
p.set_defaults(handler=cmd_destroy)
|
|
432
|
+
|
|
433
|
+
p = commands.add_parser("show", parents=[common], help="display a saved plan")
|
|
434
|
+
p.add_argument("plan", help="plan file created with 'adstack plan --out'")
|
|
435
|
+
p.add_argument("--json", action="store_true", help="print the plan as JSON")
|
|
436
|
+
p.set_defaults(handler=cmd_show)
|
|
437
|
+
|
|
438
|
+
p = commands.add_parser("state", help="inspect what Adstack manages in the account")
|
|
439
|
+
state = p.add_subparsers(dest="state_command", required=True, metavar="<subcommand>")
|
|
440
|
+
p = state.add_parser("list", parents=[common, account], help="list managed resources in the account")
|
|
441
|
+
p.add_argument("path", nargs="?", default=".", help=path_help)
|
|
442
|
+
p.add_argument("--json", action="store_true", help="print the resources as JSON")
|
|
443
|
+
p.set_defaults(handler=cmd_state_list)
|
|
444
|
+
|
|
445
|
+
p = commands.add_parser("report", parents=[common, account], help="performance and search-term reports")
|
|
446
|
+
p.add_argument("kind", choices=["performance", "search-terms"])
|
|
447
|
+
p.add_argument("path", nargs="?", default=".", help=path_help)
|
|
448
|
+
p.add_argument("--days", type=int, choices=[7, 14, 30], default=7, help="reporting window (default: 7)")
|
|
449
|
+
p.add_argument(
|
|
450
|
+
"--all-campaigns", action="store_true", help="include campaigns outside the configuration's namespace"
|
|
451
|
+
)
|
|
452
|
+
p.add_argument("--json", action="store_true", help="print rows as JSON")
|
|
453
|
+
p.set_defaults(handler=cmd_report)
|
|
454
|
+
|
|
455
|
+
p = commands.add_parser(
|
|
456
|
+
"mcp",
|
|
457
|
+
parents=[account],
|
|
458
|
+
help="run the MCP server (stdio) for AI assistants",
|
|
459
|
+
description="Serve Adstack's tools over the Model Context Protocol (stdio). Applying changes is disabled "
|
|
460
|
+
"unless --allow-apply is set or the server uses the sandbox.",
|
|
461
|
+
)
|
|
462
|
+
p.add_argument("--root", default=".", help="directory the tools may read configurations from (default: .)")
|
|
463
|
+
p.add_argument(
|
|
464
|
+
"--allow-apply",
|
|
465
|
+
action="store_true",
|
|
466
|
+
help="expose the apply tool for the real ad platform; or set ADSTACK_MCP_ALLOW_APPLY=1",
|
|
467
|
+
)
|
|
468
|
+
p.set_defaults(handler=cmd_mcp)
|
|
469
|
+
|
|
470
|
+
p = commands.add_parser("version", help="print the Adstack version")
|
|
471
|
+
p.set_defaults(handler=cmd_version)
|
|
472
|
+
return parser
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
if __name__ == "__main__":
|
|
476
|
+
raise SystemExit(main())
|
adstack/config.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Load an Adstack configuration: one YAML file, or a directory of YAML files.
|
|
2
|
+
|
|
3
|
+
Like a Terraform module, every ``*.yaml`` and ``*.yml`` file in a directory belongs
|
|
4
|
+
to one configuration. Files are merged: lists are concatenated (``campaigns``),
|
|
5
|
+
mappings are combined (``ad_templates`` may be split across files), and defining
|
|
6
|
+
the same key twice is an error. Each file must declare ``version: 1``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import yaml
|
|
17
|
+
|
|
18
|
+
from .errors import ConfigError
|
|
19
|
+
from .providers import get_provider
|
|
20
|
+
|
|
21
|
+
FORMAT_VERSION = 1
|
|
22
|
+
SUFFIXES = (".yaml", ".yml")
|
|
23
|
+
MAX_FILE_BYTES = 1_000_000
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Config:
|
|
28
|
+
"""A validated configuration."""
|
|
29
|
+
|
|
30
|
+
provider: str
|
|
31
|
+
"""Provider name, for example ``google_ads``."""
|
|
32
|
+
desired: dict[str, Any]
|
|
33
|
+
"""Provider-normalized desired state. JSON-serializable and deterministic."""
|
|
34
|
+
sources: dict[str, str]
|
|
35
|
+
"""Original file contents by file name. Saved plans embed them."""
|
|
36
|
+
|
|
37
|
+
def summary(self) -> str:
|
|
38
|
+
return get_provider(self.provider).summary(self.desired)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class _StrictLoader(yaml.SafeLoader):
|
|
42
|
+
"""A SafeLoader that rejects duplicate and non-string mapping keys."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _construct_mapping(loader: _StrictLoader, node: yaml.MappingNode) -> dict[str, Any]:
|
|
46
|
+
loader.flatten_mapping(node)
|
|
47
|
+
result: dict[str, Any] = {}
|
|
48
|
+
for key_node, value_node in node.value:
|
|
49
|
+
key = loader.construct_object(key_node)
|
|
50
|
+
line = key_node.start_mark.line + 1
|
|
51
|
+
if not isinstance(key, str):
|
|
52
|
+
raise ConfigError(f"line {line}: mapping keys must be strings, found {key!r}")
|
|
53
|
+
if key in result:
|
|
54
|
+
raise ConfigError(f"line {line}: duplicate key {key!r}")
|
|
55
|
+
result[key] = loader.construct_object(value_node)
|
|
56
|
+
return result
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
_StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_sources(path: str | os.PathLike[str]) -> dict[str, str]:
|
|
63
|
+
"""Read a configuration file, or every YAML file directly inside a directory."""
|
|
64
|
+
path = Path(path)
|
|
65
|
+
if path.is_dir():
|
|
66
|
+
files = sorted(p for p in path.iterdir() if p.is_file() and p.suffix in SUFFIXES and not p.name.startswith("."))
|
|
67
|
+
if not files:
|
|
68
|
+
raise ConfigError(f"{path}: no configuration files (*.yaml or *.yml) found")
|
|
69
|
+
elif path.is_file():
|
|
70
|
+
files = [path]
|
|
71
|
+
else:
|
|
72
|
+
raise ConfigError(f"{path}: no such file or directory")
|
|
73
|
+
sources = {}
|
|
74
|
+
for file in files:
|
|
75
|
+
if file.stat().st_size > MAX_FILE_BYTES:
|
|
76
|
+
raise ConfigError(f"{file.name}: larger than {MAX_FILE_BYTES:,} bytes")
|
|
77
|
+
try:
|
|
78
|
+
sources[file.name] = file.read_text(encoding="utf-8")
|
|
79
|
+
except UnicodeDecodeError:
|
|
80
|
+
raise ConfigError(f"{file.name}: not valid UTF-8 text") from None
|
|
81
|
+
return sources
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def load(path: str | os.PathLike[str]) -> Config:
|
|
85
|
+
"""Load and validate the configuration at ``path`` (a file or a directory)."""
|
|
86
|
+
return load_sources(read_sources(path))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def load_sources(sources: dict[str, str]) -> Config:
|
|
90
|
+
"""Validate configuration text, given as ``{file name: YAML text}``."""
|
|
91
|
+
if not sources:
|
|
92
|
+
raise ConfigError("no configuration files")
|
|
93
|
+
document: dict[str, Any] = {}
|
|
94
|
+
origins: dict[str, str] = {}
|
|
95
|
+
for name in sorted(sources):
|
|
96
|
+
_merge(document, origins, _parse(name, sources[name]), name)
|
|
97
|
+
providers = document.pop("provider", None)
|
|
98
|
+
if not isinstance(providers, dict) or len(providers) != 1:
|
|
99
|
+
raise ConfigError("provider: configure exactly one provider, for example 'provider: {google_ads: {...}}'")
|
|
100
|
+
((name, settings),) = providers.items()
|
|
101
|
+
provider = get_provider(name)
|
|
102
|
+
desired = provider.load(settings, document)
|
|
103
|
+
return Config(provider=name, desired=desired, sources=dict(sources))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _parse(name: str, text: str) -> dict[str, Any]:
|
|
107
|
+
try:
|
|
108
|
+
document = yaml.load(text, Loader=_StrictLoader)
|
|
109
|
+
except yaml.YAMLError as exc:
|
|
110
|
+
raise ConfigError(f"{name}: invalid YAML: {exc}") from None
|
|
111
|
+
except ConfigError as exc:
|
|
112
|
+
raise ConfigError(f"{name}: {exc}") from None
|
|
113
|
+
if not isinstance(document, dict):
|
|
114
|
+
raise ConfigError(f"{name}: expected a mapping that starts with 'version: {FORMAT_VERSION}'")
|
|
115
|
+
version = document.pop("version", None)
|
|
116
|
+
if type(version) is not int or version != FORMAT_VERSION:
|
|
117
|
+
raise ConfigError(f"{name}: 'version: {FORMAT_VERSION}' is required (the configuration format version)")
|
|
118
|
+
return document
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _merge(document: dict[str, Any], origins: dict[str, str], fragment: dict[str, Any], name: str) -> None:
|
|
122
|
+
for key, value in fragment.items():
|
|
123
|
+
if key not in document:
|
|
124
|
+
document[key] = value
|
|
125
|
+
origins[key] = name
|
|
126
|
+
if isinstance(value, dict):
|
|
127
|
+
for sub in value:
|
|
128
|
+
origins[f"{key}.{sub}"] = name
|
|
129
|
+
continue
|
|
130
|
+
current = document[key]
|
|
131
|
+
if isinstance(current, list) and isinstance(value, list):
|
|
132
|
+
document[key] = current + value
|
|
133
|
+
elif isinstance(current, dict) and isinstance(value, dict):
|
|
134
|
+
for sub, item in value.items():
|
|
135
|
+
where = f"{key}.{sub}"
|
|
136
|
+
if sub in current:
|
|
137
|
+
raise ConfigError(f"{where} is defined in both {origins[where]} and {name}")
|
|
138
|
+
current[sub] = item
|
|
139
|
+
origins[where] = name
|
|
140
|
+
else:
|
|
141
|
+
raise ConfigError(f"{key} is defined in both {origins[key]} and {name}")
|