-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResolveSqlProjAndInputs.cs
More file actions
836 lines (721 loc) · 32.4 KB
/
ResolveSqlProjAndInputs.cs
File metadata and controls
836 lines (721 loc) · 32.4 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
using System.Text.RegularExpressions;
using System.Xml.Linq;
using JD.Efcpt.Build.Tasks.Chains;
using JD.Efcpt.Build.Tasks.Decorators;
using JD.Efcpt.Build.Tasks.Extensions;
using Microsoft.Build.Framework;
using PatternKit.Behavioral.Strategy;
using PatternKit.Creational.Builder;
using Task = Microsoft.Build.Utilities.Task;
namespace JD.Efcpt.Build.Tasks;
/// <summary>
/// MSBuild task that resolves the SQL project to use and locates efcpt configuration, renaming, and template inputs.
/// </summary>
/// <remarks>
/// <para>
/// This task is the first stage of the efcpt MSBuild pipeline. It selects a single SQL project file
/// (<c>.sqlproj</c> or <c>.csproj</c>/<c>.fsproj</c> using a supported SQL SDK)
/// associated with the current project and probes for configuration artifacts in the following order:
/// <list type="number">
/// <item><description>Explicit override properties (<see cref="SqlProjOverride"/>, <see cref="ConfigOverride"/>, <see cref="RenamingOverride"/>, <see cref="TemplateDirOverride"/>) when they contain an explicit path.</description></item>
/// <item><description>Files or directories next to the consuming project (<see cref="ProjectDirectory"/>).</description></item>
/// <item><description>Files or directories located under <see cref="SolutionDir"/> when <see cref="ProbeSolutionDir"/> evaluates to <c>true</c>.</description></item>
/// <item><description>Packaged defaults under <see cref="DefaultsRoot"/> (typically the <c>Defaults</c> folder from the NuGet package).</description></item>
/// </list>
/// If resolution fails for any of the inputs, the task throws an exception and the build fails.
/// </para>
/// <para>
/// For the SQL project reference, the task inspects <see cref="ProjectReferences"/> and enforces that exactly
/// one SQL project reference is present unless <see cref="SqlProjOverride"/> is supplied. The resolved
/// path is validated on disk.
/// </para>
/// <para>
/// When <see cref="DumpResolvedInputs"/> evaluates to <c>true</c>, a <c>resolved-inputs.json</c> file is
/// written to <see cref="OutputDir"/> containing the resolved paths. This is primarily intended for
/// debugging and diagnostics.
/// </para>
/// </remarks>
#if NET7_0_OR_GREATER
public sealed partial class ResolveSqlProjAndInputs : Task
#else
public sealed class ResolveSqlProjAndInputs : Task
#endif
{
/// <summary>
/// Full path to the consuming project file.
/// </summary>
[Required]
public string ProjectFullPath { get; set; } = "";
/// <summary>
/// Directory that contains the consuming project file.
/// </summary>
[Required]
public string ProjectDirectory { get; set; } = "";
/// <summary>
/// Active build configuration (for example <c>Debug</c> or <c>Release</c>).
/// </summary>
[Required]
public string Configuration { get; set; } = "";
/// <summary>
/// Project references of the consuming project.
/// </summary>
/// <remarks>
/// The task inspects this item group to locate a single SQL project reference when
/// <see cref="SqlProjOverride"/> is not provided.
/// </remarks>
public ITaskItem[] ProjectReferences { get; set; } = [];
/// <summary>
/// Optional override path for the SQL project to use.
/// </summary>
/// <value>
/// When set to a non-empty explicit path (rooted or containing a directory separator), this value
/// is resolved against <see cref="ProjectDirectory"/> and used instead of probing
/// <see cref="ProjectReferences"/>.
/// </value>
public string SqlProjOverride { get; set; } = "";
/// <summary>
/// Optional override path for the efcpt configuration JSON file.
/// </summary>
public string ConfigOverride { get; set; } = "";
/// <summary>
/// Optional override path for the efcpt renaming JSON file.
/// </summary>
public string RenamingOverride { get; set; } = "";
/// <summary>
/// Optional override path for the efcpt template directory.
/// </summary>
public string TemplateDirOverride { get; set; } = "";
/// <summary>
/// Optional explicit connection string override. When set, connection string mode is used instead of .sqlproj mode.
/// </summary>
public string EfcptConnectionString { get; set; } = "";
/// <summary>
/// Optional path to appsettings.json file containing connection strings.
/// </summary>
public string EfcptAppSettings { get; set; } = "";
/// <summary>
/// Optional path to app.config or web.config file containing connection strings.
/// </summary>
public string EfcptAppConfig { get; set; } = "";
/// <summary>
/// Connection string key name to use from configuration files. Defaults to "DefaultConnection".
/// </summary>
public string EfcptConnectionStringName { get; set; } = "DefaultConnection";
/// <summary>
/// Solution directory to probe when searching for configuration, renaming, and template assets.
/// </summary>
/// <remarks>
/// Typically bound to the <c>EfcptSolutionDir</c> MSBuild property. Resolved relative to
/// <see cref="ProjectDirectory"/> when not rooted.
/// </remarks>
public string SolutionDir { get; set; } = "";
/// <summary>
/// Solution file path, when building inside a solution.
/// </summary>
/// <remarks>
/// Typically bound to the <c>SolutionPath</c> MSBuild property. Resolved relative to
/// <see cref="ProjectDirectory"/> when not rooted.
/// </remarks>
public string SolutionPath { get; set; } = "";
/// <summary>
/// Controls whether the solution directory should be probed when locating configuration assets.
/// </summary>
/// <value>
/// Interpreted similarly to a boolean value; the strings <c>true</c>, <c>1</c>, and <c>yes</c>
/// enable probing. Defaults to <c>true</c>.
/// </value>
public string ProbeSolutionDir { get; set; } = "true";
/// <summary>
/// Output directory that will receive downstream artifacts.
/// </summary>
/// <remarks>
/// This task ensures the directory exists and uses it as the location for
/// <c>resolved-inputs.json</c> when <see cref="DumpResolvedInputs"/> is enabled.
/// </remarks>
[Required]
public string OutputDir { get; set; } = "";
/// <summary>
/// Root directory that contains packaged default configuration and templates.
/// </summary>
/// <remarks>
/// Typically points at the <c>Defaults</c> folder shipped as <c>contentFiles</c> in the NuGet
/// package. When set, this location is probed after the project and solution directories.
/// </remarks>
public string DefaultsRoot { get; set; } = "";
/// <summary>
/// Controls whether the task writes a diagnostic JSON file describing resolved inputs.
/// </summary>
/// <value>
/// When interpreted as <c>true</c>, a <c>resolved-inputs.json</c> file is written to
/// <see cref="OutputDir"/>.
/// </value>
public string DumpResolvedInputs { get; set; } = "false";
/// <summary>
/// Resolved full path to the SQL project to use.
/// </summary>
[Output]
public string SqlProjPath { get; set; } = "";
/// <summary>
/// Resolved full path to the configuration JSON file.
/// </summary>
[Output]
public string ResolvedConfigPath { get; set; } = "";
/// <summary>
/// Resolved full path to the renaming JSON file.
/// </summary>
[Output]
public string ResolvedRenamingPath { get; set; } = "";
/// <summary>
/// Resolved full path to the template directory.
/// </summary>
[Output]
public string ResolvedTemplateDir { get; set; } = "";
/// <summary>
/// Resolved connection string (if using connection string mode).
/// </summary>
[Output]
public string ResolvedConnectionString { get; set; } = "";
/// <summary>
/// Indicates whether the build will use connection string mode (true) or .sqlproj mode (false).
/// </summary>
[Output]
public string UseConnectionString { get; set; } = "false";
/// <summary>
/// Indicates whether the resolved configuration file is the library default (not user-provided).
/// </summary>
/// <value>
/// The string "true" when the configuration was resolved from <see cref="DefaultsRoot"/>;
/// otherwise "false".
/// </value>
[Output]
public string IsUsingDefaultConfig { get; set; } = "false";
#region Context Records
private readonly record struct SqlProjResolutionContext(
string SqlProjOverride,
string ProjectDirectory,
IReadOnlyList<string> SqlProjReferences
);
private readonly record struct SqlProjValidationResult(
bool IsValid,
string? SqlProjPath,
string? ErrorMessage
);
private readonly record struct ResolutionState(
string SqlProjPath,
string ConfigPath,
string RenamingPath,
string TemplateDir,
string ConnectionString,
bool UseConnectionStringMode
);
#endregion
#region Strategies
private static readonly Lazy<Strategy<SqlProjResolutionContext, SqlProjValidationResult>> SqlProjValidationStrategy = new(()
=> Strategy<SqlProjResolutionContext, SqlProjValidationResult>.Create()
// Branch 1: Explicit override provided
.When(static (in ctx) =>
!string.IsNullOrWhiteSpace(ctx.SqlProjOverride))
.Then((in ctx) =>
{
var path = PathUtils.FullPath(ctx.SqlProjOverride, ctx.ProjectDirectory);
return new SqlProjValidationResult(
IsValid: true,
SqlProjPath: path,
ErrorMessage: null);
})
// Branch 2: No SQL project references found
.When(static (in ctx) =>
ctx.SqlProjReferences.Count == 0)
.Then(static (in _) =>
new SqlProjValidationResult(
IsValid: false,
SqlProjPath: null,
ErrorMessage: "No SQL project ProjectReference found. Add a single .sqlproj or MSBuild.Sdk.SqlProj reference, or set EfcptSqlProj."))
// Branch 3: Multiple SQL project references (ambiguous)
.When(static (in ctx) =>
ctx.SqlProjReferences.Count > 1)
.Then((in ctx) =>
new SqlProjValidationResult(
IsValid: false,
SqlProjPath: null,
ErrorMessage:
$"Multiple SQL project references detected ({string.Join(", ", ctx.SqlProjReferences)}). Exactly one is allowed; use EfcptSqlProj to disambiguate."))
// Branch 4: Exactly one reference (success path)
.Default((in ctx) =>
{
var resolved = ctx.SqlProjReferences[0];
return File.Exists(resolved)
? new SqlProjValidationResult(IsValid: true, SqlProjPath: resolved, ErrorMessage: null)
: new SqlProjValidationResult(
IsValid: false,
SqlProjPath: null,
ErrorMessage: $"SQL project ProjectReference not found on disk: {resolved}");
})
.Build());
#endregion
/// <inheritdoc />
public override bool Execute()
{
var decorator = TaskExecutionDecorator.Create(ExecuteCore);
var ctx = new TaskExecutionContext(Log, nameof(ResolveSqlProjAndInputs));
return decorator.Execute(in ctx);
}
private bool ExecuteCore(TaskExecutionContext ctx)
{
// Normalize all string properties to empty string if null.
// MSBuild on .NET Framework can set properties to null instead of empty string,
// which causes NullReferenceExceptions in downstream code.
NormalizeProperties();
var log = new BuildLog(ctx.Logger, "");
// Log runtime context for troubleshooting
var runtime = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription;
log.Detail($"MSBuild Runtime: {runtime}");
log.Detail($"ProjectReferences Count: {ProjectReferences?.Length ?? 0}");
log.Detail($"SolutionPath: {SolutionPath}");
Directory.CreateDirectory(OutputDir);
var resolutionState = BuildResolutionState(log);
// Set output properties
SqlProjPath = resolutionState.SqlProjPath;
ResolvedConfigPath = resolutionState.ConfigPath;
ResolvedRenamingPath = resolutionState.RenamingPath;
ResolvedTemplateDir = resolutionState.TemplateDir;
ResolvedConnectionString = resolutionState.ConnectionString;
UseConnectionString = resolutionState.UseConnectionStringMode ? "true" : "false";
IsUsingDefaultConfig = IsConfigFromDefaults(resolutionState.ConfigPath) ? "true" : "false";
if (DumpResolvedInputs.IsTrue())
WriteDumpFile(resolutionState);
log.Detail(resolutionState.UseConnectionStringMode
? $"Resolved connection string from: {resolutionState.ConnectionString}"
: $"Resolved SQL project: {SqlProjPath}");
return true;
}
private TargetContext DetermineMode(BuildLog log)
=> TryExplicitConnectionString(log)
?? TrySqlProjDetection(log)
?? TryAutoDiscoveredConnectionString(log)
?? new(false, "", ""); // Neither found - validation will fail later
private TargetContext? TryExplicitConnectionString(BuildLog log)
{
if (!HasExplicitConnectionConfig())
return null;
var connectionString = TryResolveConnectionString(log);
if (string.IsNullOrWhiteSpace(connectionString))
{
log.Warn("JD0016", "Explicit connection string configuration provided but failed to resolve. Falling back to .sqlproj detection.");
return null;
}
log.Detail("Using connection string mode due to explicit configuration property");
return new(true, connectionString, "");
}
private TargetContext? TrySqlProjDetection(BuildLog log)
{
try
{
var sqlProjPath = ResolveSqlProjWithValidation(log);
if (string.IsNullOrWhiteSpace(sqlProjPath))
return null;
WarnIfAutoDiscoveredConnectionStringExists(log);
return new(false, "", sqlProjPath);
}
catch (Exception ex)
{
// Log detailed exception information to help users diagnose SQL project resolution issues.
// This is intentionally more verbose than other catch blocks in this file because this
// specific failure point is commonly reported by users and requires diagnostic context.
log.Warn($"SQL project detection failed: {ex.Message}");
log.Detail($"Exception details: {ex}");
return null;
}
}
private TargetContext? TryAutoDiscoveredConnectionString(BuildLog log)
{
var connectionString = TryResolveAutoDiscoveredConnectionString(log);
if (string.IsNullOrWhiteSpace(connectionString))
return null;
log.Info("No .sqlproj found. Using auto-discovered connection string.");
return new(true, connectionString, "");
}
private bool HasExplicitConnectionConfig()
=> PathUtils.HasValue(EfcptConnectionString)
|| PathUtils.HasValue(EfcptAppSettings)
|| PathUtils.HasValue(EfcptAppConfig);
private void WarnIfAutoDiscoveredConnectionStringExists(BuildLog log)
{
var autoDiscoveredConnectionString = TryResolveAutoDiscoveredConnectionString(log);
if (!string.IsNullOrWhiteSpace(autoDiscoveredConnectionString))
{
log.Warn("JD0015",
"Both .sqlproj and auto-discovered connection strings detected. Using .sqlproj mode (default behavior). " +
"Set EfcptConnectionString explicitly to use connection string mode.");
}
}
private record TargetContext(bool UseConnectionStringMode, string ConnectionString, string SqlProjPath);
private ResolutionState BuildResolutionState(BuildLog log)
{
// Step 1: Determine mode using priority-based resolution
log.Detail("BuildResolutionState: Step 1 - DetermineMode starting");
TargetContext? targetContext = null;
try
{
targetContext = DetermineMode(log);
}
catch (Exception ex)
{
log.Warn($"BuildResolutionState: DetermineMode threw: {ex.GetType().Name}: {ex.Message}");
throw;
}
var useConnectionStringMode = targetContext?.UseConnectionStringMode ?? false;
var connectionString = targetContext?.ConnectionString ?? "";
var sqlProjPath = targetContext?.SqlProjPath ?? "";
log.Detail($"BuildResolutionState: Step 1 complete - UseConnectionStringMode={useConnectionStringMode}, " +
$"ConnectionString={(string.IsNullOrEmpty(connectionString) ? "(empty)" : "(set)")}, " +
$"SqlProjPath={(string.IsNullOrEmpty(sqlProjPath) ? "(empty)" : sqlProjPath)}");
// Step 2: Resolve config file
log.Detail("BuildResolutionState: Step 2 - ResolveFile for config starting");
log.Detail($" ConfigOverride={(ConfigOverride ?? "(null)")}");
log.Detail($" ProjectDirectory={(ProjectDirectory ?? "(null)")}");
log.Detail($" DefaultsRoot={(DefaultsRoot ?? "(null)")}");
string configPath;
try
{
configPath = ResolveFile(ConfigOverride ?? "", "efcpt-config.json");
}
catch (Exception ex)
{
log.Warn($"BuildResolutionState: ResolveFile(config) threw: {ex.GetType().Name}: {ex.Message}");
throw;
}
log.Detail($"BuildResolutionState: Step 2 complete - ConfigPath={configPath}");
// Step 3: Resolve renaming file
log.Detail("BuildResolutionState: Step 3 - ResolveFile for renaming starting");
log.Detail($" RenamingOverride={(RenamingOverride ?? "(null)")}");
string renamingPath;
try
{
renamingPath = ResolveFile(
RenamingOverride ?? "",
"efcpt.renaming.json",
"efcpt-renaming.json",
"efpt.renaming.json");
}
catch (Exception ex)
{
log.Warn($"BuildResolutionState: ResolveFile(renaming) threw: {ex.GetType().Name}: {ex.Message}");
throw;
}
log.Detail($"BuildResolutionState: Step 3 complete - RenamingPath={renamingPath}");
// Step 4: Resolve template directory
log.Detail("BuildResolutionState: Step 4 - ResolveDir for templates starting");
log.Detail($" TemplateDirOverride={(TemplateDirOverride ?? "(null)")}");
string templateDir;
try
{
templateDir = ResolveDir(
TemplateDirOverride ?? "",
"Template",
"CodeTemplates",
"Templates");
}
catch (Exception ex)
{
log.Warn($"BuildResolutionState: ResolveDir(templates) threw: {ex.GetType().Name}: {ex.Message}");
throw;
}
log.Detail($"BuildResolutionState: Step 4 complete - TemplateDir={templateDir}");
// Step 5: Validate that either connection string or SQL project was resolved
log.Detail("BuildResolutionState: Step 5 - Validation");
if (useConnectionStringMode)
{
if (string.IsNullOrWhiteSpace(connectionString))
throw new InvalidOperationException(
"Connection string resolution failed. No connection string could be resolved from configuration.");
}
else
{
if (string.IsNullOrWhiteSpace(sqlProjPath))
throw new InvalidOperationException(
"SqlProj resolution failed. No SQL project reference found. " +
"Add a .sqlproj ProjectReference, set EfcptSqlProj property, or provide a connection string via " +
"EfcptConnectionString/appsettings.json/app.config. Check build output for detailed error messages.");
}
log.Detail("BuildResolutionState: All steps complete, building ResolutionState");
// Build the final state
return new ResolutionState(
SqlProjPath: sqlProjPath,
ConfigPath: configPath,
RenamingPath: renamingPath,
TemplateDir: templateDir,
ConnectionString: connectionString,
UseConnectionStringMode: useConnectionStringMode
);
}
private string ResolveSqlProjWithValidation(BuildLog log)
{
// ProjectReferences may be null on some .NET Framework MSBuild hosts
var references = ProjectReferences ?? [];
var sqlRefs = references
.Where(x => x?.ItemSpec != null)
.Select(x => PathUtils.FullPath(x.ItemSpec, ProjectDirectory))
.Where(SqlProjectDetector.IsSqlProjectReference)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
if (!PathUtils.HasValue(SqlProjOverride) && sqlRefs.Count == 0)
{
var fallback = TryResolveFromSolution();
if (!string.IsNullOrWhiteSpace(fallback))
{
log.Warn("No SQL project references found in project; using SQL project detected from solution: " + fallback);
sqlRefs.Add(fallback);
}
}
var ctx = new SqlProjResolutionContext(
SqlProjOverride: SqlProjOverride,
ProjectDirectory: ProjectDirectory,
SqlProjReferences: sqlRefs);
var result = SqlProjValidationStrategy.Value.Execute(in ctx);
return result.IsValid
? result.SqlProjPath!
: throw new InvalidOperationException(result.ErrorMessage);
}
private string? TryResolveFromSolution()
{
if (!PathUtils.HasValue(SolutionPath))
return null;
var solutionPath = PathUtils.FullPath(SolutionPath, ProjectDirectory);
if (!File.Exists(solutionPath))
return null;
var matches = ScanSolutionForSqlProjects(solutionPath).ToList();
return matches.Count switch
{
< 1 => throw new InvalidOperationException("No SQL project references found and none detected in solution."),
1 => matches[0].Path,
> 1 => throw new InvalidOperationException(
$"Multiple SQL projects detected while scanning solution '{solutionPath}' ({string.Join(", ", matches.Select(m => m.Path))}). Reference one directly or set EfcptSqlProj."),
};
}
private static IEnumerable<(string Name, string Path)> ScanSolutionForSqlProjects(string solutionPath)
{
var ext = Path.GetExtension(solutionPath);
if (ext.EqualsIgnoreCase(".slnx"))
{
foreach (var match in ScanSlnxForSqlProjects(solutionPath))
yield return match;
yield break;
}
foreach (var match in ScanSlnForSqlProjects(solutionPath))
yield return match;
}
private static IEnumerable<(string Name, string Path)> ScanSlnForSqlProjects(string solutionPath)
{
var solutionDir = Path.GetDirectoryName(solutionPath) ?? "";
List<string> lines;
try
{
lines = File.ReadLines(solutionPath).ToList();
}
catch
{
yield break;
}
foreach (var line in lines)
{
var match = SolutionProjectLine.Match(line);
if (!match.Success)
continue;
var nameGroup = match.Groups["name"];
var pathGroup = match.Groups["path"];
// Skip if required groups are missing or empty
if (!nameGroup.Success || !pathGroup.Success ||
string.IsNullOrWhiteSpace(nameGroup.Value) ||
string.IsNullOrWhiteSpace(pathGroup.Value))
continue;
var name = nameGroup.Value;
var relativePath = pathGroup.Value
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
if (!IsProjectFile(Path.GetExtension(relativePath)))
continue;
var fullPath = Path.GetFullPath(Path.Combine(solutionDir, relativePath));
if (!File.Exists(fullPath))
continue;
if (SqlProjectDetector.IsSqlProjectReference(fullPath))
yield return (name, fullPath);
}
}
private static IEnumerable<(string Name, string Path)> ScanSlnxForSqlProjects(string solutionPath)
{
var solutionDir = Path.GetDirectoryName(solutionPath) ?? "";
XDocument doc;
try
{
doc = XDocument.Load(solutionPath);
}
catch
{
yield break;
}
foreach (var project in doc.Descendants().Where(e => e.Name.LocalName == "Project"))
{
var pathAttr = project.Attributes().FirstOrDefault(a => a.Name.LocalName == "Path");
if (pathAttr == null || string.IsNullOrWhiteSpace(pathAttr.Value))
continue;
var relativePath = pathAttr.Value.Trim()
.Replace('\\', Path.DirectorySeparatorChar)
.Replace('/', Path.DirectorySeparatorChar);
if (!IsProjectFile(Path.GetExtension(relativePath)))
continue;
var fullPath = Path.GetFullPath(Path.Combine(solutionDir, relativePath));
if (!File.Exists(fullPath))
continue;
var nameAttr = project.Attributes().FirstOrDefault(a => a.Name.LocalName == "Name");
var name = string.IsNullOrWhiteSpace(nameAttr?.Value)
? Path.GetFileNameWithoutExtension(fullPath)
: nameAttr.Value;
if (SqlProjectDetector.IsSqlProjectReference(fullPath))
yield return (name, fullPath);
}
}
private static bool IsProjectFile(string? extension)
=> extension.EqualsIgnoreCase(".sqlproj") ||
extension.EqualsIgnoreCase(".csproj") ||
extension.EqualsIgnoreCase(".fsproj");
private static readonly Regex SolutionProjectLine = SolutionProjectLineRegex();
private string ResolveFile(string overridePath, params string[] fileNames)
{
// Ensure all inputs are non-null
overridePath ??= "";
var projectDir = ProjectDirectory ?? "";
var solutionDir = SolutionDir ?? "";
var defaultsRoot = DefaultsRoot ?? "";
var probeSolutionDir = (ProbeSolutionDir ?? "true").IsTrue();
var chain = FileResolutionChain.Build();
if (chain == null)
throw new InvalidOperationException("FileResolutionChain.Build() returned null");
var candidates = EnumerableExtensions.BuildCandidateNames(overridePath, fileNames);
if (candidates == null)
throw new InvalidOperationException("BuildCandidateNames returned null");
var context = new FileResolutionContext(
OverridePath: overridePath,
ProjectDirectory: projectDir,
SolutionDir: solutionDir,
ProbeSolutionDir: probeSolutionDir,
DefaultsRoot: defaultsRoot,
FileNames: candidates);
return chain.Execute(in context, out var result)
? result!
: throw new InvalidOperationException("Chain should always produce result or throw");
}
private string ResolveDir(string overridePath, params string[] dirNames)
{
// Ensure all inputs are non-null
overridePath ??= "";
var projectDir = ProjectDirectory ?? "";
var solutionDir = SolutionDir ?? "";
var defaultsRoot = DefaultsRoot ?? "";
var probeSolutionDir = (ProbeSolutionDir ?? "true").IsTrue();
var chain = DirectoryResolutionChain.Build();
if (chain == null)
throw new InvalidOperationException("DirectoryResolutionChain.Build() returned null");
var candidates = EnumerableExtensions.BuildCandidateNames(overridePath, dirNames);
if (candidates == null)
throw new InvalidOperationException("BuildCandidateNames returned null");
var context = new DirectoryResolutionContext(
OverridePath: overridePath,
ProjectDirectory: projectDir,
SolutionDir: solutionDir,
ProbeSolutionDir: probeSolutionDir,
DefaultsRoot: defaultsRoot,
DirNames: candidates);
return chain.Execute(in context, out var result)
? result!
: throw new InvalidOperationException("Chain should always produce result or throw");
}
private bool IsConfigFromDefaults(string configPath)
{
if (string.IsNullOrWhiteSpace(DefaultsRoot) || string.IsNullOrWhiteSpace(configPath))
return false;
var normalizedConfig = Path.GetFullPath(configPath);
var normalizedDefaults = Path.GetFullPath(DefaultsRoot).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
+ Path.DirectorySeparatorChar;
return normalizedConfig.StartsWith(normalizedDefaults, StringComparison.OrdinalIgnoreCase);
}
private string? TryResolveConnectionString(BuildLog log)
{
var chain = ConnectionStringResolutionChain.Build();
var context = new ConnectionStringResolutionContext(
ExplicitConnectionString: EfcptConnectionString,
EfcptAppSettings: EfcptAppSettings,
EfcptAppConfig: EfcptAppConfig,
ConnectionStringName: EfcptConnectionStringName,
ProjectDirectory: ProjectDirectory,
Log: log);
return chain.Execute(in context, out var result)
? result
: null; // Fallback to .sqlproj mode
}
private string? TryResolveAutoDiscoveredConnectionString(BuildLog log)
{
// Only try auto-discovery (not explicit properties like EfcptConnectionString, EfcptAppSettings, EfcptAppConfig)
var chain = ConnectionStringResolutionChain.Build();
var context = new ConnectionStringResolutionContext(
ExplicitConnectionString: "", // Ignore explicit connection string
EfcptAppSettings: "", // Ignore explicit app settings path
EfcptAppConfig: "", // Ignore explicit app config path
ConnectionStringName: EfcptConnectionStringName,
ProjectDirectory: ProjectDirectory,
Log: log);
return chain.Execute(in context, out var result)
? result
: null;
}
private void WriteDumpFile(ResolutionState state)
{
var dump =
$"""
"project": "{ProjectFullPath}",
"sqlproj": "{state.SqlProjPath}",
"config": "{state.ConfigPath}",
"renaming": "{state.RenamingPath}",
"template": "{state.TemplateDir}",
"connectionString": "{state.ConnectionString}",
"useConnectionStringMode": "{state.UseConnectionStringMode}",
"output": "{OutputDir}"
""";
File.WriteAllText(Path.Combine(OutputDir, "resolved-inputs.json"), dump);
}
/// <summary>
/// Normalizes all string properties to empty string if null.
/// MSBuild on .NET Framework can set properties to null instead of empty string.
/// </summary>
private void NormalizeProperties()
{
ProjectFullPath ??= "";
ProjectDirectory ??= "";
Configuration ??= "";
ProjectReferences ??= [];
SqlProjOverride ??= "";
ConfigOverride ??= "";
RenamingOverride ??= "";
TemplateDirOverride ??= "";
EfcptConnectionString ??= "";
EfcptAppSettings ??= "";
EfcptAppConfig ??= "";
EfcptConnectionStringName ??= "DefaultConnection";
SolutionDir ??= "";
SolutionPath ??= "";
ProbeSolutionDir ??= "true";
OutputDir ??= "";
DefaultsRoot ??= "";
DumpResolvedInputs ??= "false";
}
#if NET7_0_OR_GREATER
[GeneratedRegex("^\\s*Project\\(\"(?<typeGuid>[^\"]+)\"\\)\\s*=\\s*\"(?<name>[^\"]+)\",\\s*\"(?<path>[^\"]+)\",\\s*\"(?<guid>[^\"]+)\"",
RegexOptions.Compiled | RegexOptions.Multiline)]
private static partial Regex SolutionProjectLineRegex();
#else
private static readonly Regex _solutionProjectLineRegex = new(
"^\\s*Project\\(\"(?<typeGuid>[^\"]+)\"\\)\\s*=\\s*\"(?<name>[^\"]+)\",\\s*\"(?<path>[^\"]+)\",\\s*\"(?<guid>[^\"]+)\"",
RegexOptions.Compiled | RegexOptions.Multiline);
private static Regex SolutionProjectLineRegex() => _solutionProjectLineRegex;
#endif
}