-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.zig
More file actions
3392 lines (3119 loc) · 140 KB
/
Copy pathproject.zig
File metadata and controls
3392 lines (3119 loc) · 140 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
const std = @import("std");
const Io = std.Io;
pub const Runtime = struct {
allocator: std.mem.Allocator,
io: Io,
};
pub const Options = struct {
project_dir: []const u8 = ".",
target_path: ?[]const u8 = null,
select: ?[]const u8 = null,
exclude: ?[]const u8 = null,
resource_type: ?[]const u8 = null,
output: Output = .text,
};
pub const Output = enum {
text,
json,
};
const ProjectConfig = struct {
name: []const u8,
model_paths: std.ArrayList([]const u8) = .empty,
seed_paths: std.ArrayList([]const u8) = .empty,
macro_paths: std.ArrayList([]const u8) = .empty,
macro_paths_set: bool = false,
target_path: []const u8 = "target",
};
const SourceDef = struct {
unique_id: []const u8,
source_name: []const u8,
table_name: []const u8,
original_file_path: []const u8,
};
const ExposureDef = struct {
unique_id: []const u8,
name: []const u8,
exposure_type: []const u8 = "",
enabled: bool = true,
maturity: ?[]const u8 = null,
url: ?[]const u8 = null,
description: []const u8 = "",
owner_name: []const u8 = "",
owner_email: ?[]const u8 = null,
path: []const u8,
original_file_path: []const u8,
tags: std.ArrayList([]const u8) = .empty,
meta: std.ArrayList(MetaEntry) = .empty,
refs: std.ArrayList(RefDep) = .empty,
source_refs: std.ArrayList(SourceDep) = .empty,
depends_on: std.ArrayList([]const u8) = .empty,
};
const MetaEntry = struct {
key: []const u8,
value: JsonScalar,
};
const JsonScalar = struct {
text: []const u8,
kind: enum {
string,
number,
bool,
null,
} = .string,
};
const RefDep = struct {
package: ?[]const u8,
name: []const u8,
};
const SourceDep = struct {
source_name: []const u8,
table_name: []const u8,
};
const ColumnDef = struct {
name: []const u8,
description: []const u8 = "",
doc_blocks: std.ArrayList([]const u8) = .empty,
tests: std.ArrayList(GenericTestDef) = .empty,
};
const GenericTestDef = struct {
name: []const u8,
accepted_values: std.ArrayList([]const u8) = .empty,
relationship_to: []const u8 = "",
relationship_field: []const u8 = "",
};
const DocBlock = struct {
unique_id: []const u8,
name: []const u8,
path: []const u8,
original_file_path: []const u8,
block_contents: []const u8,
};
const MacroDef = struct {
unique_id: []const u8,
name: []const u8,
path: []const u8,
original_file_path: []const u8,
macro_sql: []const u8,
patch_path: ?[]const u8 = null,
description: []const u8 = "",
arguments: std.ArrayList(MacroArgument) = .empty,
macro_depends_on: std.ArrayList([]const u8) = .empty,
};
const MacroArgument = struct {
name: []const u8,
type: []const u8 = "",
description: []const u8 = "",
};
const ModelProperty = struct {
name: []const u8,
patch_path: []const u8,
description: []const u8 = "",
materialized: []const u8 = "",
tags: std.ArrayList([]const u8) = .empty,
doc_blocks: std.ArrayList([]const u8) = .empty,
tests: std.ArrayList(GenericTestDef) = .empty,
columns: std.ArrayList(ColumnDef) = .empty,
enabled: ?bool = null,
};
const UnmatchedModelProperty = struct {
name: []const u8,
patch_path: []const u8,
};
const MacroProperty = struct {
name: []const u8,
patch_path: []const u8,
description: []const u8 = "",
arguments: std.ArrayList(MacroArgument) = .empty,
};
const UnmatchedMacroProperty = struct {
name: []const u8,
patch_path: []const u8,
};
const Node = struct {
resource_type: []const u8 = "model",
unique_id: []const u8,
name: []const u8,
path: []const u8,
original_file_path: []const u8,
patch_path: ?[]const u8 = null,
raw_code: []const u8,
description: []const u8 = "",
materialized: []const u8 = "view",
enabled: bool = true,
tags: std.ArrayList([]const u8) = .empty,
doc_blocks: std.ArrayList([]const u8) = .empty,
tests: std.ArrayList(GenericTestDef) = .empty,
columns: std.ArrayList(ColumnDef) = .empty,
refs: std.ArrayList(RefDep) = .empty,
source_refs: std.ArrayList(SourceDep) = .empty,
depends_on: std.ArrayList([]const u8) = .empty,
macro_depends_on: std.ArrayList([]const u8) = .empty,
};
const GenericTestNode = struct {
unique_id: []const u8,
name: []const u8,
alias: []const u8,
path: []const u8,
original_file_path: []const u8,
raw_code: []const u8,
test_name: []const u8,
column_name: ?[]const u8 = null,
accepted_values: std.ArrayList([]const u8) = .empty,
relationship_to: []const u8 = "",
relationship_field: []const u8 = "",
attached_node: []const u8,
depends_on: std.ArrayList([]const u8) = .empty,
macro_depends_on: std.ArrayList([]const u8) = .empty,
};
const Graph = struct {
allocator: std.mem.Allocator,
project_name: []const u8,
nodes: std.ArrayList(Node) = .empty,
tests: std.ArrayList(GenericTestNode) = .empty,
sources: std.ArrayList(SourceDef) = .empty,
exposures: std.ArrayList(ExposureDef) = .empty,
docs: std.ArrayList(DocBlock) = .empty,
macros: std.ArrayList(MacroDef) = .empty,
model_properties: std.ArrayList(ModelProperty) = .empty,
macro_properties: std.ArrayList(MacroProperty) = .empty,
unmatched_model_properties: std.ArrayList(UnmatchedModelProperty) = .empty,
unmatched_macro_properties: std.ArrayList(UnmatchedMacroProperty) = .empty,
fn deinit(self: *Graph) void {
for (self.nodes.items) |*node| {
deinitNode(self.allocator, node);
}
for (self.tests.items) |*test_node| {
deinitGenericTestNode(self.allocator, test_node);
}
for (self.exposures.items) |*exposure| {
deinitExposureDef(self.allocator, exposure);
}
for (self.model_properties.items) |*property| {
deinitModelProperty(self.allocator, property);
}
for (self.macro_properties.items) |*property| {
deinitMacroProperty(self.allocator, property);
}
for (self.macros.items) |*macro| {
deinitMacro(self.allocator, macro);
}
self.nodes.deinit(self.allocator);
self.tests.deinit(self.allocator);
self.sources.deinit(self.allocator);
self.exposures.deinit(self.allocator);
self.docs.deinit(self.allocator);
self.macros.deinit(self.allocator);
self.model_properties.deinit(self.allocator);
self.macro_properties.deinit(self.allocator);
self.unmatched_model_properties.deinit(self.allocator);
self.unmatched_macro_properties.deinit(self.allocator);
}
};
fn deinitNode(allocator: std.mem.Allocator, node: *Node) void {
node.tags.deinit(allocator);
node.doc_blocks.deinit(allocator);
deinitGenericTestDefs(allocator, &node.tests);
for (node.columns.items) |*column| {
column.doc_blocks.deinit(allocator);
deinitGenericTestDefs(allocator, &column.tests);
}
node.columns.deinit(allocator);
node.refs.deinit(allocator);
node.source_refs.deinit(allocator);
node.depends_on.deinit(allocator);
node.macro_depends_on.deinit(allocator);
}
fn deinitGenericTestNode(allocator: std.mem.Allocator, test_node: *GenericTestNode) void {
test_node.accepted_values.deinit(allocator);
test_node.depends_on.deinit(allocator);
test_node.macro_depends_on.deinit(allocator);
}
fn deinitExposureDef(allocator: std.mem.Allocator, exposure: *ExposureDef) void {
exposure.tags.deinit(allocator);
exposure.meta.deinit(allocator);
exposure.refs.deinit(allocator);
exposure.source_refs.deinit(allocator);
exposure.depends_on.deinit(allocator);
}
fn deinitMacro(allocator: std.mem.Allocator, macro: *MacroDef) void {
macro.arguments.deinit(allocator);
macro.macro_depends_on.deinit(allocator);
}
fn deinitModelProperty(allocator: std.mem.Allocator, property: *ModelProperty) void {
property.tags.deinit(allocator);
property.doc_blocks.deinit(allocator);
deinitGenericTestDefs(allocator, &property.tests);
for (property.columns.items) |*column| {
column.doc_blocks.deinit(allocator);
deinitGenericTestDefs(allocator, &column.tests);
}
property.columns.deinit(allocator);
}
fn deinitMacroProperty(allocator: std.mem.Allocator, property: *MacroProperty) void {
property.arguments.deinit(allocator);
}
fn deinitGenericTestDefs(allocator: std.mem.Allocator, tests: *std.ArrayList(GenericTestDef)) void {
for (tests.items) |*test_def| {
test_def.accepted_values.deinit(allocator);
}
tests.deinit(allocator);
}
pub fn parse(runtime: Runtime, options: Options, stdout: *Io.Writer, stderr: *Io.Writer) !void {
var graph = try loadGraph(runtime, options.project_dir);
defer graph.deinit();
try resolveDependencies(&graph);
try writeWarnings(stderr, &graph);
const active_models = countActiveNodes(&graph);
const active_seeds = countActiveSeeds(&graph);
const target_path = options.target_path orelse graphDefaultTarget(runtime, options.project_dir) catch "target";
const target_dir = if (std.fs.path.isAbsolute(target_path))
target_path
else
try pathJoin(runtime.allocator, &.{ options.project_dir, target_path });
try std.Io.Dir.cwd().createDirPath(runtime.io, target_dir);
const manifest_path = try pathJoin(runtime.allocator, &.{ target_dir, "manifest.json" });
const manifest = try renderManifest(runtime.allocator, &graph);
try std.Io.Dir.cwd().writeFile(runtime.io, .{ .sub_path = manifest_path, .data = manifest });
try stdout.print("Parsed {d} model(s), {d} seed(s), {d} source(s), and {d} exposure(s) into {s}\n", .{
active_models,
active_seeds,
graph.sources.items.len,
countActiveExposures(&graph),
normalizeForDisplay(manifest_path),
});
}
pub fn list(runtime: Runtime, options: Options, stdout: *Io.Writer) !void {
var graph = try loadGraph(runtime, options.project_dir);
defer graph.deinit();
try resolveDependencies(&graph);
const select = if (options.select) |value| try runtime.allocator.dupe(u8, value) else null;
const exclude = if (options.exclude) |value| try runtime.allocator.dupe(u8, value) else null;
const resource_type = if (options.resource_type) |value| try runtime.allocator.dupe(u8, value) else null;
const selected = try selectResources(runtime.allocator, &graph, resource_type, select, exclude);
if (options.output == .json) {
try writeSelectedJson(stdout, selected);
} else {
for (selected) |item| {
try stdout.print("{s}\n", .{item.unique_id});
}
}
}
fn graphDefaultTarget(runtime: Runtime, project_dir: []const u8) ![]const u8 {
var config = try loadProjectConfig(runtime, project_dir);
defer config.model_paths.deinit(runtime.allocator);
defer config.seed_paths.deinit(runtime.allocator);
defer config.macro_paths.deinit(runtime.allocator);
return config.target_path;
}
fn loadGraph(runtime: Runtime, project_dir: []const u8) !Graph {
var config = try loadProjectConfig(runtime, project_dir);
defer config.model_paths.deinit(runtime.allocator);
defer config.seed_paths.deinit(runtime.allocator);
defer config.macro_paths.deinit(runtime.allocator);
var graph = Graph{ .allocator = runtime.allocator, .project_name = config.name };
errdefer graph.deinit();
for (config.macro_paths.items) |macro_path| {
var macro_files: std.ArrayList([]const u8) = .empty;
defer macro_files.deinit(runtime.allocator);
var macro_yaml_files: std.ArrayList([]const u8) = .empty;
defer macro_yaml_files.deinit(runtime.allocator);
const root = try pathJoin(runtime.allocator, &.{ project_dir, macro_path });
discoverMacroFiles(runtime, root, macro_path, ¯o_files, ¯o_yaml_files) catch |err| switch (err) {
error.FileNotFound => continue,
else => return err,
};
sortStrings(macro_files.items);
sortStrings(macro_yaml_files.items);
for (macro_yaml_files.items) |yaml_path| {
try parseYamlProperties(runtime, project_dir, macro_path, yaml_path, config.name, &graph);
}
for (macro_files.items) |relative_path| {
try parseMacros(runtime, project_dir, relative_path, config.name, &graph);
}
}
for (config.model_paths.items) |model_path| {
var sql_files: std.ArrayList([]const u8) = .empty;
defer sql_files.deinit(runtime.allocator);
var yaml_files: std.ArrayList([]const u8) = .empty;
defer yaml_files.deinit(runtime.allocator);
var md_files: std.ArrayList([]const u8) = .empty;
defer md_files.deinit(runtime.allocator);
const root = try pathJoin(runtime.allocator, &.{ project_dir, model_path });
discoverFiles(runtime, root, model_path, &sql_files, &yaml_files, &md_files) catch |err| switch (err) {
error.FileNotFound => continue,
else => return err,
};
sortStrings(sql_files.items);
sortStrings(yaml_files.items);
sortStrings(md_files.items);
for (md_files.items) |md_path| {
try parseDocBlocks(runtime, project_dir, model_path, md_path, config.name, &graph);
}
for (yaml_files.items) |yaml_path| {
try parseYamlProperties(runtime, project_dir, model_path, yaml_path, config.name, &graph);
}
for (sql_files.items) |sql_path| {
try parseModel(runtime, project_dir, model_path, sql_path, config.name, &graph);
}
}
for (config.seed_paths.items) |seed_path| {
var seed_files: std.ArrayList([]const u8) = .empty;
defer seed_files.deinit(runtime.allocator);
const root = try pathJoin(runtime.allocator, &.{ project_dir, seed_path });
discoverSeedFiles(runtime, root, seed_path, &seed_files) catch |err| switch (err) {
error.FileNotFound => continue,
else => return err,
};
sortStrings(seed_files.items);
for (seed_files.items) |relative_path| {
try parseSeed(runtime, seed_path, relative_path, config.name, &graph);
}
}
try rejectDuplicateMacroProperties(&graph);
try applyMacroProperties(&graph);
try applyModelProperties(&graph);
try materializeGenericTests(&graph);
sortNodes(graph.nodes.items);
sortTests(graph.tests.items);
sortSources(graph.sources.items);
sortExposures(graph.exposures.items);
sortDocs(graph.docs.items);
sortMacros(graph.macros.items);
try rejectDuplicateModels(&graph);
try rejectDuplicateSeeds(&graph);
try rejectDuplicateDocs(&graph);
try rejectDuplicateExposures(&graph);
try rejectDuplicateMacros(&graph);
try resolveMacroDependencies(&graph);
return graph;
}
fn loadProjectConfig(runtime: Runtime, project_dir: []const u8) !ProjectConfig {
const path = try pathJoin(runtime.allocator, &.{ project_dir, "dbt_project.yml" });
const text = std.Io.Dir.cwd().readFileAlloc(runtime.io, path, runtime.allocator, .limited(1024 * 1024)) catch |err| switch (err) {
error.FileNotFound => return error.MissingProjectFile,
else => return err,
};
var config = ProjectConfig{ .name = "" };
errdefer {
config.model_paths.deinit(runtime.allocator);
config.seed_paths.deinit(runtime.allocator);
config.macro_paths.deinit(runtime.allocator);
}
var lines = std.mem.splitScalar(u8, text, '\n');
var read_model_path_block = false;
var read_seed_path_block = false;
var read_macro_path_block = false;
while (lines.next()) |raw_line| {
const line = stripYamlComment(raw_line);
const trimmed = std.mem.trim(u8, line, " \t\r");
if (trimmed.len == 0) continue;
if (read_model_path_block) {
if (std.mem.startsWith(u8, trimmed, "- ")) {
try config.model_paths.append(runtime.allocator, try dupTrimmedScalar(runtime.allocator, trimmed[2..]));
continue;
}
read_model_path_block = false;
}
if (read_seed_path_block) {
if (std.mem.startsWith(u8, trimmed, "- ")) {
try config.seed_paths.append(runtime.allocator, try dupTrimmedScalar(runtime.allocator, trimmed[2..]));
continue;
}
read_seed_path_block = false;
}
if (read_macro_path_block) {
if (std.mem.startsWith(u8, trimmed, "- ")) {
try config.macro_paths.append(runtime.allocator, try dupTrimmedScalar(runtime.allocator, trimmed[2..]));
continue;
}
read_macro_path_block = false;
}
if (splitKeyValue(trimmed)) |kv| {
if (std.mem.eql(u8, kv.key, "name")) {
config.name = try dupTrimmedScalar(runtime.allocator, kv.value);
} else if (std.mem.eql(u8, kv.key, "target-path")) {
config.target_path = try dupTrimmedScalar(runtime.allocator, kv.value);
} else if (std.mem.eql(u8, kv.key, "model-paths")) {
if (std.mem.trim(u8, kv.value, " \t").len == 0) {
read_model_path_block = true;
} else {
try parseInlineStringList(runtime.allocator, kv.value, &config.model_paths);
}
} else if (std.mem.eql(u8, kv.key, "seed-paths")) {
if (std.mem.trim(u8, kv.value, " \t").len == 0) {
read_seed_path_block = true;
} else {
try parseInlineStringList(runtime.allocator, kv.value, &config.seed_paths);
}
} else if (std.mem.eql(u8, kv.key, "macro-paths")) {
config.macro_paths_set = true;
if (std.mem.trim(u8, kv.value, " \t").len == 0) {
read_macro_path_block = true;
} else {
try parseInlineStringList(runtime.allocator, kv.value, &config.macro_paths);
}
}
}
}
if (config.name.len == 0) return error.InvalidProjectName;
if (config.model_paths.items.len == 0) {
try config.model_paths.append(runtime.allocator, "models");
}
if (config.seed_paths.items.len == 0) {
try config.seed_paths.append(runtime.allocator, "seeds");
}
if (!config.macro_paths_set) {
try config.macro_paths.append(runtime.allocator, "macros");
}
return config;
}
fn discoverFiles(runtime: Runtime, absolute_dir: []const u8, relative_dir: []const u8, sql_files: *std.ArrayList([]const u8), yaml_files: *std.ArrayList([]const u8), md_files: *std.ArrayList([]const u8)) !void {
const fd = try openLinuxDirectory(runtime.allocator, absolute_dir);
defer closeLinuxFd(fd);
var buffer: [8192]u8 align(@alignOf(std.os.linux.dirent64)) = undefined;
var iter = LinuxDirReadState{ .fd = fd, .buffer = &buffer };
while (try nextLinuxDirectoryEntry(&iter)) |entry| {
if (entry.name.len == 0 or entry.name[0] == '.') continue;
if (std.mem.eql(u8, entry.name, "target") or
std.mem.eql(u8, entry.name, "dbt_packages") or
std.mem.eql(u8, entry.name, ".zig-cache") or
std.mem.eql(u8, entry.name, "zig-out"))
{
continue;
}
const child_abs = try pathJoin(runtime.allocator, &.{ absolute_dir, entry.name });
const child_rel = try pathJoin(runtime.allocator, &.{ relative_dir, entry.name });
if (entry.kind == .unknown and try linuxPathIsDirectory(runtime.allocator, child_abs)) {
try discoverFiles(runtime, child_abs, child_rel, sql_files, yaml_files, md_files);
continue;
}
switch (entry.kind) {
.directory => try discoverFiles(runtime, child_abs, child_rel, sql_files, yaml_files, md_files),
.file, .unknown => {
if (std.mem.endsWith(u8, entry.name, ".sql")) {
try sql_files.append(runtime.allocator, child_rel);
} else if (std.mem.endsWith(u8, entry.name, ".yml") or std.mem.endsWith(u8, entry.name, ".yaml")) {
try yaml_files.append(runtime.allocator, child_rel);
} else if (std.mem.endsWith(u8, entry.name, ".md")) {
try md_files.append(runtime.allocator, child_rel);
}
},
else => {},
}
}
}
fn discoverSeedFiles(runtime: Runtime, absolute_dir: []const u8, relative_dir: []const u8, seed_files: *std.ArrayList([]const u8)) !void {
const fd = try openLinuxDirectory(runtime.allocator, absolute_dir);
defer closeLinuxFd(fd);
var buffer: [8192]u8 align(@alignOf(std.os.linux.dirent64)) = undefined;
var iter = LinuxDirReadState{ .fd = fd, .buffer = &buffer };
while (try nextLinuxDirectoryEntry(&iter)) |entry| {
if (entry.name.len == 0 or entry.name[0] == '.') continue;
const child_abs = try pathJoin(runtime.allocator, &.{ absolute_dir, entry.name });
const child_rel = try pathJoin(runtime.allocator, &.{ relative_dir, entry.name });
if (entry.kind == .unknown and try linuxPathIsDirectory(runtime.allocator, child_abs)) {
try discoverSeedFiles(runtime, child_abs, child_rel, seed_files);
continue;
}
switch (entry.kind) {
.directory => try discoverSeedFiles(runtime, child_abs, child_rel, seed_files),
.file, .unknown => {
if (std.mem.endsWith(u8, entry.name, ".csv")) {
try seed_files.append(runtime.allocator, child_rel);
}
},
else => {},
}
}
}
fn discoverSqlFiles(runtime: Runtime, absolute_dir: []const u8, relative_dir: []const u8, sql_files: *std.ArrayList([]const u8)) !void {
const fd = try openLinuxDirectory(runtime.allocator, absolute_dir);
defer closeLinuxFd(fd);
var buffer: [8192]u8 align(@alignOf(std.os.linux.dirent64)) = undefined;
var iter = LinuxDirReadState{ .fd = fd, .buffer = &buffer };
while (try nextLinuxDirectoryEntry(&iter)) |entry| {
if (entry.name.len == 0 or entry.name[0] == '.') continue;
if (std.mem.eql(u8, entry.name, "target") or
std.mem.eql(u8, entry.name, "dbt_packages") or
std.mem.eql(u8, entry.name, ".zig-cache") or
std.mem.eql(u8, entry.name, "zig-out"))
{
continue;
}
const child_abs = try pathJoin(runtime.allocator, &.{ absolute_dir, entry.name });
const child_rel = try pathJoin(runtime.allocator, &.{ relative_dir, entry.name });
if (entry.kind == .unknown and try linuxPathIsDirectory(runtime.allocator, child_abs)) {
try discoverSqlFiles(runtime, child_abs, child_rel, sql_files);
continue;
}
switch (entry.kind) {
.directory => try discoverSqlFiles(runtime, child_abs, child_rel, sql_files),
.file, .unknown => {
if (std.mem.endsWith(u8, entry.name, ".sql")) {
try sql_files.append(runtime.allocator, child_rel);
}
},
else => {},
}
}
}
fn discoverMacroFiles(runtime: Runtime, absolute_dir: []const u8, relative_dir: []const u8, sql_files: *std.ArrayList([]const u8), yaml_files: *std.ArrayList([]const u8)) !void {
const fd = try openLinuxDirectory(runtime.allocator, absolute_dir);
defer closeLinuxFd(fd);
var buffer: [8192]u8 align(@alignOf(std.os.linux.dirent64)) = undefined;
var iter = LinuxDirReadState{ .fd = fd, .buffer = &buffer };
while (try nextLinuxDirectoryEntry(&iter)) |entry| {
if (entry.name.len == 0 or entry.name[0] == '.') continue;
if (std.mem.eql(u8, entry.name, "target") or
std.mem.eql(u8, entry.name, "dbt_packages") or
std.mem.eql(u8, entry.name, ".zig-cache") or
std.mem.eql(u8, entry.name, "zig-out"))
{
continue;
}
const child_abs = try pathJoin(runtime.allocator, &.{ absolute_dir, entry.name });
const child_rel = try pathJoin(runtime.allocator, &.{ relative_dir, entry.name });
if (entry.kind == .unknown and try linuxPathIsDirectory(runtime.allocator, child_abs)) {
try discoverMacroFiles(runtime, child_abs, child_rel, sql_files, yaml_files);
continue;
}
switch (entry.kind) {
.directory => try discoverMacroFiles(runtime, child_abs, child_rel, sql_files, yaml_files),
.file, .unknown => {
if (std.mem.endsWith(u8, entry.name, ".sql")) {
try sql_files.append(runtime.allocator, child_rel);
} else if (std.mem.endsWith(u8, entry.name, ".yml") or std.mem.endsWith(u8, entry.name, ".yaml")) {
try yaml_files.append(runtime.allocator, child_rel);
}
},
else => {},
}
}
}
const LinuxDirEntry = struct {
name: [:0]const u8,
kind: std.Io.File.Kind,
};
const LinuxDirReadState = struct {
fd: std.os.linux.fd_t,
buffer: []u8,
index: usize = 0,
end: usize = 0,
};
// Keep discovery synchronous and deterministic on mounts that report DT_UNKNOWN
// or behave poorly with the experimental std.Io directory iterator.
fn openLinuxDirectory(allocator: std.mem.Allocator, path: []const u8) !std.os.linux.fd_t {
const path_z = try allocator.dupeZ(u8, path);
defer allocator.free(path_z);
const rc = std.os.linux.openat(std.os.linux.AT.FDCWD, path_z.ptr, .{ .DIRECTORY = true, .CLOEXEC = true }, 0);
return switch (std.os.linux.errno(rc)) {
.SUCCESS => @intCast(rc),
.NOENT => error.FileNotFound,
.NOTDIR => error.NotDir,
.ACCES => error.AccessDenied,
else => error.Unexpected,
};
}
fn closeLinuxFd(fd: std.os.linux.fd_t) void {
_ = std.os.linux.close(fd);
}
fn linuxPathIsDirectory(allocator: std.mem.Allocator, path: []const u8) !bool {
const fd = openLinuxDirectory(allocator, path) catch |err| switch (err) {
error.NotDir => return false,
error.FileNotFound => return false,
else => return err,
};
closeLinuxFd(fd);
return true;
}
fn nextLinuxDirectoryEntry(state: *LinuxDirReadState) !?LinuxDirEntry {
while (true) {
if (state.index >= state.end) {
const rc = std.os.linux.getdents64(state.fd, state.buffer.ptr, state.buffer.len);
switch (std.os.linux.errno(rc)) {
.SUCCESS => {},
.INTR => continue,
else => return error.Unexpected,
}
if (rc == 0) return null;
state.index = 0;
state.end = rc;
}
const linux_entry: *align(1) std.os.linux.dirent64 = @ptrCast(&state.buffer[state.index]);
state.index += linux_entry.reclen;
const name_ptr: [*]u8 = &linux_entry.name;
const padded_name = name_ptr[0 .. linux_entry.reclen - @offsetOf(std.os.linux.dirent64, "name")];
const name_len = std.mem.findScalar(u8, padded_name, 0).?;
const name = name_ptr[0..name_len :0];
if (std.mem.eql(u8, name, ".") or std.mem.eql(u8, name, "..")) continue;
return .{
.name = name,
.kind = switch (linux_entry.type) {
std.os.linux.DT.DIR => .directory,
std.os.linux.DT.REG => .file,
std.os.linux.DT.LNK => .sym_link,
else => .unknown,
},
};
}
}
fn parseDocBlocks(runtime: Runtime, project_dir: []const u8, model_root: []const u8, relative_path: []const u8, package_name: []const u8, graph: *Graph) !void {
const path = try pathJoin(runtime.allocator, &.{ project_dir, relative_path });
const text = try std.Io.Dir.cwd().readFileAlloc(runtime.io, path, runtime.allocator, .limited(4 * 1024 * 1024));
var index: usize = 0;
while (std.mem.indexOfPos(u8, text, index, "{%")) |open| {
const close = std.mem.indexOfPos(u8, text, open + 2, "%}") orelse return error.MalformedDocsBlock;
const tag = std.mem.trim(u8, text[open + 2 .. close], " \t\r\n-");
if (!std.mem.startsWith(u8, tag, "docs")) {
index = close + 2;
continue;
}
if (tag.len <= "docs".len or !std.ascii.isWhitespace(tag["docs".len])) return error.MalformedDocsBlock;
const raw_name = std.mem.trim(u8, tag["docs".len..], " \t\r\n");
if (raw_name.len == 0 or std.mem.indexOfAny(u8, raw_name, " \t\r\n(){}") != null) return error.MalformedDocsBlock;
const end_open = std.mem.indexOfPos(u8, text, close + 2, "{%") orelse return error.MalformedDocsBlock;
const end_close = std.mem.indexOfPos(u8, text, end_open + 2, "%}") orelse return error.MalformedDocsBlock;
const end_tag = std.mem.trim(u8, text[end_open + 2 .. end_close], " \t\r\n-");
if (!std.mem.eql(u8, end_tag, "enddocs")) return error.MalformedDocsBlock;
const block_contents = std.mem.trim(u8, text[close + 2 .. end_open], " \t\r\n");
const unique_id = try std.fmt.allocPrint(runtime.allocator, "doc.{s}.{s}", .{ package_name, raw_name });
try graph.docs.append(runtime.allocator, .{
.unique_id = unique_id,
.name = try runtime.allocator.dupe(u8, raw_name),
.path = relativeUnderResourcePath(relative_path, model_root),
.original_file_path = relative_path,
.block_contents = try runtime.allocator.dupe(u8, block_contents),
});
index = end_close + 2;
}
}
fn parseMacros(runtime: Runtime, project_dir: []const u8, relative_path: []const u8, package_name: []const u8, graph: *Graph) !void {
const path = try pathJoin(runtime.allocator, &.{ project_dir, relative_path });
const text = try std.Io.Dir.cwd().readFileAlloc(runtime.io, path, runtime.allocator, .limited(4 * 1024 * 1024));
var index: usize = 0;
while (std.mem.indexOfPos(u8, text, index, "{%")) |open| {
const close = std.mem.indexOfPos(u8, text, open + 2, "%}") orelse return error.MalformedMacroBlock;
const tag = std.mem.trim(u8, text[open + 2 .. close], " \t\r\n-");
if (!isMacroOpenTag(tag)) {
index = close + 2;
continue;
}
const name_start = skipWs(tag, "macro".len);
if (name_start >= tag.len or !isIdentStart(tag[name_start])) return error.MalformedMacroBlock;
var name_end = name_start + 1;
while (name_end < tag.len and isIdentChar(tag[name_end])) name_end += 1;
const macro_name = tag[name_start..name_end];
const call_pos = skipWs(tag, name_end);
if (call_pos >= tag.len or tag[call_pos] != '(') return error.MalformedMacroBlock;
_ = findMatchingParen(tag, call_pos) orelse return error.MalformedMacroBlock;
const end = try findEndMacroTag(text, close + 2);
const macro_sql = std.mem.trim(u8, text[open .. end.close + 2], " \t\r\n");
const unique_id = try std.fmt.allocPrint(runtime.allocator, "macro.{s}.{s}", .{ package_name, macro_name });
try graph.macros.append(runtime.allocator, .{
.unique_id = unique_id,
.name = try runtime.allocator.dupe(u8, macro_name),
.path = relative_path,
.original_file_path = relative_path,
.macro_sql = try runtime.allocator.dupe(u8, macro_sql),
});
index = end.close + 2;
}
}
const MacroEndTag = struct {
close: usize,
};
fn isMacroOpenTag(tag: []const u8) bool {
return std.mem.startsWith(u8, tag, "macro") and tag.len > "macro".len and std.ascii.isWhitespace(tag["macro".len]);
}
fn findEndMacroTag(text: []const u8, start: usize) !MacroEndTag {
var index = start;
while (std.mem.indexOfPos(u8, text, index, "{%")) |open| {
const close = std.mem.indexOfPos(u8, text, open + 2, "%}") orelse return error.MalformedMacroBlock;
const tag = std.mem.trim(u8, text[open + 2 .. close], " \t\r\n-");
if (std.mem.eql(u8, tag, "endmacro")) return .{ .close = close };
index = close + 2;
}
return error.MalformedMacroBlock;
}
fn parseYamlProperties(runtime: Runtime, project_dir: []const u8, resource_root: []const u8, relative_path: []const u8, package_name: []const u8, graph: *Graph) !void {
const path = try pathJoin(runtime.allocator, &.{ project_dir, relative_path });
const text = try std.Io.Dir.cwd().readFileAlloc(runtime.io, path, runtime.allocator, .limited(4 * 1024 * 1024));
try parseSourcesFromText(runtime.allocator, text, relative_path, package_name, graph);
try parseExposuresFromText(runtime.allocator, text, resource_root, relative_path, package_name, graph);
try parseModelPropertiesFromText(runtime.allocator, text, relative_path, graph);
try parseMacroPropertiesFromText(runtime.allocator, text, relative_path, graph);
}
fn parseSourcesFromText(allocator: std.mem.Allocator, text: []const u8, relative_path: []const u8, package_name: []const u8, graph: *Graph) !void {
var in_sources = false;
var in_tables = false;
var sources_indent: usize = 0;
var source_item_indent: ?usize = null;
var table_item_indent: ?usize = null;
var current_source: ?[]const u8 = null;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |raw_line| {
const line = stripYamlComment(raw_line);
const trimmed = std.mem.trim(u8, line, " \t\r");
if (trimmed.len == 0) continue;
const indent = leadingSpaces(line);
if (std.mem.eql(u8, trimmed, "sources:")) {
in_sources = true;
in_tables = false;
sources_indent = indent;
source_item_indent = null;
table_item_indent = null;
continue;
}
if (!in_sources) continue;
if (indent <= sources_indent and !std.mem.eql(u8, trimmed, "sources:")) {
in_sources = false;
in_tables = false;
current_source = null;
continue;
}
if (std.mem.eql(u8, trimmed, "tables:")) {
in_tables = true;
table_item_indent = null;
continue;
}
if (std.mem.startsWith(u8, trimmed, "- name:")) {
const name = try dupTrimmedScalar(allocator, trimmed["- name:".len..]);
if (source_item_indent == null or indent == source_item_indent.?) {
source_item_indent = indent;
current_source = name;
in_tables = false;
table_item_indent = null;
} else if (in_tables and (table_item_indent == null or indent == table_item_indent.?)) {
table_item_indent = indent;
const source_name = current_source orelse return error.UnsupportedYaml;
const unique_id = try std.fmt.allocPrint(allocator, "source.{s}.{s}.{s}", .{ package_name, source_name, name });
try graph.sources.append(allocator, .{
.unique_id = unique_id,
.source_name = source_name,
.table_name = name,
.original_file_path = relative_path,
});
}
}
}
}
fn parseExposuresFromText(allocator: std.mem.Allocator, text: []const u8, resource_root: []const u8, relative_path: []const u8, package_name: []const u8, graph: *Graph) !void {
var in_exposures = false;
var in_depends_on = false;
var in_owner = false;
var in_config = false;
var in_meta = false;
var exposures_indent: usize = 0;
var exposure_item_indent: ?usize = null;
var depends_on_indent: usize = 0;
var owner_indent: usize = 0;
var config_indent: usize = 0;
var meta_indent: usize = 0;
var current_exposure: ?usize = null;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |raw_line| {
const line = stripYamlComment(raw_line);
const trimmed = std.mem.trim(u8, line, " \t\r");
if (trimmed.len == 0) continue;
const indent = leadingSpaces(line);
if (std.mem.eql(u8, trimmed, "exposures:")) {
in_exposures = true;
in_depends_on = false;
in_owner = false;
in_config = false;
in_meta = false;
exposures_indent = indent;
exposure_item_indent = null;
current_exposure = null;
continue;
}
if (!in_exposures) continue;
if (indent <= exposures_indent and !std.mem.eql(u8, trimmed, "exposures:")) {
in_exposures = false;
in_depends_on = false;
in_owner = false;
in_config = false;
in_meta = false;
current_exposure = null;
continue;
}
if (std.mem.startsWith(u8, trimmed, "- name:")) {
if (exposure_item_indent == null or indent == exposure_item_indent.?) {
exposure_item_indent = indent;
in_depends_on = false;
in_owner = false;
in_config = false;
in_meta = false;
const name = try dupTrimmedScalar(allocator, trimmed["- name:".len..]);
const unique_id = try std.fmt.allocPrint(allocator, "exposure.{s}.{s}", .{ package_name, name });
try graph.exposures.append(allocator, .{
.unique_id = unique_id,
.name = name,
.path = relativeUnderResourcePath(relative_path, resource_root),
.original_file_path = relative_path,
});
current_exposure = graph.exposures.items.len - 1;
continue;
}
}
const exposure_index = current_exposure orelse continue;
if (exposure_item_indent) |item_indent| {
if (indent <= item_indent and !std.mem.startsWith(u8, trimmed, "- name:")) {
in_depends_on = false;
in_owner = false;
in_config = false;
in_meta = false;
}
}
if (std.mem.eql(u8, trimmed, "depends_on:")) {
in_depends_on = true;
in_owner = false;
in_config = false;
in_meta = false;
depends_on_indent = indent;
continue;
}
if (std.mem.eql(u8, trimmed, "owner:")) {
in_owner = true;
in_depends_on = false;
in_config = false;
in_meta = false;
owner_indent = indent;
continue;
}
if (std.mem.eql(u8, trimmed, "config:")) {
in_config = true;
in_depends_on = false;
in_owner = false;
in_meta = false;
config_indent = indent;
continue;
}
if (std.mem.eql(u8, trimmed, "meta:")) {
in_meta = true;
in_depends_on = false;
in_owner = false;
meta_indent = indent;
continue;
}
if (in_depends_on and indent <= depends_on_indent) in_depends_on = false;
if (in_owner and indent <= owner_indent) in_owner = false;
if (in_config and indent <= config_indent) in_config = false;
if (in_meta and indent <= meta_indent) in_meta = false;
if (in_depends_on and std.mem.startsWith(u8, trimmed, "- ")) {