-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModule.cfc
More file actions
2795 lines (2470 loc) · 93.1 KB
/
Module.cfc
File metadata and controls
2795 lines (2470 loc) · 93.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Wheels CLI Module for LuCLI
*
* Provides code generation, migrations, testing, and server management
* for CFWheels applications. Each public function is a subcommand:
*
* wheels new myapp
* wheels create app myapp --port=3000
* wheels generate model User name email
* wheels migrate latest
* wheels test --filter=models
* wheels start
*
* hint: CFWheels framework CLI - create, generate, migrate, test, and manage your app
*/
component extends="modules.BaseModule" {
function init(
boolean verboseEnabled = false,
boolean timingEnabled = false,
string cwd = "",
any timer = nullValue(),
struct moduleConfig = {}
) {
super.init(argumentCollection = arguments);
// Resolve project root (where lucee.json / vendor/wheels lives)
variables.projectRoot = resolveProjectRoot(arguments.cwd);
// Module root for template resolution
variables.moduleRoot = getDirectoryFromPath(getCurrentTemplatePath());
// Lazy-init service instances
variables.services = {};
return this;
}
// ─────────────────────────────────────────────────
// generate — Code generation
// ─────────────────────────────────────────────────
/**
* hint: Generate Wheels components (model, controller, view, migration, scaffold, route, test, property, api-resource, helper, snippets)
*/
public string function generate() {
var args = __arguments ?: [];
if (!arrayLen(args)) {
out("Usage: wheels generate <type> <name> [attributes...]", "yellow");
out("");
out("Types:", "bold");
out(" app Create a new Wheels application (alias for 'wheels new')");
out(" model Generate a model CFC");
out(" controller Generate a controller CFC");
out(" view Generate a view template");
out(" migration Generate a database migration");
out(" scaffold Generate model + controller + views + migration + tests + routes");
out(" api-resource Generate API-only model + controller + migration + tests + routes (no views)");
out(" route Add a resource route to config/routes.cfm");
out(" test Generate a test spec file");
out(" property Generate an add-column migration for a model property");
out(" helper Generate a helper file in app/helpers/");
out(" snippets Generate common code pattern snippets (auth, soft-delete, api, etc.)");
out("");
out("Examples:", "bold");
out(" wheels generate app myapp");
out(" wheels generate model User name email:string active:boolean");
out(" wheels generate controller Users index show create");
out(" wheels generate migration CreateUsers");
out(" wheels generate scaffold Post title body:text publishedAt:datetime");
out(" wheels generate api-resource Product name price:decimal sku:string");
out(" wheels generate route posts");
out(" wheels generate test model User");
out(" wheels generate property User email:string");
out(" wheels generate helper formatting");
out(" wheels generate snippets auth");
return "";
}
var type = args[1];
var remaining = args.len() > 1 ? args.slice(2) : [];
switch (lCase(type)) {
case "app":
case "a":
// Delegate to wheels new — pass remaining args as __arguments
__arguments = remaining;
return new();
case "model":
case "m":
return generateModel(remaining);
case "controller":
case "c":
return generateController(remaining);
case "view":
case "v":
return generateView(remaining);
case "migration":
case "migrate":
return generateMigration(remaining);
case "scaffold":
case "s":
return generateScaffold(remaining);
case "api-resource":
case "api":
return generateApiResource(remaining);
case "route":
case "r":
return generateRoute(remaining);
case "test":
return generateTest(remaining);
case "property":
case "prop":
return generateProperty(remaining);
case "helper":
case "h":
return generateHelper(remaining);
case "snippets":
return generateSnippets(remaining);
default:
out("Unknown generator type: #type#", "red");
out("Run 'wheels generate' for available types.");
return "";
}
}
// ─────────────────────────────────────────────────
// migrate — Database migration management
// ─────────────────────────────────────────────────
/**
* hint: Run database migrations (latest, up, down, info)
*/
public string function migrate() {
var args = __arguments ?: [];
var action = arrayLen(args) ? lCase(args[1]) : "latest";
switch (action) {
case "latest":
case "up":
case "down":
case "info":
return runMigration(action);
default:
out("Unknown migration action: #action#", "red");
out("Usage: wheels migrate [latest|up|down|info]");
return "";
}
}
// ─────────────────────────────────────────────────
// test — Run test suite
// ─────────────────────────────────────────────────
/**
* hint: Run test suite with optional filter and reporter
*/
public string function test() {
var args = __arguments ?: [];
var filter = "";
var reporter = "simple";
var format = "json";
var verboseOutput = false;
// Parse named arguments from --key=value or --key value
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (arg == "--filter" && i < arrayLen(args)) {
filter = args[++i];
} else if (reFindNoCase("^--filter=", arg)) {
filter = valueAfterEquals(arg);
} else if (arg == "--reporter" && i < arrayLen(args)) {
reporter = args[++i];
} else if (reFindNoCase("^--reporter=", arg)) {
reporter = valueAfterEquals(arg);
} else if (arg == "--verbose" || arg == "-v") {
verboseOutput = true;
} else if (!arg.startsWith("--")) {
// Positional arg is the filter directory
filter = arg;
}
}
return runTests(filter, reporter, format, verboseOutput);
}
// ─────────────────────────────────────────────────
// reload — Reload application
// ─────────────────────────────────────────────────
/**
* hint: Reload the running Wheels application
*/
public string function reload() {
var serverPort = detectServerPort();
if (!serverPort) {
out("No running Wheels server detected. Start one with: wheels start", "red");
return "";
}
var password = detectReloadPassword();
try {
var reloadUrl = "http://localhost:#serverPort#/?reload=true&password=#password#";
var httpResult = makeHttpRequest(reloadUrl);
out("Application reloaded successfully.", "green");
verbose("URL: http://localhost:#serverPort#/?reload=true&password=***");
} catch (any e) {
out("Failed to reload: #e.message#", "red");
if (!len(password)) {
out("Hint: Set RELOAD_PASSWORD in .env or config/settings.cfm", "yellow");
}
}
return "";
}
// ─────────────────────────────────────────────────
// start / stop — Dev server management
// ─────────────────────────────────────────────────
/**
* hint: Start the Wheels development server via LuCLI
*/
public string function start() {
var args = __arguments ?: [];
out("Starting Wheels server...", "cyan");
// Delegate to LuCLI's server start command
var cmdArgs = ["start"];
// Pass through any extra args (--port, --version, etc.)
cmdArgs.append(args, true);
executeCommand("server", cmdArgs, variables.projectRoot);
return "";
}
/**
* hint: Stop the running Wheels development server
*/
public string function stop() {
out("Stopping Wheels server...", "cyan");
executeCommand("server", ["stop"], variables.projectRoot);
return "";
}
// ─────────────────────────────────────────────────
// new — Scaffold a new Wheels project
// ─────────────────────────────────────────────────
/**
* hint: Scaffold a new Wheels project directory
*/
public string function new() {
var args = __arguments ?: [];
if (!arrayLen(args)) {
out("Usage: wheels new <appname> [options]", "yellow");
out("");
out("Creates a new Wheels application in the specified directory.");
out("By default, SQLite is configured as the zero-config database.");
out("");
out("Options:", "bold");
out(" --port=<number> Server port (default: 8080)");
out(" --datasource=<name> Datasource name (default: app name)");
out(" --reload-password=<pw> Reload password (default: app name)");
out(" --no-sqlite Skip default SQLite database setup");
out(" --setup-h2 Use H2 embedded database instead of SQLite");
out(" --no-open-browser Don't open browser on server start");
out("");
out("Examples:", "bold");
out(" wheels new myapp");
out(" wheels new myapp --port=3000 --setup-h2");
out(" wheels new myapp --datasource=mydb --no-sqlite");
return "";
}
var appName = "";
var options = {
port: 8080,
datasource: "",
reloadPassword: "",
setupH2: false,
noSQLite: false,
openBrowser: true
};
// Parse arguments: first non-flag arg is app name, flags are options
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (reFindNoCase("^--port=", arg)) {
options.port = val(valueAfterEquals(arg));
} else if (reFindNoCase("^--datasource=", arg)) {
options.datasource = valueAfterEquals(arg);
} else if (reFindNoCase("^--reload-password=", arg)) {
options.reloadPassword = valueAfterEquals(arg);
} else if (arg == "--setup-h2") {
options.setupH2 = true;
} else if (arg == "--no-sqlite") {
options.noSQLite = true;
} else if (arg == "--no-open-browser") {
options.openBrowser = false;
} else if (!arg.startsWith("--") && !len(appName)) {
appName = arg;
}
}
if (!len(appName)) {
out("Error: app name is required.", "red");
out("Usage: wheels new <appname>");
return "";
}
// Default datasource and reload password to app name if not specified
if (!len(options.datasource)) options.datasource = lCase(appName);
if (!len(options.reloadPassword)) options.reloadPassword = lCase(appName);
return scaffoldNewApp(appName, options);
}
// ─────────────────────────────────────────────────
// create — Create application components
// ─────────────────────────────────────────────────
/**
* hint: Create application components (wheels create app <name> [options])
*/
public string function create() {
var args = __arguments ?: [];
if (!arrayLen(args)) {
out("Usage: wheels create <type> <name> [options]", "yellow");
out("");
out("Types:", "bold");
out(" app Create a new Wheels application");
out("");
out("Examples:", "bold");
out(" wheels create app myapp");
out(" wheels create app myapp --port=3000 --setup-h2");
return "";
}
var type = lCase(args[1]);
var remaining = args.len() > 1 ? args.slice(2) : [];
switch (type) {
case "app":
__arguments = remaining;
return new();
default:
out("Unknown create type: #type#", "red");
out("Run 'wheels create' for available types.");
return "";
}
}
// ─────────────────────────────────────────────────
// routes — List application routes
// ─────────────────────────────────────────────────
/**
* hint: List all configured routes with method, path, and controller action
*/
public string function routes() {
var serverPort = detectServerPort();
if (!serverPort) {
out("No running Wheels server detected. Start one with: wheels start", "red");
return "";
}
try {
var routesUrl = "http://localhost:#serverPort#/wheels/ai?context=routing";
var httpResult = makeHttpRequest(routesUrl);
out(httpResult);
} catch (any e) {
out("Failed to fetch routes: #e.message#", "red");
}
return "";
}
// ─────────────────────────────────────────────────
// info — Show environment info
// ─────────────────────────────────────────────────
/**
* hint: Show framework version, environment, and configuration
*/
public string function info() {
out("Wheels CLI v#version()#", "bold");
out("");
if (len(variables.projectRoot) && directoryExists(variables.projectRoot & "/vendor/wheels")) {
out("Project: #variables.projectRoot#");
// Detect Wheels version from vendor
var versionFile = variables.projectRoot & "/vendor/wheels/events/onapplicationstart/settings.cfm";
if (fileExists(versionFile)) {
try {
var vContent = fileRead(versionFile);
var vMatch = reFindNoCase('version[^"]*"([^"]+)"', vContent, 1, true);
if (arrayLen(vMatch.match) > 1) {
out("Wheels: v#vMatch.match[2]#");
}
} catch (any e) { /* skip */ }
}
// CFML engine
out("Engine: Lucee (LuCLI module)");
// Datasource
var settingsFile = variables.projectRoot & "/config/settings.cfm";
if (fileExists(settingsFile)) {
try {
var sContent = fileRead(settingsFile);
var dsMatch = reFindNoCase('dataSourceName\s*[=,]\s*"([^"]+)"', sContent, 1, true);
if (arrayLen(dsMatch.match) > 1) {
out("Database: #dsMatch.match[2]#");
}
} catch (any e) { /* skip */ }
}
// Environment file
var envFile = variables.projectRoot & "/.env";
if (fileExists(envFile)) {
out("Env file: .env found", "green");
}
// lucee.json
var luceeJson = variables.projectRoot & "/lucee.json";
if (fileExists(luceeJson)) {
out("Config: lucee.json found", "green");
}
// Count routes
var routesFile = variables.projectRoot & "/config/routes.cfm";
if (fileExists(routesFile)) {
var routeContent = fileRead(routesFile);
var resourceCount = 0;
var pos = 1;
while (pos > 0) {
pos = findNoCase(".resources(", routeContent, pos);
if (pos > 0) { resourceCount++; pos++; }
}
if (resourceCount > 0) {
out("Routes: #resourceCount# resource route(s)");
}
}
// Count models
var modelsDir = variables.projectRoot & "/app/models";
if (directoryExists(modelsDir)) {
var modelCount = arrayLen(directoryList(modelsDir, false, "name", "*.cfc"));
if (modelCount > 0) {
out("Models: #modelCount# model(s)");
}
}
// Server status
var serverPort = detectServerPort();
if (serverPort) {
out("Server: running on port #serverPort#", "green");
} else {
out("Server: not running", "yellow");
}
} else {
out("Not in a Wheels project directory.", "yellow");
}
return "";
}
// ─────────────────────────────────────────────────
// mcp — MCP server instructions
// ─────────────────────────────────────────────────
/**
* hint: Show MCP server configuration instructions
*/
public string function mcp() {
out("MCP is built into LuCLI. Run:", "bold");
out(" lucli mcp wheels");
out("");
out("Configure in Claude Code (.claude/claude_project_config.json):", "bold");
out(' {"mcpServers":{"wheels":{"command":"lucli","args":["mcp","wheels"]}}}');
out("");
out("All public commands in this module are auto-discovered as MCP tools.");
out("Tools are prefixed with the module name: wheels_generate, wheels_migrate, etc.");
return "";
}
// ─────────────────────────────────────────────────
// console — Interactive REPL
// ─────────────────────────────────────────────────
/**
* hint: Launch interactive CFML console with Wheels app context (model, service, get)
*/
public string function console() {
var args = __arguments ?: [];
var password = "";
// Parse --password=value
for (var i = 1; i <= arrayLen(args); i++) {
var arg = args[i];
if (reFindNoCase("^--password=", arg)) {
password = valueAfterEquals(arg);
} else if (arg == "--password" && i < arrayLen(args)) {
password = args[++i];
}
}
// Detect server
var serverPort = detectServerPort();
if (!serverPort) {
out("No running Wheels server detected.", "red");
out("The console requires a running server. Start with: wheels start");
return "";
}
// Auto-detect reload password if not provided
if (!len(password)) {
password = detectReloadPassword();
}
// Verify connectivity with a ping
var evalUrl = "http://localhost:#serverPort#/wheels/console/eval";
try {
var pingResult = makeHttpPost(evalUrl, serializeJSON({expression: "__ping__", password: password}));
if (isJSON(pingResult)) {
var pingData = deserializeJSON(pingResult);
if (!pingData.success) {
out("Console connection failed: #pingData.error#", "red");
return "";
}
var wheelsVersion = pingData.version ?: "unknown";
var wheelsEnv = pingData.environment ?: "unknown";
} else {
out("Server returned unexpected response. Is this a Wheels 3.x application?", "red");
return "";
}
} catch (any e) {
out("Cannot connect to console endpoint at #evalUrl#", "red");
out("Ensure your Wheels app is v3.1+ with console support.", "yellow");
out("Error: #e.message#", "yellow");
return "";
}
// Banner
out("", "");
out("Wheels Console v#version()#", "bold");
out("Connected to localhost:#serverPort# (#wheelsEnv#) — Wheels #wheelsVersion#", "cyan");
out("Type expressions to evaluate in your app context. /help for commands.", "");
out("", "");
// Interactive REPL loop
var System = createObject("java", "java.lang.System");
var reader = createObject("java", "java.io.BufferedReader").init(
createObject("java", "java.io.InputStreamReader").init(System.in)
);
var running = true;
while (running) {
// Print prompt
System.out.print("wheels> ");
System.out.flush();
// Read input
var line = reader.readLine();
// Handle EOF (Ctrl+D)
if (isNull(line)) {
out("");
out("Bye!", "cyan");
break;
}
line = trim(line);
// Skip empty lines
if (!len(line)) continue;
// Handle REPL commands
switch (lCase(line)) {
case "/exit":
case "/quit":
case "/q":
out("Bye!", "cyan");
running = false;
continue;
case "/help":
case "/h":
printConsoleHelp();
continue;
case "/env":
consoleExec(evalUrl, "__env__", password);
continue;
case "/reload":
out("Reloading application...", "cyan");
try {
var reloadUrl = "http://localhost:#serverPort#/?reload=true&password=#password#";
makeHttpRequest(reloadUrl);
out("Application reloaded.", "green");
} catch (any e) {
out("Reload failed: #e.message#", "red");
}
continue;
case "/clear":
// ANSI clear screen
System.out.print(chr(27) & "[2J" & chr(27) & "[H");
System.out.flush();
continue;
}
// Evaluate expression
consoleExec(evalUrl, line, password);
}
return "";
}
/**
* Execute a single expression and display the result
*/
private void function consoleExec(required string url, required string expression, string password = "") {
try {
var body = serializeJSON({expression: expression, password: password});
var httpResult = makeHttpPost(url, body);
if (!isJSON(httpResult)) {
out("Server returned non-JSON response.", "red");
verbose(httpResult);
return;
}
var result = deserializeJSON(httpResult);
// Display captured output (from writeOutput calls)
if (len(result.output ?: "")) {
out(result.output);
}
if (!result.success) {
out("Error: #result.error#", "red");
return;
}
// Display result based on type
var resultType = result.type ?: "void";
var resultValue = result.result ?: "";
if (resultType == "void" && !len(resultValue)) {
// No return value and no output — nothing to display
return;
}
switch (resultType) {
case "query":
displayQueryResult(resultValue);
break;
case "model":
displayModelResult(resultValue);
break;
case "struct":
case "array":
displayJsonResult(resultValue, resultType);
break;
case "number":
case "boolean":
case "string":
out("=> #resultValue#", "green");
break;
case "object":
out("=> [#resultValue#]", "cyan");
break;
default:
if (len(resultValue)) {
out("=> #resultValue#");
}
}
} catch (any e) {
out("Request failed: #e.message#", "red");
}
}
/**
* Display a query result as a formatted table
*/
private void function displayQueryResult(required string jsonResult) {
try {
var data = deserializeJSON(jsonResult);
var columns = data.columns ?: [];
var rows = data.data ?: [];
var recordCount = data.recordCount ?: 0;
if (!arrayLen(columns)) {
out("(empty query)", "yellow");
return;
}
// Calculate column widths
var widths = {};
for (var col in columns) {
widths[col] = len(col);
}
for (var row in rows) {
for (var col in columns) {
var val = toString(row[col] ?: "");
if (len(val) > 40) val = left(val, 37) & "...";
widths[col] = max(widths[col], len(val));
}
}
// Header
var header = "";
var separator = "";
for (var col in columns) {
var w = widths[col];
header &= " " & lCase(col) & repeatString(" ", w - len(col)) & " |";
separator &= repeatString("-", w + 2) & "+";
}
out(header, "bold");
out(separator, "");
// Rows
for (var row in rows) {
var line = "";
for (var col in columns) {
var w = widths[col];
var val = toString(row[col] ?: "");
if (len(val) > 40) val = left(val, 37) & "...";
line &= " " & val & repeatString(" ", w - len(val)) & " |";
}
out(line);
}
// Footer
if (recordCount > arrayLen(rows)) {
out("(#recordCount# rows, showing first #arrayLen(rows)#)", "yellow");
} else {
out("(#recordCount# row#recordCount != 1 ? 's' : ''#)", "yellow");
}
} catch (any e) {
// Fallback: show raw JSON
out(jsonResult);
}
}
/**
* Display a model result as key-value pairs
*/
private void function displayModelResult(required string jsonResult) {
try {
var props = deserializeJSON(jsonResult);
out("=> {", "green");
var keys = structKeyArray(props);
arraySort(keys, "textnocase");
for (var key in keys) {
if (left(key, 1) == "_") continue; // Skip meta keys in main display
var val = isNull(props[key]) ? "null" : toString(props[key]);
if (len(val) > 80) val = left(val, 77) & "...";
out(" #lCase(key)#: #val#");
}
// Show meta info
if (structKeyExists(props, "_key")) {
out(" _key: #props._key#", "cyan");
}
if (structKeyExists(props, "_isNew")) {
out(" _isNew: #props._isNew#", "cyan");
}
out(" }", "green");
} catch (any e) {
out("=> #jsonResult#");
}
}
/**
* Display a struct or array result as indented JSON
*/
private void function displayJsonResult(required string jsonResult, required string type) {
try {
// Simple indentation for readability
var formatted = jsonResult;
// Basic pretty-print: add newlines after { [ , and before } ]
formatted = replace(formatted, "{", "{#chr(10)# ", "all");
formatted = replace(formatted, "}", "#chr(10)#}", "all");
formatted = replace(formatted, "[", "[#chr(10)# ", "all");
formatted = replace(formatted, "]", "#chr(10)#]", "all");
formatted = replace(formatted, ",", ",#chr(10)# ", "all");
out("=> #formatted#", "green");
} catch (any e) {
out("=> #jsonResult#");
}
}
/**
* Print console help text
*/
private void function printConsoleHelp() {
out("");
out("Wheels Console Commands:", "bold");
out(" /help, /h Show this help");
out(" /env Show environment info");
out(" /reload Reload the application");
out(" /clear Clear the screen");
out(" /exit, /quit Exit the console");
out("");
out("Expression Examples:", "bold");
out(' model("User").findAll() Query all users');
out(' model("User").findByKey(1) Find user by ID');
out(' model("User").findByKey(1).properties() Get user properties');
out(' model("User").count() Count records');
out(' model("Post").findAll(where="status=''draft''") Filtered query');
out(' get("environment") Framework setting');
out(' application.wheels.version Wheels version');
out(' service("emailService") Resolve a service');
out("");
}
// ─────────────────────────────────────────────────
// analyze — Code analysis
// ─────────────────────────────────────────────────
/**
* hint: Analyze Wheels application code for quality issues, anti-patterns, and complexity metrics
*/
public string function analyze() {
var args = __arguments ?: [];
var target = arrayLen(args) ? lCase(args[1]) : "all";
if (!arrayLen(args) && !directoryExists(variables.projectRoot & "/app")) {
out("No app/ directory found. Are you in a Wheels project?", "red");
return "";
}
out("Analyzing code...", "cyan");
out("");
try {
var analysis = getService("analysis");
var results = analysis.analyze(target);
// Display metrics
out("Code Analysis Results", "bold");
out("────────────────────────────────────");
out("Files: #results.totalFiles#");
out("Lines: #results.totalLines#");
out("Functions: #results.totalFunctions#");
out("Grade: #results.metrics.grade# (#results.metrics.healthScore#/100)");
out("");
// Anti-patterns
if (arrayLen(results.antiPatterns)) {
out("Anti-Patterns (#arrayLen(results.antiPatterns)#)", "red");
for (var issue in results.antiPatterns) {
var fileName = listLast(issue.file, "/\");
var severity = issue.severity == "error" ? "red" : "yellow";
out(" [#uCase(issue.severity)#] #fileName#:#issue.line ?: 1# — #issue.message#", severity);
}
out("");
}
// Complex functions
if (arrayLen(results.complexFunctions)) {
out("Complex Functions (#arrayLen(results.complexFunctions)#)", "yellow");
for (var f in results.complexFunctions) {
var fName = listLast(f.file, "/\");
out(" #fName#:#f.functionName# — complexity #f.complexity#", "yellow");
}
out("");
}
// Code smells
if (arrayLen(results.codeSmells)) {
out("Code Smells (#arrayLen(results.codeSmells)#)", "yellow");
for (var smell in results.codeSmells) {
var sName = listLast(smell.file, "/\");
out(" #sName# — #smell.message#", "yellow");
}
out("");
}
if (!arrayLen(results.antiPatterns) && !arrayLen(results.complexFunctions) && !arrayLen(results.codeSmells)) {
out("No issues found!", "green");
}
out("Completed in #numberFormat(results.executionTime, '0.00')#s");
} catch (any e) {
out("Analysis failed: #e.message#", "red");
}
return "";
}
// ─────────────────────────────────────────────────
// validate — Quick validation
// ─────────────────────────────────────────────────
/**
* hint: Validate Wheels application code for common errors and anti-patterns
*/
public string function validate() {
if (!directoryExists(variables.projectRoot & "/app")) {
out("No app/ directory found. Are you in a Wheels project?", "red");
return "";
}
out("Validating...", "cyan");
out("");
try {
var analysis = getService("analysis");
var results = analysis.validate();
if (results.valid) {
out("Validation passed — no errors found (#results.totalIssues# warnings)", "green");
} else {
out("Validation found #results.totalIssues# issue(s):", "red");
}
for (var issue in results.issues) {
var fileName = listLast(issue.file, "/\");
var severity = issue.severity == "error" ? "red" : "yellow";
out(" [#uCase(issue.severity)#] #fileName# — #issue.message#", severity);
}
} catch (any e) {
out("Validation failed: #e.message#", "red");
}
return "";
}
// ═════════════════════════════════════════════════
// PRIVATE — Implementation details
// ═════════════════════════════════════════════════
// ── Code Generation ──────────────────────────────
private string function generateModel(required array args) {
if (!arrayLen(args)) {
out("Usage: wheels generate model <Name> [properties...]", "yellow");
out(" Example: wheels generate model User name email:string active:boolean");
return "";
}
var modelName = capitalize(args[1]);
var properties = args.len() > 1 ? args.slice(2) : [];
// Parse properties and associations from args
var parsed = parseGeneratorArgs(properties);
// Use CodeGen service with template files
var codegen = getService("codegen");
var validation = codegen.validateName(modelName, "model");
if (!validation.valid) {
out("Invalid model name: #arrayToList(validation.errors, '; ')#", "red");
return "";
}
var result = codegen.generateModel(
name = modelName,
properties = parsed.properties,
belongsTo = arrayToList(parsed.belongsTo),
hasMany = arrayToList(parsed.hasMany),
hasOne = arrayToList(parsed.hasOne)
);
if (result.success) {
printCreated("app/models/#modelName#.cfc");
} else {
out(result.error, "red");
return "";
}
// Also generate migration if properties provided
if (arrayLen(parsed.properties)) {
var scaffold = getService("scaffold");
var migrationPath = scaffold.createMigrationWithProperties(modelName, parsed.properties);
var migrationFileName = listLast(migrationPath, "/\");
printCreated("app/migrator/migrations/#migrationFileName#");
}
return "";
}
private string function generateController(required array args) {
if (!arrayLen(args)) {
out("Usage: wheels generate controller <Name> [actions...]", "yellow");