everydaydevops-luff 3.0.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.
Files changed (40) hide show
  1. everydaydevops_luff-3.0.0.data/data/share/luff/skills/flutter-audit/SKILL.md +30 -0
  2. everydaydevops_luff-3.0.0.data/data/share/luff/skills/flutter-create/SKILL.md +27 -0
  3. everydaydevops_luff-3.0.0.data/data/share/luff/skills/flutter-feature/SKILL.md +30 -0
  4. everydaydevops_luff-3.0.0.data/data/share/luff/skills/flutter-migrate/SKILL.md +30 -0
  5. everydaydevops_luff-3.0.0.data/data/share/luff/skills/flutter-verify/SKILL.md +12 -0
  6. everydaydevops_luff-3.0.0.dist-info/METADATA +50 -0
  7. everydaydevops_luff-3.0.0.dist-info/RECORD +40 -0
  8. everydaydevops_luff-3.0.0.dist-info/WHEEL +5 -0
  9. everydaydevops_luff-3.0.0.dist-info/entry_points.txt +3 -0
  10. everydaydevops_luff-3.0.0.dist-info/licenses/LICENSE +21 -0
  11. everydaydevops_luff-3.0.0.dist-info/top_level.txt +1 -0
  12. flutter_setup/__init__.py +0 -0
  13. flutter_setup/appender.py +46 -0
  14. flutter_setup/bootstrap.py +1655 -0
  15. flutter_setup/cicd_generator.py +885 -0
  16. flutter_setup/cli.py +1193 -0
  17. flutter_setup/config.py +156 -0
  18. flutter_setup/config_manager.py +160 -0
  19. flutter_setup/core.py +204 -0
  20. flutter_setup/exceptions.py +37 -0
  21. flutter_setup/flutter_manager.py +579 -0
  22. flutter_setup/platform.py +15 -0
  23. flutter_setup/prerequisites.py +39 -0
  24. flutter_setup/prerequisites_linux.py +140 -0
  25. flutter_setup/prerequisites_macos.py +226 -0
  26. flutter_setup/project_cli.py +397 -0
  27. flutter_setup/project_creator.py +91 -0
  28. flutter_setup/standards.py +99 -0
  29. flutter_setup/standards_data/everyday-devops-flutter-1.0.0.json +97 -0
  30. flutter_setup/standards_data/manifest-v1.schema.json +209 -0
  31. flutter_setup/templates/everyday/AGENTS.md +5 -0
  32. flutter_setup/templates/everyday/app_log.dart +6 -0
  33. flutter_setup/templates/everyday/home_content.dart +9 -0
  34. flutter_setup/templates/everyday/home_repository.dart +8 -0
  35. flutter_setup/templates/everyday/home_screen.dart +60 -0
  36. flutter_setup/templates/everyday/offline_store.dart +5 -0
  37. flutter_setup/templates/everyday/sentry_startup.dart +16 -0
  38. flutter_setup/templates/everyday/theme.dart +12 -0
  39. flutter_setup/templates.py +73 -0
  40. flutter_setup/verification.py +160 -0
@@ -0,0 +1,1655 @@
1
+ """Project bootstrapping for Flutter setup."""
2
+
3
+ import re as _re
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+ from rich.console import Console
9
+
10
+ from .cicd_generator import CicdGenerator
11
+ from .config import Config
12
+ from .exceptions import ProjectCreationError
13
+ from .templates import apply_templates
14
+
15
+ console = Console()
16
+
17
+
18
+ def _extract_makefile_target_names(content: str) -> set[str]:
19
+ """Return set of target names defined in a Makefile."""
20
+ # Match 'name:' but NOT 'name:=' (variable assignment)
21
+ names = set(
22
+ _re.findall(r"^([a-zA-Z][a-zA-Z0-9_-]*)\s*:(?!=)", content, _re.MULTILINE)
23
+ )
24
+ names.discard(".PHONY")
25
+ return names
26
+
27
+
28
+ def _is_var_defined_in(line: str, content: str) -> bool:
29
+ """Return True if line is a variable assignment whose name is already defined in content."""
30
+ m = _re.match(r"^([A-Z_][A-Z0-9_]*)\s*[:?]?=", line)
31
+ if not m:
32
+ return False
33
+ var_name = m.group(1)
34
+ return bool(
35
+ _re.search(rf"^{_re.escape(var_name)}\s*[:?]?=", content, _re.MULTILINE)
36
+ )
37
+
38
+
39
+ def _filter_new_makefile_content(
40
+ new_content: str, existing_targets: set[str], existing_content: str = ""
41
+ ) -> str:
42
+ """Return parts of new_content not already present in the existing Makefile.
43
+
44
+ Target blocks whose names are in existing_targets are skipped. Preamble
45
+ variable lines are included only when their variable name is not already
46
+ defined in existing_content — ensuring appended targets that reference
47
+ $(FLUTTER), $(ANDROID_SDK_ROOT), etc. will find those variables.
48
+ """
49
+ blocks = _re.split(
50
+ r"(?=^[a-zA-Z][a-zA-Z0-9_-]*\s*:(?!=))", new_content, flags=_re.MULTILINE
51
+ )
52
+ result = []
53
+ for block in blocks:
54
+ if not block.strip():
55
+ continue
56
+ first_line = block.splitlines()[0] if block.splitlines() else ""
57
+ target_match = _re.match(r"^([a-zA-Z][a-zA-Z0-9_-]*)\s*:(?!=)", first_line)
58
+ if target_match:
59
+ target_name = target_match.group(1)
60
+ if target_name not in existing_targets:
61
+ result.append(block)
62
+ else:
63
+ # Preamble block: include variable lines not already defined
64
+ missing = [
65
+ line
66
+ for line in block.splitlines(keepends=True)
67
+ if not _is_var_defined_in(line, existing_content)
68
+ ]
69
+ if any(ln.strip() for ln in missing):
70
+ result.append("".join(missing))
71
+ return "".join(result)
72
+
73
+
74
+ class ProjectBootstrap:
75
+ """Bootstraps development environment for Flutter projects."""
76
+
77
+ def __init__(self, config: Config, force: bool = False) -> None:
78
+ """Initialize ProjectBootstrap."""
79
+ self.config = config
80
+ self.force = force
81
+ self.home = Path.home()
82
+ self.flutter_root = config.flutter_location
83
+
84
+ def bootstrap_project(self) -> None:
85
+ """Bootstrap the development environment."""
86
+ if self.config.dry_run:
87
+ console.print(
88
+ "[yellow]DRY RUN: Would bootstrap development environment[/yellow]"
89
+ )
90
+ return
91
+
92
+ console.print(" 🔧 Bootstrapping development & testing helpers...")
93
+
94
+ # Create VS Code/Cursor configuration
95
+ self._create_vscode_config()
96
+
97
+ # Create Makefile
98
+ self._create_makefile()
99
+
100
+ # Patch Android NDK version in build.gradle.kts
101
+ if "android" in self.config.platforms:
102
+ self._patch_android_ndk_version()
103
+
104
+ # Create test structure
105
+ self._create_test_structure()
106
+
107
+ # Create analysis options
108
+ self._create_analysis_options()
109
+
110
+ # Create optional architecture and persistence scaffolds
111
+ self._create_architecture_scaffold()
112
+
113
+ # Create CI/CD workflows and configuration
114
+ self._create_cicd()
115
+
116
+ # Add dependencies
117
+ self._add_dependencies()
118
+
119
+ # Create optional end-to-end test scaffolds
120
+ self._create_e2e_scaffold()
121
+
122
+ # Update pubspec description (flutter create leaves a generic placeholder)
123
+ self._update_pubspec_description()
124
+
125
+ # Create environment support (.env file + gitignore entry; NOT added to assets)
126
+ self._create_environment_support()
127
+
128
+ # Pin Flutter SDK version in pubspec.yaml
129
+ ver = self.config.flutter_version or self._detect_flutter_version()
130
+ if ver:
131
+ self._pin_flutter_sdk_version(ver)
132
+
133
+ # Re-run pub get after all pubspec.yaml modifications are complete so
134
+ # packages added by yaml.dump-based edits (integration_test, .env asset,
135
+ # flutter version pin) are resolved before the user's first make target.
136
+ self._run_pub_get()
137
+
138
+ # Run build_runner for projects that require code generation (Drift,
139
+ # Riverpod, Freezed) so the project compiles immediately after setup.
140
+ if self.config.database == "sqlite" or self.config.architecture == "clean":
141
+ self._run_build_runner()
142
+
143
+ # Create README (append section if file already exists)
144
+ self._append_readme()
145
+
146
+ if self.config.managed:
147
+ apply_templates(self.config)
148
+ self._use_scaffold_material_import()
149
+ if self._uses_firebase():
150
+ with (self.config.project_path / "README.md").open(
151
+ "a", encoding="utf-8"
152
+ ) as file:
153
+ file.write(
154
+ "\n## Firebase\n\nConfigure your Firebase project with FlutterFire "
155
+ "before using the generated adapters. Start the app with "
156
+ "`flutter run --dart-define=LUFF_FIREBASE_ENABLED=true` only "
157
+ "after supplying native configuration.\n"
158
+ )
159
+
160
+ # Format code
161
+ self._format_code()
162
+
163
+ def _use_scaffold_material_import(self) -> None:
164
+ root = self.config.project_path
165
+ pubspec = yaml.safe_load((root / "pubspec.yaml").read_text())
166
+ if "material_ui" not in pubspec.get("dependencies", {}):
167
+ return
168
+ for directory in ("lib", "test", "integration_test"):
169
+ for dart in (root / directory).rglob("*.dart"):
170
+ source = dart.read_text()
171
+ updated = source.replace(
172
+ "package:flutter/material.dart",
173
+ "package:material_ui/material_ui.dart",
174
+ )
175
+ if updated != source:
176
+ dart.write_text(updated)
177
+
178
+ def _create_vscode_config(self) -> None:
179
+ """Create VS Code/Cursor configuration files."""
180
+ vscode_dir = self.config.project_path / ".vscode"
181
+ vscode_dir.mkdir(exist_ok=True)
182
+
183
+ # Settings
184
+ settings = {
185
+ "dart.flutterHotReloadOnSave": "all",
186
+ "dart.lineLength": 100,
187
+ "editor.formatOnSave": True,
188
+ "editor.defaultFormatter": "Dart-Code.dart-code",
189
+ "files.exclude": {"**/.dart_tool": True, "**/build": True},
190
+ }
191
+
192
+ import json
193
+
194
+ with open(vscode_dir / "settings.json", "w") as f:
195
+ json.dump(settings, f, indent=2)
196
+
197
+ # Launch configuration
198
+ launch_config = {
199
+ "version": "0.2.0",
200
+ "configurations": [
201
+ {"name": "Flutter Debug", "request": "launch", "type": "dart"}
202
+ ],
203
+ }
204
+
205
+ with open(vscode_dir / "launch.json", "w") as f:
206
+ json.dump(launch_config, f, indent=2)
207
+
208
+ console.print(" ✅ VS Code/Cursor configuration created")
209
+
210
+ def _detect_flutter_version(self) -> str | None:
211
+ """Return the version string of the Flutter SDK at config.flutter_location."""
212
+ import re
213
+
214
+ flutter_bin = self.config.flutter_location / "bin" / "flutter"
215
+ try:
216
+ result = subprocess.run(
217
+ [str(flutter_bin), "--version"],
218
+ capture_output=True,
219
+ **self.config.sdk_subprocess_options(),
220
+ text=True,
221
+ check=False,
222
+ )
223
+ output = result.stdout or result.stderr or ""
224
+ match = re.search(r"Flutter\s+([\d.]+)", output)
225
+ if match:
226
+ return match.group(1)
227
+ except Exception:
228
+ pass
229
+ return None
230
+
231
+ def _build_makefile_content(self) -> str:
232
+ """Build and return the Makefile content string."""
233
+ ver = self.config.flutter_version or self._detect_flutter_version()
234
+ flutter_home = str(self.config.flutter_location)
235
+
236
+ if ver:
237
+ version_header = (
238
+ f"FLUTTER_HOME := {flutter_home}\n"
239
+ f'FLUTTER := "$(FLUTTER_HOME)/bin/flutter"\n'
240
+ f"FLUTTER_REQUIRED_VERSION := {ver}\n\n"
241
+ )
242
+ version_dep = " check-flutter-version"
243
+ version_target = """
244
+ check-flutter-version:
245
+ \t@ACTUAL=$$($(FLUTTER) --version 2>&1 | awk '/^Flutter [0-9]/{print $$2; exit}'); \\
246
+ \tif [ -z "$$ACTUAL" ]; then \\
247
+ \t\techo "ERROR: Could not determine Flutter version at $(FLUTTER_HOME)"; exit 1; \\
248
+ \tfi; \\
249
+ \techo " Detected Flutter $$ACTUAL (required: >=$(FLUTTER_REQUIRED_VERSION))"; \\
250
+ \tawk -v a="$$ACTUAL" -v r="$(FLUTTER_REQUIRED_VERSION)" 'BEGIN{split(a,av,".");split(r,rv,".");for(i=1;i<=3;i++){sub(/[^0-9].*/,"",av[i]);sub(/[^0-9].*/,"",rv[i])};if(av[1]+0>rv[1]+0)exit 0;if(av[1]+0<rv[1]+0)exit 1;if(av[2]+0>rv[2]+0)exit 0;if(av[2]+0<rv[2]+0)exit 1;if(av[3]+0>=rv[3]+0)exit 0;exit 1}' /dev/null || \\
251
+ \t{ echo "ERROR: Flutter $$ACTUAL does not satisfy >=$$FLUTTER_REQUIRED_VERSION"; exit 1; }
252
+
253
+ .PHONY: check-flutter-version
254
+ """
255
+ else:
256
+ version_header = ""
257
+ version_dep = ""
258
+ version_target = ""
259
+
260
+ flutter_cmd = "$(FLUTTER)" if ver else "flutter"
261
+
262
+ generate_target = ""
263
+ codegen_dep = ""
264
+ if self.config.database == "sqlite" or self.config.architecture == "clean":
265
+ generate_target = f"""
266
+ generate:{version_dep}
267
+ \tdart run build_runner build --delete-conflicting-outputs
268
+ """
269
+ codegen_dep = " generate"
270
+
271
+ web_target = ""
272
+ if "web" in self.config.platforms:
273
+ web_target = f"run-chrome:{version_dep}\n\t{flutter_cmd} run -d chrome\n\n"
274
+
275
+ android_sdk_header = ""
276
+ android_sdk_dep = ""
277
+ android_sdk_target = ""
278
+ if "android" in self.config.platforms:
279
+ android_sdk_header = (
280
+ "ANDROID_SDK_ROOT ?= $(or $(ANDROID_HOME),/opt/android-sdk)\n"
281
+ "SDKMANAGER := $(ANDROID_SDK_ROOT)/cmdline-tools/latest/bin/sdkmanager\n"
282
+ "AVDMANAGER := $(ANDROID_SDK_ROOT)/cmdline-tools/latest/bin/avdmanager\n"
283
+ "REQUIRED_NDK := 27.0.12077973\n"
284
+ "REQUIRED_BUILD_TOOLS := 34.0.0\n"
285
+ "REQUIRED_CMAKE := 3.22.1\n"
286
+ "ANDROID_AVD_NAME := flutter_dev\n"
287
+ "ANDROID_API_LEVEL := 35\n"
288
+ "ANDROID_AVD_DEVICE := pixel_6\n"
289
+ "ANDROID_SYSTEM_IMAGE := system-images;android-$(ANDROID_API_LEVEL);google_apis;x86_64\n\n"
290
+ )
291
+ android_sdk_dep = " check-android-sdk"
292
+ android_sdk_target = """
293
+ check-android-sdk:
294
+ \t@if [ ! -f "$(ANDROID_SDK_ROOT)/ndk/$(REQUIRED_NDK)/source.properties" ]; then \\
295
+ \t\techo "NDK $(REQUIRED_NDK) missing or incomplete, installing..."; \\
296
+ \t\t$(SDKMANAGER) "ndk;$(REQUIRED_NDK)"; \\
297
+ \telse \\
298
+ \t\techo "NDK $(REQUIRED_NDK) ok"; \\
299
+ \tfi
300
+ \t@if [ ! -d "$(ANDROID_SDK_ROOT)/build-tools/$(REQUIRED_BUILD_TOOLS)" ]; then \\
301
+ \t\techo "Build-Tools $(REQUIRED_BUILD_TOOLS) missing, installing..."; \\
302
+ \t\t$(SDKMANAGER) "build-tools;$(REQUIRED_BUILD_TOOLS)"; \\
303
+ \telse \\
304
+ \t\techo "Build-Tools $(REQUIRED_BUILD_TOOLS) ok"; \\
305
+ \tfi
306
+ \t@if [ ! -d "$(ANDROID_SDK_ROOT)/cmake/$(REQUIRED_CMAKE)" ]; then \\
307
+ \t\techo "CMake $(REQUIRED_CMAKE) missing, installing..."; \\
308
+ \t\t$(SDKMANAGER) "cmake;$(REQUIRED_CMAKE)"; \\
309
+ \telse \\
310
+ \t\techo "CMake $(REQUIRED_CMAKE) ok"; \\
311
+ \tfi
312
+
313
+ .PHONY: check-android-sdk
314
+
315
+ setup-emulator:
316
+ \t@if $(AVDMANAGER) list avd | grep -q "Name: $(ANDROID_AVD_NAME)"; then \\
317
+ \t\techo "Emulator '$(ANDROID_AVD_NAME)' already exists"; \\
318
+ \telse \\
319
+ \t\techo "Installing system image $(ANDROID_SYSTEM_IMAGE)..."; \\
320
+ \t\t$(SDKMANAGER) "$(ANDROID_SYSTEM_IMAGE)"; \\
321
+ \t\techo "Creating emulator '$(ANDROID_AVD_NAME)'..."; \\
322
+ \t\techo no | $(AVDMANAGER) create avd --name "$(ANDROID_AVD_NAME)" --package "$(ANDROID_SYSTEM_IMAGE)" --device "$(ANDROID_AVD_DEVICE)"; \\
323
+ \tfi
324
+
325
+ .PHONY: setup-emulator
326
+ """
327
+
328
+ if "android" in self.config.platforms:
329
+ run_android_emulator_check = (
330
+ '\t@if ! adb devices | grep -q "^emulator"; then \\\n'
331
+ '\t\techo "No emulator running, launching $(ANDROID_AVD_NAME)..."; \\\n'
332
+ f"\t\t{flutter_cmd} emulators --launch $(ANDROID_AVD_NAME); \\\n"
333
+ '\t\techo "Waiting for emulator to boot..."; \\\n'
334
+ '\t\tadb -e wait-for-device && adb -e shell \'while [ "$$(getprop sys.boot_completed)" != "1" ]; do sleep 2; done\'; \\\n'
335
+ '\t\techo "Emulator ready."; \\\n'
336
+ "\tfi\n"
337
+ )
338
+ else:
339
+ run_android_emulator_check = ""
340
+
341
+ ios_target = ""
342
+ if "ios" in self.config.platforms:
343
+ ios_target = f"run-ios:{version_dep}\n\t{flutter_cmd} run -d ios\n\n"
344
+
345
+ android_target = ""
346
+ if "android" in self.config.platforms:
347
+ android_target = (
348
+ f"run-android:{version_dep}{android_sdk_dep}\n"
349
+ f"{run_android_emulator_check}\t{flutter_cmd} run -d emulator\n\n"
350
+ )
351
+
352
+ e2e_targets = self._build_e2e_makefile_targets(version_dep, codegen_dep)
353
+
354
+ return f"""{version_header}{android_sdk_header}{web_target}{ios_target}{android_target}analyze:{version_dep}{codegen_dep}
355
+ \t{flutter_cmd} analyze
356
+
357
+ test:{version_dep}{codegen_dep}
358
+ \t{flutter_cmd} test
359
+
360
+ integration:{version_dep}{codegen_dep}
361
+ \t{flutter_cmd} test integration_test
362
+
363
+ {e2e_targets}
364
+ upgrade:{version_dep}
365
+ \t{flutter_cmd} pub upgrade
366
+
367
+ upgrade-check:{version_dep}
368
+ \t{flutter_cmd} pub get
369
+ {generate_target}{android_sdk_target}{version_target}"""
370
+
371
+ def _build_e2e_makefile_targets(self, version_dep: str, codegen_dep: str) -> str:
372
+ """Return optional Makefile targets for selected end-to-end tooling."""
373
+ if self.config.e2e_testing != "patrol":
374
+ return ""
375
+
376
+ return f"""patrol-test:{version_dep}{codegen_dep}
377
+ \tpatrol test -t patrol_test/app_test.dart
378
+
379
+ patrol-doctor:
380
+ \tpatrol doctor
381
+ """
382
+
383
+ def _create_makefile(self) -> None:
384
+ """Create Makefile with common commands."""
385
+ # Always lock the project to the Flutter version present at creation time.
386
+ # --flutter-version provides an explicit pin; otherwise detect from the SDK.
387
+ makefile_content = self._build_makefile_content()
388
+
389
+ with open(self.config.project_path / "Makefile", "w") as f:
390
+ f.write(makefile_content)
391
+
392
+ console.print(" ✅ Makefile created")
393
+
394
+ def _append_vscode_config(self) -> None:
395
+ """Append VS Code/Cursor configuration files, skipping existing unless --force."""
396
+ import json
397
+
398
+ vscode_dir = self.config.project_path / ".vscode"
399
+ vscode_dir.mkdir(exist_ok=True)
400
+
401
+ settings = {
402
+ "dart.flutterHotReloadOnSave": "all",
403
+ "dart.lineLength": 100,
404
+ "editor.formatOnSave": True,
405
+ "editor.defaultFormatter": "Dart-Code.dart-code",
406
+ "files.exclude": {"**/.dart_tool": True, "**/build": True},
407
+ }
408
+ settings_file = vscode_dir / "settings.json"
409
+ if settings_file.exists() and not self.force:
410
+ console.print(
411
+ " ⚠️ .vscode/settings.json already exists — skipping (use --force to overwrite)"
412
+ )
413
+ else:
414
+ settings_file.write_text(json.dumps(settings, indent=2))
415
+ console.print(" ✅ .vscode/settings.json written")
416
+
417
+ launch_config = {
418
+ "version": "0.2.0",
419
+ "configurations": [
420
+ {"name": "Flutter Debug", "request": "launch", "type": "dart"}
421
+ ],
422
+ }
423
+ launch_file = vscode_dir / "launch.json"
424
+ if launch_file.exists() and not self.force:
425
+ console.print(
426
+ " ⚠️ .vscode/launch.json already exists — skipping (use --force to overwrite)"
427
+ )
428
+ else:
429
+ launch_file.write_text(json.dumps(launch_config, indent=2))
430
+ console.print(" ✅ .vscode/launch.json written")
431
+
432
+ def _append_makefile(self) -> None:
433
+ """Append missing Makefile targets, or create Makefile if absent."""
434
+ new_content = self._build_makefile_content()
435
+ makefile = self.config.project_path / "Makefile"
436
+
437
+ if not makefile.exists():
438
+ makefile.write_text(new_content)
439
+ console.print(" ✅ Makefile created")
440
+ return
441
+
442
+ existing = makefile.read_text()
443
+ existing_targets = _extract_makefile_target_names(existing)
444
+ to_append = _filter_new_makefile_content(
445
+ new_content, existing_targets, existing
446
+ )
447
+
448
+ if to_append:
449
+ with open(makefile, "a") as f:
450
+ f.write("\n# Added by flutter-setup\n")
451
+ f.write(to_append)
452
+ console.print(" ✅ Makefile targets appended")
453
+ else:
454
+ console.print(
455
+ " ℹ️ Makefile already has all flutter-setup targets — nothing to append"
456
+ )
457
+
458
+ def append_project(self) -> None:
459
+ """Append flutter-setup tooling to an existing project directory."""
460
+ if self.config.dry_run:
461
+ console.print(
462
+ "[yellow]DRY RUN: Would append flutter-setup tooling[/yellow]"
463
+ )
464
+ return
465
+ console.print(" 🔧 Appending flutter-setup tooling...")
466
+ self._append_vscode_config()
467
+ self._append_makefile()
468
+ self._create_e2e_scaffold()
469
+ self._create_cicd()
470
+ self._append_readme()
471
+ console.print(" ✅ Tooling appended")
472
+
473
+ def _patch_android_ndk_version(self) -> None:
474
+ """Pin the Android NDK version in build.gradle.kts.
475
+
476
+ flutter create sets ndkVersion = flutter.ndkVersion (currently 26.x), but
477
+ path_provider_android and sqlite3_flutter_libs require NDK 27.0.12077973.
478
+ NDK versions are backward-compatible, so pinning to the highest required
479
+ version fixes the mismatch warning and avoids a failed build.
480
+ """
481
+ gradle_path = self.config.project_path / "android" / "app" / "build.gradle.kts"
482
+ if not gradle_path.exists():
483
+ return
484
+
485
+ content = gradle_path.read_text()
486
+ patched = content.replace(
487
+ "ndkVersion = flutter.ndkVersion",
488
+ 'ndkVersion = "27.0.12077973"',
489
+ )
490
+ if patched != content:
491
+ gradle_path.write_text(patched)
492
+ console.print(" ✅ Android NDK version pinned in build.gradle.kts")
493
+
494
+ def _create_test_structure(self) -> None:
495
+ """Create test directory structure."""
496
+ test_dir = self.config.project_path / "test"
497
+ test_dir.mkdir(exist_ok=True)
498
+
499
+ # Remove the stale counter test that `flutter create` generates; it
500
+ # references `MyApp` which doesn't exist in the scaffolded project.
501
+ default_test = test_dir / "widget_test.dart"
502
+ if default_test.exists():
503
+ default_test.unlink()
504
+
505
+ # Unit test directory
506
+ unit_dir = test_dir / "unit"
507
+ unit_dir.mkdir(exist_ok=True)
508
+
509
+ # Widget test directory
510
+ widget_dir = test_dir / "widget"
511
+ widget_dir.mkdir(exist_ok=True)
512
+
513
+ # Integration test directory
514
+ integration_dir = self.config.project_path / "integration_test"
515
+ integration_dir.mkdir(exist_ok=True)
516
+
517
+ # Create sample tests
518
+ self._create_sample_tests()
519
+
520
+ console.print(" ✅ Test structure created")
521
+
522
+ def _create_sample_tests(self) -> None:
523
+ """Create sample test files."""
524
+ # Unit test
525
+ unit_test = """import 'package:flutter_test/flutter_test.dart';
526
+
527
+ void main() {
528
+ test('sanity check', () {
529
+ expect(1 + 1, equals(2));
530
+ });
531
+ }
532
+ """
533
+
534
+ with open(
535
+ self.config.project_path / "test" / "unit" / "sanity_test.dart", "w"
536
+ ) as f:
537
+ f.write(unit_test)
538
+
539
+ app_import = f"package:{self.config.package_name}/main.dart"
540
+ app_widget = "MyApp"
541
+ riverpod_import = ""
542
+ pump_widget = f"const {app_widget}()"
543
+ if self.config.architecture == "clean":
544
+ app_import = f"package:{self.config.package_name}/src/app/app.dart"
545
+ app_widget = "App"
546
+ riverpod_import = (
547
+ "import 'package:flutter_riverpod/flutter_riverpod.dart';\n"
548
+ )
549
+ pump_widget = f"const ProviderScope(child: {app_widget}())"
550
+
551
+ # Widget test
552
+ if self.config.architecture == "clean":
553
+ widget_assertion = "expect(find.text('Home'), findsOneWidget);"
554
+ else:
555
+ widget_assertion = f"expect(find.byType({app_widget}), findsOneWidget);"
556
+
557
+ widget_test = f"""import 'package:flutter_test/flutter_test.dart';
558
+ {riverpod_import}import '{app_import}';
559
+
560
+ void main() {{
561
+ testWidgets('App loads without errors', (tester) async {{
562
+ await tester.pumpWidget({pump_widget});
563
+ await tester.pumpAndSettle();
564
+ {widget_assertion}
565
+ }});
566
+ }}
567
+ """
568
+
569
+ with open(
570
+ self.config.project_path / "test" / "widget" / "app_widget_test.dart", "w"
571
+ ) as f:
572
+ f.write(widget_test)
573
+
574
+ # Integration test
575
+ if self.config.architecture == "clean":
576
+ integration_assertion = "expect(find.text('Home'), findsOneWidget);"
577
+ else:
578
+ integration_assertion = (
579
+ f"expect(find.byType({app_widget}), findsOneWidget);"
580
+ )
581
+
582
+ integration_test = f"""import 'package:flutter_dotenv/flutter_dotenv.dart';
583
+ import 'package:flutter_test/flutter_test.dart';
584
+ import 'package:integration_test/integration_test.dart';
585
+ {riverpod_import}import '{app_import}';
586
+
587
+ void main() {{
588
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
589
+
590
+ setUpAll(() async {{
591
+ await dotenv.load(fileName: '.env', isOptional: true);
592
+ }});
593
+
594
+ testWidgets('home page renders', (tester) async {{
595
+ await tester.pumpWidget({pump_widget});
596
+ await tester.pumpAndSettle();
597
+ {integration_assertion}
598
+ }});
599
+ }}
600
+ """
601
+
602
+ with open(
603
+ self.config.project_path / "integration_test" / "app_test.dart", "w"
604
+ ) as f:
605
+ f.write(integration_test)
606
+
607
+ def _create_e2e_scaffold(self) -> None:
608
+ """Create optional end-to-end test scaffolds."""
609
+ if self.config.e2e_testing == "patrol":
610
+ self._create_patrol_scaffold()
611
+
612
+ def _create_patrol_scaffold(self) -> None:
613
+ """Create Patrol end-to-end test support."""
614
+ self._create_patrol_sample_test()
615
+ self._add_patrol_to_pubspec()
616
+ self._add_patrol_config_to_pubspec()
617
+ self._add_patrol_to_gitignore()
618
+ console.print(" ✅ Patrol end-to-end scaffold created")
619
+
620
+ def _create_patrol_sample_test(self) -> None:
621
+ """Create a sample Patrol test unless one already exists."""
622
+ patrol_dir = self.config.project_path / "patrol_test"
623
+ patrol_dir.mkdir(exist_ok=True)
624
+ test_file = patrol_dir / "app_test.dart"
625
+ if test_file.exists() and not self.force:
626
+ return
627
+
628
+ app_import = f"package:{self.config.package_name}/main.dart"
629
+ app_widget = "MyApp"
630
+ riverpod_import = ""
631
+ pump_widget = f"const {app_widget}()"
632
+ if self.config.architecture == "clean":
633
+ app_import = f"package:{self.config.package_name}/src/app/app.dart"
634
+ app_widget = "App"
635
+ riverpod_import = (
636
+ "import 'package:flutter_riverpod/flutter_riverpod.dart';\n"
637
+ )
638
+ pump_widget = f"const ProviderScope(child: {app_widget}())"
639
+
640
+ assertion = (
641
+ "expect(find.text('Home'), findsOneWidget);"
642
+ if self.config.architecture == "clean"
643
+ else f"expect(find.byType({app_widget}), findsOneWidget);"
644
+ )
645
+
646
+ test_file.write_text(f"""import 'package:flutter_dotenv/flutter_dotenv.dart';
647
+ import 'package:flutter_test/flutter_test.dart';
648
+ import 'package:patrol/patrol.dart';
649
+ {riverpod_import}import '{app_import}';
650
+
651
+ void main() {{
652
+ setUpAll(() async {{
653
+ await dotenv.load(fileName: '.env', isOptional: true);
654
+ }});
655
+
656
+ patrolTest('home page renders', ($) async {{
657
+ await $.pumpWidgetAndSettle({pump_widget});
658
+ {assertion}
659
+ }});
660
+ }}
661
+ """)
662
+
663
+ def _create_analysis_options(self) -> None:
664
+ """Create analysis options file."""
665
+ analysis_content = """include: package:flutter_lints/flutter.yaml
666
+
667
+ linter:
668
+ rules:
669
+ avoid_print: false
670
+ prefer_const_constructors: true
671
+ """
672
+
673
+ with open(self.config.project_path / "analysis_options.yaml", "w") as f:
674
+ f.write(analysis_content)
675
+
676
+ console.print(" ✅ Analysis options created")
677
+
678
+ def _create_architecture_scaffold(self) -> None:
679
+ """Create optional reusable application architecture scaffolds."""
680
+ if self.config.architecture == "clean":
681
+ self._create_clean_architecture_scaffold()
682
+
683
+ if self.config.database == "sqlite":
684
+ self._create_sqlite_scaffold()
685
+
686
+ if self.config.testing == "mocktail":
687
+ self._create_mocktail_scaffold()
688
+
689
+ if self._uses_firebase():
690
+ self._create_firebase_scaffold()
691
+
692
+ def _uses_firebase(self) -> bool:
693
+ """Return whether any Firebase integration was selected."""
694
+ return (
695
+ self.config.auth_provider == "firebase"
696
+ or self.config.cloud_database == "firestore"
697
+ or self.config.notifications_provider == "firebase"
698
+ )
699
+
700
+ def _create_clean_architecture_scaffold(self) -> None:
701
+ """Create a Clean Architecture starter layout."""
702
+ src_dir = self.config.project_path / "lib" / "src"
703
+ directories = [
704
+ src_dir / "app",
705
+ src_dir / "core" / "error",
706
+ src_dir / "core" / "routing",
707
+ src_dir / "core" / "theme",
708
+ src_dir / "features" / "home" / "data",
709
+ src_dir / "features" / "home" / "domain",
710
+ src_dir / "features" / "home" / "presentation",
711
+ self.config.project_path / "test" / "features" / "home",
712
+ ]
713
+
714
+ for directory in directories:
715
+ directory.mkdir(parents=True, exist_ok=True)
716
+
717
+ (src_dir / "app" / "router.dart").write_text(
718
+ """import 'package:go_router/go_router.dart';
719
+
720
+ import '../features/home/presentation/home_screen.dart';
721
+
722
+ final router = GoRouter(
723
+ routes: [
724
+ GoRoute(
725
+ path: '/',
726
+ builder: (context, state) => const HomeScreen(),
727
+ ),
728
+ ],
729
+ );
730
+ """
731
+ )
732
+
733
+ safe_title = self.config.project_name.replace("'", "\\'")
734
+ (src_dir / "app" / "app.dart").write_text(
735
+ f"""import 'package:flutter/material.dart';
736
+
737
+ import 'router.dart';
738
+
739
+ class App extends StatelessWidget {{
740
+ const App({{super.key}});
741
+
742
+ @override
743
+ Widget build(BuildContext context) {{
744
+ return MaterialApp.router(
745
+ title: '{safe_title}',
746
+ theme: ThemeData(useMaterial3: true),
747
+ routerConfig: router,
748
+ );
749
+ }}
750
+ }}
751
+ """
752
+ )
753
+
754
+ (
755
+ src_dir / "features" / "home" / "presentation" / "home_screen.dart"
756
+ ).write_text(
757
+ """import 'package:flutter/material.dart';
758
+
759
+ class HomeScreen extends StatelessWidget {
760
+ const HomeScreen({super.key});
761
+
762
+ @override
763
+ Widget build(BuildContext context) {
764
+ return const Scaffold(
765
+ body: Center(
766
+ child: Text('Home'),
767
+ ),
768
+ );
769
+ }
770
+ }
771
+ """
772
+ )
773
+
774
+ (src_dir / "core" / "error" / "app_failure.dart").write_text(
775
+ """class AppFailure {
776
+ const AppFailure(this.message);
777
+
778
+ final String message;
779
+ }
780
+ """
781
+ )
782
+
783
+ firebase_import = ""
784
+ firebase_init = ""
785
+ if self._uses_firebase():
786
+ firebase_import = "import 'src/core/firebase/firebase_initializer.dart';\n"
787
+ firebase_init = (
788
+ " if (const bool.fromEnvironment('LUFF_FIREBASE_ENABLED')) {\n"
789
+ " await initializeFirebase();\n"
790
+ " }\n"
791
+ if self.config.managed
792
+ else " await initializeFirebase();\n"
793
+ )
794
+
795
+ main_dart = self.config.project_path / "lib" / "main.dart"
796
+ if main_dart.exists():
797
+ main_dart.write_text(f"""import 'package:flutter/material.dart';
798
+ import 'package:flutter_dotenv/flutter_dotenv.dart';
799
+ import 'package:flutter_riverpod/flutter_riverpod.dart';
800
+
801
+ {firebase_import}\
802
+ import 'src/app/app.dart';
803
+
804
+ Future<void> main() async {{
805
+ WidgetsFlutterBinding.ensureInitialized();
806
+ await dotenv.load(fileName: '.env', isOptional: true);
807
+ {firebase_init}\
808
+ runApp(const ProviderScope(child: App()));
809
+ }}
810
+ """)
811
+
812
+ self._create_assets_scaffold()
813
+
814
+ console.print(" ✅ Clean Architecture scaffold created")
815
+
816
+ def _create_assets_scaffold(self) -> None:
817
+ """Create assets/ directories and declare them in pubspec.yaml.
818
+
819
+ Uses .gitkeep sentinels so the empty directories are tracked in git.
820
+ """
821
+ assets_root = self.config.project_path / "assets"
822
+ asset_dirs = [
823
+ assets_root / "images",
824
+ assets_root / "fonts",
825
+ ]
826
+ for asset_dir in asset_dirs:
827
+ asset_dir.mkdir(parents=True, exist_ok=True)
828
+ (asset_dir / ".gitkeep").touch()
829
+
830
+ pubspec_path = self.config.project_path / "pubspec.yaml"
831
+ if not pubspec_path.exists():
832
+ return
833
+ try:
834
+ with open(pubspec_path, "r") as f:
835
+ pubspec = yaml.safe_load(f) or {}
836
+ flutter_section = pubspec.setdefault("flutter", {})
837
+ assets = flutter_section.setdefault("assets", [])
838
+ if "assets/images/" not in assets:
839
+ assets.append("assets/images/")
840
+ with open(pubspec_path, "w") as f:
841
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
842
+ console.print(" ✅ Assets directories created")
843
+ except Exception as e:
844
+ console.print(f" ⚠️ Failed to declare assets in pubspec.yaml: {e}")
845
+
846
+ def _create_sqlite_scaffold(self) -> None:
847
+ """Create a Drift/SQLite starter database scaffold."""
848
+ data_dir = self.config.project_path / "lib" / "src" / "core" / "data"
849
+ data_dir.mkdir(parents=True, exist_ok=True)
850
+
851
+ (data_dir / "app_database.dart").write_text("""import 'dart:io';
852
+
853
+ import 'package:drift/drift.dart';
854
+ import 'package:drift/native.dart';
855
+ import 'package:path/path.dart' as p;
856
+ import 'package:path_provider/path_provider.dart';
857
+
858
+ part 'app_database.g.dart';
859
+
860
+ class AppSettings extends Table {
861
+ TextColumn get key => text()();
862
+ TextColumn get value => text()();
863
+ DateTimeColumn get updatedAt => dateTime().withDefault(currentDateAndTime)();
864
+
865
+ @override
866
+ Set<Column<Object>> get primaryKey => {key};
867
+ }
868
+
869
+ @DriftDatabase(tables: [AppSettings])
870
+ class AppDatabase extends _$AppDatabase {
871
+ AppDatabase() : super(_openConnection());
872
+
873
+ @override
874
+ int get schemaVersion => 1;
875
+
876
+ @override
877
+ MigrationStrategy get migration => MigrationStrategy(
878
+ onCreate: (m) => m.createAll(),
879
+ onUpgrade: (m, from, to) async {
880
+ throw UnimplementedError('Add migration steps for v$from -> v$to');
881
+ },
882
+ );
883
+ }
884
+
885
+ LazyDatabase _openConnection() {
886
+ return LazyDatabase(() async {
887
+ final dbFolder = await getApplicationDocumentsDirectory();
888
+ final file = File(p.join(dbFolder.path, 'app.sqlite'));
889
+ return NativeDatabase.createInBackground(file);
890
+ });
891
+ }
892
+ """)
893
+
894
+ console.print(" ✅ SQLite persistence scaffold created")
895
+
896
+ def _create_mocktail_scaffold(self) -> None:
897
+ """Create shared mocktail test helpers."""
898
+ helpers_dir = self.config.project_path / "test" / "helpers"
899
+ helpers_dir.mkdir(parents=True, exist_ok=True)
900
+
901
+ (helpers_dir / "mocks.dart").write_text(
902
+ """import 'package:mocktail/mocktail.dart';
903
+
904
+ class MockRepository extends Mock {}
905
+ """
906
+ )
907
+
908
+ console.print(" ✅ Mocktail testing scaffold created")
909
+
910
+ def _create_firebase_scaffold(self) -> None:
911
+ """Create Firebase integration starter files."""
912
+ firebase_dir = self.config.project_path / "lib" / "src" / "core" / "firebase"
913
+ firebase_dir.mkdir(parents=True, exist_ok=True)
914
+
915
+ (firebase_dir / "firebase_initializer.dart").write_text(
916
+ """import 'package:firebase_core/firebase_core.dart';
917
+
918
+ Future<void> initializeFirebase() async {
919
+ await Firebase.initializeApp();
920
+ }
921
+ """
922
+ )
923
+
924
+ if self.config.auth_provider == "firebase":
925
+ (firebase_dir / "firebase_auth_service.dart").write_text(
926
+ """import 'package:firebase_auth/firebase_auth.dart';
927
+
928
+ class FirebaseAuthService {
929
+ FirebaseAuthService({FirebaseAuth? auth}) : _auth = auth ?? FirebaseAuth.instance;
930
+
931
+ final FirebaseAuth _auth;
932
+
933
+ Stream<User?> authStateChanges() => _auth.authStateChanges();
934
+ }
935
+ """
936
+ )
937
+
938
+ if self.config.cloud_database == "firestore":
939
+ (firebase_dir / "firestore_database.dart").write_text(
940
+ """import 'package:cloud_firestore/cloud_firestore.dart';
941
+
942
+ class FirestoreDatabase {
943
+ FirestoreDatabase({FirebaseFirestore? firestore})
944
+ : _firestore = firestore ?? FirebaseFirestore.instance;
945
+
946
+ final FirebaseFirestore _firestore;
947
+
948
+ CollectionReference<Map<String, dynamic>> collection(String path) {
949
+ return _firestore.collection(path);
950
+ }
951
+ }
952
+ """
953
+ )
954
+
955
+ if self.config.notifications_provider == "firebase":
956
+ (firebase_dir / "firebase_notifications_service.dart").write_text(
957
+ """import 'package:firebase_messaging/firebase_messaging.dart';
958
+
959
+ class FirebaseNotificationsService {
960
+ FirebaseNotificationsService({FirebaseMessaging? messaging})
961
+ : _messaging = messaging ?? FirebaseMessaging.instance;
962
+
963
+ final FirebaseMessaging _messaging;
964
+
965
+ Future<NotificationSettings> requestPermission() {
966
+ return _messaging.requestPermission();
967
+ }
968
+
969
+ Future<String?> getToken() {
970
+ return _messaging.getToken();
971
+ }
972
+ }
973
+ """
974
+ )
975
+
976
+ console.print(" ✅ Firebase integration scaffold created")
977
+
978
+ def _create_cicd(self) -> None:
979
+ """Create CI/CD workflows and configuration."""
980
+ cicd_generator = CicdGenerator(self.config, force=self.force)
981
+ cicd_generator.generate_cicd()
982
+
983
+ def _add_dependencies(self) -> None:
984
+ """Add required dependencies to the project."""
985
+ try:
986
+ for dependency in self._runtime_dependencies():
987
+ subprocess.run(
988
+ [
989
+ str(self.flutter_root / "bin" / "flutter"),
990
+ "pub",
991
+ "add",
992
+ dependency,
993
+ ],
994
+ cwd=self.config.project_path,
995
+ check=self.config.managed,
996
+ capture_output=True,
997
+ **self.config.sdk_subprocess_options(),
998
+ )
999
+
1000
+ for dependency in self._dev_dependencies():
1001
+ subprocess.run(
1002
+ [
1003
+ str(self.flutter_root / "bin" / "flutter"),
1004
+ "pub",
1005
+ "add",
1006
+ "--dev",
1007
+ dependency,
1008
+ ],
1009
+ cwd=self.config.project_path,
1010
+ check=self.config.managed,
1011
+ capture_output=True,
1012
+ **self.config.sdk_subprocess_options(),
1013
+ )
1014
+
1015
+ # Add integration_test as SDK dependency by directly editing pubspec.yaml
1016
+ # flutter pub add doesn't correctly handle SDK dependencies
1017
+ self._add_integration_test_sdk_dependency()
1018
+
1019
+ # Ensure drift_dev is in pubspec.yaml for sqlite projects even if
1020
+ # flutter pub add failed silently in restricted environments
1021
+ if self.config.database == "sqlite":
1022
+ self._add_drift_dev_to_pubspec()
1023
+ # drift_dev >=2.31 requires analyzer >=8.1; flutter_riverpod >=3
1024
+ # pins analyzer <8.0 on Dart 3.8. Both resolve on Dart >=3.9.
1025
+ if self.config.architecture == "clean":
1026
+ self._ensure_dart_sdk_39_for_drift_riverpod()
1027
+
1028
+ console.print(" ✅ Dependencies added")
1029
+
1030
+ except Exception as e:
1031
+ if self.config.managed:
1032
+ details = getattr(e, "stderr", None)
1033
+ if isinstance(details, bytes):
1034
+ details = details.decode(errors="replace")
1035
+ raise ProjectCreationError(str(details or e)) from e
1036
+ console.print(f" ⚠️ Dependency addition warning: {e}")
1037
+
1038
+ def _runtime_dependencies(self) -> list[str]:
1039
+ """Return runtime dependencies required by selected scaffolds."""
1040
+ dependencies = ["flutter_dotenv"]
1041
+
1042
+ if self.config.architecture == "clean":
1043
+ dependencies.extend(
1044
+ [
1045
+ "flutter_riverpod",
1046
+ "riverpod_annotation",
1047
+ "go_router",
1048
+ "freezed_annotation",
1049
+ "json_annotation",
1050
+ "collection",
1051
+ "intl",
1052
+ "uuid",
1053
+ ]
1054
+ )
1055
+
1056
+ if self.config.database == "sqlite":
1057
+ dependencies.extend(
1058
+ ["drift", "sqlite3_flutter_libs", "path_provider", "path"]
1059
+ )
1060
+
1061
+ if self._uses_firebase():
1062
+ dependencies.append("firebase_core")
1063
+
1064
+ if self.config.auth_provider == "firebase":
1065
+ dependencies.append("firebase_auth")
1066
+
1067
+ if self.config.cloud_database == "firestore":
1068
+ dependencies.append("cloud_firestore")
1069
+
1070
+ if self.config.notifications_provider == "firebase":
1071
+ dependencies.append("firebase_messaging")
1072
+
1073
+ if self.config.sentry:
1074
+ dependencies.append("sentry_flutter")
1075
+
1076
+ return dependencies
1077
+
1078
+ def _dev_dependencies(self) -> list[str]:
1079
+ """Return dev dependencies required by selected scaffolds."""
1080
+ dependencies = ["flutter_lints"]
1081
+
1082
+ if self.config.architecture == "clean":
1083
+ # build_runner is required to run riverpod_generator, freezed, and
1084
+ # json_serializable — add it here so clean-arch projects without
1085
+ # sqlite still get code generation support.
1086
+ dependencies.extend(
1087
+ ["riverpod_generator", "freezed", "json_serializable", "build_runner"]
1088
+ )
1089
+
1090
+ if self.config.database == "sqlite":
1091
+ dependencies.extend(["drift_dev", "build_runner"])
1092
+
1093
+ if self.config.testing == "mocktail":
1094
+ dependencies.append("mocktail")
1095
+
1096
+ if self.config.e2e_testing == "patrol":
1097
+ dependencies.append("patrol")
1098
+
1099
+ return dependencies
1100
+
1101
+ _GENERIC_PUBSPEC_DESCRIPTION = "A new Flutter project."
1102
+
1103
+ def _update_pubspec_description(self) -> None:
1104
+ """Replace the generic flutter-create description in pubspec.yaml.
1105
+
1106
+ Only overwrites the known placeholder left by `flutter create` so that
1107
+ re-running bootstrap does not clobber a description the developer has
1108
+ already customised.
1109
+ """
1110
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1111
+ if not pubspec_path.exists():
1112
+ return
1113
+ try:
1114
+ with open(pubspec_path, "r") as f:
1115
+ pubspec = yaml.safe_load(f) or {}
1116
+ if pubspec.get("description") != self._GENERIC_PUBSPEC_DESCRIPTION:
1117
+ return
1118
+ pubspec["description"] = (
1119
+ f"A {self.config.project_name} Flutter application."
1120
+ )
1121
+ with open(pubspec_path, "w") as f:
1122
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1123
+ console.print(" ✅ pubspec description updated")
1124
+ except Exception as e:
1125
+ console.print(f" ⚠️ Failed to update pubspec description: {e}")
1126
+
1127
+ def _pin_flutter_sdk_version(self, version: str) -> None:
1128
+ """Set the flutter SDK constraint in pubspec.yaml to >= the given version."""
1129
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1130
+ if not pubspec_path.exists():
1131
+ console.print(" ⚠️ pubspec.yaml not found, skipping Flutter version pin")
1132
+ return
1133
+
1134
+ try:
1135
+ with open(pubspec_path, "r") as f:
1136
+ pubspec = yaml.safe_load(f) or {}
1137
+
1138
+ if "environment" not in pubspec:
1139
+ pubspec["environment"] = {}
1140
+ pubspec["environment"]["flutter"] = f">={version}"
1141
+
1142
+ with open(pubspec_path, "w") as f:
1143
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1144
+
1145
+ console.print(f" ✅ Pinned flutter SDK to >={version} in pubspec.yaml")
1146
+ except Exception as e:
1147
+ console.print(f" ⚠️ Failed to pin Flutter version in pubspec.yaml: {e}")
1148
+
1149
+ def _add_integration_test_sdk_dependency(self) -> None:
1150
+ """Add integration_test as an SDK dependency to pubspec.yaml."""
1151
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1152
+ if not pubspec_path.exists():
1153
+ console.print(" ⚠️ pubspec.yaml not found, skipping integration_test")
1154
+ return
1155
+
1156
+ try:
1157
+ # Read pubspec.yaml
1158
+ with open(pubspec_path, "r") as f:
1159
+ pubspec = yaml.safe_load(f) or {}
1160
+
1161
+ # Ensure dev_dependencies section exists
1162
+ if "dev_dependencies" not in pubspec:
1163
+ pubspec["dev_dependencies"] = {}
1164
+
1165
+ # Check if integration_test already exists
1166
+ existing = pubspec["dev_dependencies"].get("integration_test")
1167
+ if (
1168
+ existing
1169
+ and isinstance(existing, dict)
1170
+ and existing.get("sdk") == "flutter"
1171
+ ):
1172
+ # Already correctly configured, skip
1173
+ return
1174
+
1175
+ # Add or update integration_test with SDK specification
1176
+ pubspec["dev_dependencies"]["integration_test"] = {"sdk": "flutter"}
1177
+
1178
+ # Write back to pubspec.yaml
1179
+ with open(pubspec_path, "w") as f:
1180
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1181
+
1182
+ except Exception as e:
1183
+ console.print(f" ⚠️ Failed to add integration_test SDK dependency: {e}")
1184
+
1185
+ def _add_patrol_to_pubspec(self) -> None:
1186
+ """Ensure Patrol is present in pubspec.yaml dev_dependencies."""
1187
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1188
+ if not pubspec_path.exists():
1189
+ console.print(" ⚠️ pubspec.yaml not found, skipping Patrol dependency")
1190
+ return
1191
+
1192
+ try:
1193
+ with open(pubspec_path, "r") as f:
1194
+ pubspec = yaml.safe_load(f) or {}
1195
+ dev_deps = pubspec.setdefault("dev_dependencies", {})
1196
+ if "patrol" in dev_deps:
1197
+ return
1198
+ dev_deps["patrol"] = "any"
1199
+ with open(pubspec_path, "w") as f:
1200
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1201
+ except Exception as e:
1202
+ console.print(f" ⚠️ Failed to add Patrol dependency: {e}")
1203
+
1204
+ def _add_patrol_config_to_pubspec(self) -> None:
1205
+ """Ensure the Patrol pubspec.yaml section exists."""
1206
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1207
+ if not pubspec_path.exists():
1208
+ console.print(" ⚠️ pubspec.yaml not found, skipping Patrol config")
1209
+ return
1210
+
1211
+ try:
1212
+ with open(pubspec_path, "r") as f:
1213
+ pubspec = yaml.safe_load(f) or {}
1214
+ original = yaml.dump(pubspec, default_flow_style=False, sort_keys=False)
1215
+ patrol_config = pubspec.setdefault("patrol", {})
1216
+ patrol_config.setdefault("app_name", self.config.project_name)
1217
+ # Apple bundle identifiers must not contain underscores.
1218
+ safe_package = self.config.package_name.replace("_", "-")
1219
+ package_id = f"{self.config.org}.{safe_package}"
1220
+ android_id = f"{self.config.org}.{self.config.package_name}"
1221
+ if "android" in self.config.platforms:
1222
+ android = patrol_config.setdefault("android", {})
1223
+ android.setdefault("package_name", android_id)
1224
+ if "ios" in self.config.platforms:
1225
+ ios = patrol_config.setdefault("ios", {})
1226
+ ios.setdefault("bundle_id", package_id)
1227
+ if "macos" in self.config.platforms:
1228
+ macos = patrol_config.setdefault("macos", {})
1229
+ macos.setdefault("bundle_id", package_id)
1230
+ updated = yaml.dump(pubspec, default_flow_style=False, sort_keys=False)
1231
+ if updated == original:
1232
+ return
1233
+ with open(pubspec_path, "w") as f:
1234
+ f.write(updated)
1235
+ except Exception as e:
1236
+ console.print(f" ⚠️ Failed to add Patrol config: {e}")
1237
+
1238
+ def _add_drift_dev_to_pubspec(self) -> None:
1239
+ """Write drift_dev directly to pubspec.yaml dev_dependencies for sqlite projects.
1240
+
1241
+ flutter pub add can silently fail in some environments; this guarantees
1242
+ the entry is present regardless. The version constraint is derived from
1243
+ the runtime drift package so the code-generator version always matches.
1244
+ """
1245
+ import re
1246
+
1247
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1248
+ if not pubspec_path.exists():
1249
+ return
1250
+ try:
1251
+ with open(pubspec_path, "r") as f:
1252
+ pubspec = yaml.safe_load(f) or {}
1253
+ dev_deps = pubspec.setdefault("dev_dependencies", {})
1254
+ if "drift_dev" not in dev_deps:
1255
+ # Pin drift_dev to the same full version as the runtime drift
1256
+ # package: drift_dev must match drift's minor version since each
1257
+ # minor release may add new codegen features the old generator
1258
+ # doesn't know about. e.g. drift: ^2.31.0 -> drift_dev: ^2.31.0
1259
+ drift_constraint = pubspec.get("dependencies", {}).get("drift", "")
1260
+ match = re.match(r"[\^~]?(\d+\.\d+\.\d+)", str(drift_constraint))
1261
+ version = f"^{match.group(1)}" if match else "any"
1262
+ dev_deps["drift_dev"] = version
1263
+ with open(pubspec_path, "w") as f:
1264
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1265
+ except Exception as e:
1266
+ console.print(f" ⚠️ Failed to add drift_dev to pubspec.yaml: {e}")
1267
+
1268
+ def _ensure_dart_sdk_39_for_drift_riverpod(self) -> None:
1269
+ """Bump the Dart SDK constraint to ^3.9.0 when clean+sqlite are both selected.
1270
+
1271
+ drift_dev >=2.31 requires analyzer >=8.1; flutter_riverpod >=3 pulls
1272
+ analyzer <8.0 on Dart 3.8, making pub get fail. Both packages align on
1273
+ analyzer ^9.0.0 starting with Dart 3.9 (released August 2025).
1274
+ """
1275
+ import re
1276
+
1277
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1278
+ if not pubspec_path.exists():
1279
+ return
1280
+ try:
1281
+ with open(pubspec_path, "r") as f:
1282
+ pubspec = yaml.safe_load(f) or {}
1283
+ env = pubspec.setdefault("environment", {})
1284
+ sdk_constraint = str(env.get("sdk", ""))
1285
+ match = re.search(r"(\d+)\.(\d+)", sdk_constraint)
1286
+ if match:
1287
+ major, minor = int(match.group(1)), int(match.group(2))
1288
+ if (major, minor) < (3, 9):
1289
+ env["sdk"] = "^3.9.0"
1290
+ with open(pubspec_path, "w") as f:
1291
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1292
+ console.print(
1293
+ " ✅ Bumped Dart SDK to ^3.9.0 "
1294
+ "(drift_dev + flutter_riverpod require Dart >=3.9)"
1295
+ )
1296
+ except Exception as e:
1297
+ console.print(f" ⚠️ Failed to update Dart SDK constraint: {e}")
1298
+
1299
+ def _create_environment_support(self) -> None:
1300
+ """Create environment variable support."""
1301
+ env_example_content = """# Environment variables — copy to .env and fill in real values.
1302
+ # .env is gitignored; .env.example is checked in as a reference.
1303
+ API_URL=https://api.example.com
1304
+ """
1305
+ env_content = """# Local environment variables (gitignored — never commit real secrets).
1306
+ API_URL=https://api.example.com
1307
+ """
1308
+
1309
+ env_example = self.config.project_path / ".env.example"
1310
+ if not env_example.exists():
1311
+ env_example.write_text(env_example_content)
1312
+
1313
+ env_file = self.config.project_path / ".env"
1314
+ if not env_file.exists():
1315
+ env_file.write_text(env_content)
1316
+
1317
+ # Keep .env out of version control
1318
+ self._add_env_to_gitignore()
1319
+
1320
+ # .env is intentionally NOT added to pubspec.yaml assets: bundling it
1321
+ # would hard-fail CI builds on a clean checkout (file is gitignored).
1322
+ # Add it manually and remove from .gitignore when you need runtime env vars,
1323
+ # or use --dart-define-from-file for build-time injection.
1324
+
1325
+ # Modify main.dart to load .env
1326
+ self._modify_main_dart()
1327
+
1328
+ console.print(" ✅ Environment support created")
1329
+
1330
+ def _add_env_to_gitignore(self) -> None:
1331
+ """Ensure .env is listed in .gitignore."""
1332
+ gitignore_path = self.config.project_path / ".gitignore"
1333
+ entry = ".env\n"
1334
+ if gitignore_path.exists():
1335
+ content = gitignore_path.read_text()
1336
+ lines = content.splitlines()
1337
+ if any(line.strip() == ".env" for line in lines):
1338
+ return
1339
+ with open(gitignore_path, "a") as f:
1340
+ if content and not content.endswith("\n"):
1341
+ f.write("\n")
1342
+ f.write("\n# Environment variables\n")
1343
+ f.write(entry)
1344
+ else:
1345
+ gitignore_path.write_text(f"# Environment variables\n{entry}")
1346
+
1347
+ def _add_patrol_to_gitignore(self) -> None:
1348
+ """Ensure Patrol-generated files and local secrets are gitignored."""
1349
+ gitignore_path = self.config.project_path / ".gitignore"
1350
+ entries = ["**/test_bundle.dart", ".patrol.env"]
1351
+ existing = gitignore_path.read_text() if gitignore_path.exists() else ""
1352
+ existing_lines = {line.strip() for line in existing.splitlines()}
1353
+ missing = [entry for entry in entries if entry not in existing_lines]
1354
+ if not missing:
1355
+ return
1356
+
1357
+ if gitignore_path.exists():
1358
+ with open(gitignore_path, "a") as f:
1359
+ if existing and not existing.endswith("\n"):
1360
+ f.write("\n")
1361
+ f.write("\n# Patrol\n")
1362
+ for entry in missing:
1363
+ f.write(f"{entry}\n")
1364
+ else:
1365
+ gitignore_path.write_text(
1366
+ "# Patrol\n" + "".join(f"{entry}\n" for entry in missing)
1367
+ )
1368
+
1369
+ def _add_env_asset_to_pubspec(self) -> None:
1370
+ """Add .env to the flutter assets list in pubspec.yaml."""
1371
+ pubspec_path = self.config.project_path / "pubspec.yaml"
1372
+ if not pubspec_path.exists():
1373
+ return
1374
+ try:
1375
+ with open(pubspec_path, "r") as f:
1376
+ pubspec = yaml.safe_load(f) or {}
1377
+ flutter_section = pubspec.setdefault("flutter", {})
1378
+ assets = flutter_section.setdefault("assets", [])
1379
+ if ".env" not in assets:
1380
+ assets.append(".env")
1381
+ with open(pubspec_path, "w") as f:
1382
+ yaml.dump(pubspec, f, default_flow_style=False, sort_keys=False)
1383
+ except Exception as e:
1384
+ console.print(f" ⚠️ Failed to add .env to pubspec.yaml assets: {e}")
1385
+
1386
+ def _modify_main_dart(self) -> None:
1387
+ """Modify main.dart to load environment variables."""
1388
+ main_dart = self.config.project_path / "lib" / "main.dart"
1389
+
1390
+ if not main_dart.exists():
1391
+ return
1392
+
1393
+ try:
1394
+ with open(main_dart, "r") as f:
1395
+ content = f.read()
1396
+
1397
+ # Add import if not present
1398
+ if "flutter_dotenv" not in content:
1399
+ # Find first import line
1400
+ lines = content.split("\n")
1401
+ import_index = -1
1402
+ for i, line in enumerate(lines):
1403
+ if line.strip().startswith("import ") and "package:flutter" in line:
1404
+ import_index = i
1405
+ break
1406
+
1407
+ if import_index >= 0:
1408
+ lines.insert(
1409
+ import_index + 1,
1410
+ "import 'package:flutter_dotenv/flutter_dotenv.dart';",
1411
+ )
1412
+ else:
1413
+ lines.insert(
1414
+ 0, "import 'package:flutter_dotenv/flutter_dotenv.dart';"
1415
+ )
1416
+
1417
+ # Modify main function
1418
+ modified_content = "\n".join(lines)
1419
+ modified_content = modified_content.replace(
1420
+ "void main() {",
1421
+ 'Future<void> main() async {\n await dotenv.load(fileName: ".env", isOptional: true);',
1422
+ )
1423
+
1424
+ with open(main_dart, "w") as f:
1425
+ f.write(modified_content)
1426
+
1427
+ if self._uses_firebase():
1428
+ content = main_dart.read_text()
1429
+ if "firebase_initializer.dart" not in content:
1430
+ lines = content.split("\n")
1431
+ import_index = -1
1432
+ for i, line in enumerate(lines):
1433
+ if line.strip().startswith("import "):
1434
+ import_index = i
1435
+
1436
+ firebase_import = (
1437
+ "import 'src/core/firebase/firebase_initializer.dart';"
1438
+ )
1439
+ if import_index >= 0:
1440
+ lines.insert(import_index + 1, firebase_import)
1441
+ else:
1442
+ lines.insert(0, firebase_import)
1443
+
1444
+ modified_content = "\n".join(lines)
1445
+ if "await dotenv.load" in modified_content:
1446
+ modified_content = modified_content.replace(
1447
+ ' await dotenv.load(fileName: ".env", isOptional: true);',
1448
+ ' await dotenv.load(fileName: ".env", isOptional: true);\n'
1449
+ " await initializeFirebase();",
1450
+ )
1451
+ elif "Future<void> main() async {" in modified_content:
1452
+ modified_content = modified_content.replace(
1453
+ "Future<void> main() async {",
1454
+ "Future<void> main() async {\n"
1455
+ " await initializeFirebase();",
1456
+ )
1457
+
1458
+ if self.config.managed:
1459
+ modified_content = modified_content.replace(
1460
+ " await initializeFirebase();",
1461
+ " if (const bool.fromEnvironment('LUFF_FIREBASE_ENABLED')) {\n"
1462
+ " await initializeFirebase();\n"
1463
+ " }",
1464
+ )
1465
+ main_dart.write_text(modified_content)
1466
+
1467
+ if self.config.managed:
1468
+ content = main_dart.read_text()
1469
+ if "WidgetsFlutterBinding.ensureInitialized();" not in content:
1470
+ main_dart.write_text(
1471
+ content.replace(
1472
+ "Future<void> main() async {",
1473
+ "Future<void> main() async {\n WidgetsFlutterBinding.ensureInitialized();",
1474
+ 1,
1475
+ )
1476
+ )
1477
+
1478
+ except Exception as e:
1479
+ console.print(f" ⚠️ Main.dart modification warning: {e}")
1480
+
1481
+ def _build_readme_section(self) -> str:
1482
+ """Return the flutter-setup tooling section for README.md."""
1483
+ if "web" in self.config.platforms:
1484
+ run_cmd = "make run-chrome # runs on Chrome"
1485
+ elif "ios" in self.config.platforms:
1486
+ run_cmd = "make run-ios # runs on iOS simulator"
1487
+ elif "android" in self.config.platforms:
1488
+ run_cmd = "make run-android # runs on Android emulator"
1489
+ else:
1490
+ run_cmd = "flutter run"
1491
+
1492
+ codegen_section = ""
1493
+ if self.config.database == "sqlite" or self.config.architecture == "clean":
1494
+ codegen_section = """
1495
+ ### Code generation
1496
+ This project uses `build_runner` for code generation (Drift, Riverpod, Freezed).
1497
+ Generation runs automatically during setup. To re-run manually:
1498
+ ```bash
1499
+ make generate
1500
+ ```
1501
+ """
1502
+
1503
+ e2e_commands = "make integration # Flutter SDK integration_test/"
1504
+ if self.config.e2e_testing == "patrol":
1505
+ e2e_commands += """
1506
+ make patrol-test # Patrol native end-to-end tests
1507
+ make patrol-doctor # Patrol environment diagnostics"""
1508
+
1509
+ return f"""## flutter-setup
1510
+
1511
+ ### Quickstart
1512
+ ```bash
1513
+ flutter pub get
1514
+ {run_cmd}
1515
+ ```
1516
+ {codegen_section}
1517
+ ### Testing
1518
+ ```bash
1519
+ make test # unit + widget tests
1520
+ ```
1521
+
1522
+ ### End-to-End Testing
1523
+ ```bash
1524
+ {e2e_commands}
1525
+ ```
1526
+
1527
+ ### Linting
1528
+ ```bash
1529
+ make analyze
1530
+ ```
1531
+
1532
+ ### Env vars
1533
+ Copy `.env.example` to `.env` and fill in values. The file is gitignored and
1534
+ not bundled as an asset by default, so `dotenv.env['KEY']` returns null until
1535
+ you either add `.env` to `pubspec.yaml` assets (and remove it from `.gitignore`),
1536
+ or use `--dart-define-from-file=.env.json` for build-time injection.
1537
+
1538
+ ### Scaffold configuration
1539
+ - Architecture: `{self.config.architecture}`
1540
+ - Database: `{self.config.database}`
1541
+ - Testing: `{self.config.testing}`
1542
+ - End-to-end testing: `{self.config.e2e_testing}`
1543
+ - Auth provider: `{self.config.auth_provider}`
1544
+ - Cloud database: `{self.config.cloud_database}`
1545
+ - Notifications: `{self.config.notifications_provider}`
1546
+ """
1547
+
1548
+ def _create_readme(self) -> None:
1549
+ """Create README file."""
1550
+ readme_path = self.config.project_path / "README.md"
1551
+ if readme_path.exists():
1552
+ console.print(
1553
+ " ⚠️ README.md already exists — skipping (use append to add a section)"
1554
+ )
1555
+ return
1556
+
1557
+ readme_content = (
1558
+ f"# {self.config.project_name}\n\nFlutter app scaffolded for Cursor.\n\n"
1559
+ + self._build_readme_section()
1560
+ )
1561
+ readme_path.write_text(readme_content)
1562
+ console.print(" ✅ README created")
1563
+
1564
+ def _append_readme(self) -> None:
1565
+ """Append a flutter-setup section to an existing README, or create one."""
1566
+ readme_path = self.config.project_path / "README.md"
1567
+ section = self._build_readme_section()
1568
+ if not readme_path.exists():
1569
+ readme_path.write_text(f"# {self.config.project_name}\n\n" + section)
1570
+ console.print(" ✅ README created")
1571
+ else:
1572
+ existing = readme_path.read_text()
1573
+ if "## flutter-setup" in existing:
1574
+ console.print(
1575
+ " ⚠️ README.md already has a flutter-setup section — skipping"
1576
+ )
1577
+ else:
1578
+ with open(readme_path, "a") as f:
1579
+ f.write("\n" + section)
1580
+ console.print(" ✅ flutter-setup section appended to README.md")
1581
+
1582
+ def _run_pub_get(self) -> None:
1583
+ """Run flutter pub get after all pubspec.yaml modifications are complete."""
1584
+ try:
1585
+ subprocess.run(
1586
+ [str(self.flutter_root / "bin" / "flutter"), "pub", "get"],
1587
+ cwd=self.config.project_path,
1588
+ check=self.config.managed,
1589
+ capture_output=True,
1590
+ **self.config.sdk_subprocess_options(),
1591
+ )
1592
+ console.print(" ✅ flutter pub get completed")
1593
+ except Exception as e:
1594
+ if self.config.managed:
1595
+ details = getattr(e, "stderr", None)
1596
+ if isinstance(details, bytes):
1597
+ details = details.decode(errors="replace")
1598
+ raise ProjectCreationError(str(details or e)) from e
1599
+ console.print(f" ⚠️ flutter pub get warning: {e}")
1600
+
1601
+ def _run_build_runner(self) -> None:
1602
+ """Run build_runner to generate code for Drift, Riverpod, and Freezed.
1603
+
1604
+ Projects using sqlite or clean architecture include code-generated files
1605
+ (*.g.dart, *.freezed.dart). Without this step the project will not
1606
+ compile on first checkout.
1607
+ """
1608
+ try:
1609
+ result = subprocess.run(
1610
+ [
1611
+ str(self.flutter_root / "bin" / "dart"),
1612
+ "run",
1613
+ "build_runner",
1614
+ "build",
1615
+ "--delete-conflicting-outputs",
1616
+ ],
1617
+ cwd=self.config.project_path,
1618
+ check=self.config.managed,
1619
+ capture_output=True,
1620
+ **self.config.sdk_subprocess_options(),
1621
+ )
1622
+ if result.returncode == 0:
1623
+ console.print(" ✅ Code generation completed (build_runner)")
1624
+ else:
1625
+ stderr = result.stderr.decode(errors="replace") if result.stderr else ""
1626
+ console.print(
1627
+ f" ⚠️ build_runner exited with code {result.returncode}"
1628
+ + (f": {stderr.strip()}" if stderr.strip() else "")
1629
+ )
1630
+ except Exception as e:
1631
+ if self.config.managed:
1632
+ details = getattr(e, "stderr", None)
1633
+ if isinstance(details, bytes):
1634
+ details = details.decode(errors="replace")
1635
+ raise ProjectCreationError(str(details or e)) from e
1636
+ console.print(f" ⚠️ build_runner warning: {e}")
1637
+
1638
+ def _format_code(self) -> None:
1639
+ """Format the generated code."""
1640
+ try:
1641
+ subprocess.run(
1642
+ [str(self.flutter_root / "bin" / "dart"), "format", "."],
1643
+ cwd=self.config.project_path,
1644
+ check=self.config.managed,
1645
+ capture_output=True,
1646
+ **self.config.sdk_subprocess_options(),
1647
+ )
1648
+ console.print(" ✅ Code formatted")
1649
+ except Exception as e:
1650
+ if self.config.managed:
1651
+ details = getattr(e, "stderr", None)
1652
+ if isinstance(details, bytes):
1653
+ details = details.decode(errors="replace")
1654
+ raise ProjectCreationError(str(details or e)) from e
1655
+ console.print(f" ⚠️ Code formatting warning: {e}")