Skip to content

Commit

Permalink
VCI-779: Fix codesmells
Browse files Browse the repository at this point in the history
  • Loading branch information
krankenbro committed Jan 24, 2024
1 parent ae04d18 commit 4a11354
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 138 deletions.
23 changes: 10 additions & 13 deletions src/VirtoCommerce.Build/Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -218,20 +218,20 @@ public static Solution Solution

protected static AbsolutePath DirectoryBuildPropsPath => Solution.Directory / "Directory.Build.props";

protected string ZipFileName => IsModule
protected static string ZipFileName => IsModule
? $"{ModuleManifest.Id}_{ReleaseVersion}.zip"
: $"{WebProject.Solution.Name}.{ReleaseVersion}.zip";

protected string ZipFilePath => ArtifactsDirectory / ZipFileName;
protected static string ZipFilePath => ArtifactsDirectory / ZipFileName;
protected static string GitRepositoryName => GitRepository.Identifier.Split('/')[1];

protected static string ModulePackageUrl => CustomModulePackageUri.IsNullOrEmpty()
? $"https://github.com/VirtoCommerce/{GitRepositoryName}/releases/download/{ReleaseVersion}/{ModuleManifest.Id}_{ReleaseVersion}.zip"
: CustomModulePackageUri;

protected GitRepository ModulesRepository => GitRepository.FromUrl(ModulesJsonRepoUrl);
protected static GitRepository ModulesRepository => GitRepository.FromUrl(ModulesJsonRepoUrl);

protected bool IsModule => ModuleManifestFile.FileExists();
protected static bool IsModule => ModuleManifestFile.FileExists();

public Target Clean => _ => _
.Before(Restore)
Expand Down Expand Up @@ -467,7 +467,7 @@ public static Solution Solution

private static void PublishMethod(Project webProject, string output, Configuration configuration)
{
Assert.NotNull(webProject, "Web Project is not found!");
webProject.NotNull("Web Project is not found!");
DotNetPublish(settings => settings
.SetProcessWorkingDirectory(webProject.Directory)
.EnableNoRestore()
Expand Down Expand Up @@ -737,10 +737,7 @@ private static void WebPackBuildMethod(Project webProject)

public Target StartAnalyzer => _ => _
.DependsOn(SonarQubeStart, SonarQubeEnd)
.Executes(() =>
{
Log.Information("Sonar validation done.");
});
.Executes(() => Log.Information("Sonar validation done."));

public Target MassPullAndBuild => _ => _
.Requires(() => ModulesFolderPath)
Expand Down Expand Up @@ -923,7 +920,7 @@ public static void CustomDotnetLogger(OutputType type, string text)
}
}

public void ChangeProjectVersion(string versionPrefix = null, string versionSuffix = null)
public static void ChangeProjectVersion(string versionPrefix = null, string versionSuffix = null)
{
//theme
if (IsTheme)
Expand Down Expand Up @@ -1015,7 +1012,7 @@ private static void SaveXml(string filePath, XmlDocument xmlDocument)
xmlDocument.Save(writer);
}

private string GetThemeVersion(string packageJsonPath)
private static string GetThemeVersion(string packageJsonPath)
{
var json = JsonDocument.Parse(File.ReadAllText(packageJsonPath));

Expand All @@ -1042,7 +1039,7 @@ public void IncrementVersionPatch()
CustomVersionPrefix = newPrefix;
}

private async Task<string> SendSwaggerSchemaToValidator(HttpClient httpClient, string schemaPath,
private static async Task<string> SendSwaggerSchemaToValidator(HttpClient httpClient, string schemaPath,
string validatorUri)
{
var swaggerSchema = await File.ReadAllTextAsync(schemaPath);
Expand Down Expand Up @@ -1102,7 +1099,7 @@ private async Task PublishRelease(string owner, string repo, string token, strin

var release = await githubClient.Repository.Release.Create(owner, repo, newRelease);

using var artifactStream = File.OpenRead(artifactPath);
await using var artifactStream = File.OpenRead(artifactPath);
var assetUpload = new ReleaseAssetUpload
{
FileName = Path.GetFileName(artifactPath),
Expand Down
105 changes: 51 additions & 54 deletions src/VirtoCommerce.Build/GrabMigrator/GrabMigrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ internal class GrabMigrator
{
public void Do(string configFilePath)
{
OutBox(@"VirtoCommerce EF-migration grabbing and applying tool.");
OutBox("VirtoCommerce EF-migration grabbing and applying tool.");

if (!string.IsNullOrEmpty(configFilePath))
{
if (File.Exists(configFilePath))
{
try
{
Out(@"Read config file...");
Out("Read config file...");

var config = (Config)JsonSerializer.Deserialize(File.ReadAllText(configFilePath), typeof(Config));

Expand All @@ -44,16 +44,16 @@ public void Do(string configFilePath)
EnableApplyMode(config, sqlStatements);
}

OutBox(@"Complete!");
OutBox("Complete!");
}
catch (Exception exc)
{
Fail($@"An exception occurred: {exc}");
Fail($"An exception occurred: {exc}");
}
}
else
{
Fail($@"Configuration file {configFilePath} not found!");
Fail($"Configuration file {configFilePath} not found!");
}
}
else
Expand All @@ -70,51 +70,49 @@ private void EnableApplyMode(Config config, Dictionary<string, List<string>> sql

sqlStatements ??= ReadSavedStatements(config.StatementsDirectory);

Out(@"Read platform config file...");
Out("Read platform config file...");

var connectionStrings = GrabConnectionStrings(config.PlatformConfigFile);

foreach (var module in config.ApplyingOrder)
{
OutBox($@"Applying scripts for module: {module}...");
OutBox($"Applying scripts for module: {module}...");

if (!sqlStatements.ContainsKey(module))
{
Out($@"Warning! There is no SQL expressions for module: {module}");
Out($"Warning! There is no SQL expressions for module: {module}");
continue;
}
var connectionString = GetConnectionString(config, connectionStrings, module);

// Fallback connection string key is always "VirtoCommerce"
connectionString = connectionString.EmptyToNull() ?? connectionStrings["VirtoCommerce"];

using (var connection = (IDbConnection)new SqlConnection(connectionString))
{
// One connection and transaction per each module
connection.Open();
var transaction = connection.BeginTransaction();

try
{
foreach (var commandText in sqlStatements[module])
{
Out($@"Run SQL statement:{Environment.NewLine}{commandText}");
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandTimeout = config.CommandTimeout;
command.CommandText = commandText;
command.ExecuteNonQuery();
}
using var connection = (IDbConnection)new SqlConnection(connectionString);
// One connection and transaction per each module
connection.Open();
var transaction = connection.BeginTransaction();

transaction.Commit();
Out($@"Successfully applied for module: {module}!");
}
catch
try
{
foreach (var commandText in sqlStatements[module])
{
transaction.Rollback();
Out($@"Statement not executed. Transaction for module {module} rolled back.");
throw;
Out($"Run SQL statement:{Environment.NewLine}{commandText}");
var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandTimeout = config.CommandTimeout;
command.CommandText = commandText;
command.ExecuteNonQuery();
}

transaction.Commit();
Out($"Successfully applied for module: {module}!");
}
catch
{
transaction.Rollback();
Out($"Statement not executed. Transaction for module {module} rolled back.");
throw;
}
}
}
Expand Down Expand Up @@ -144,20 +142,19 @@ private Dictionary<string, List<string>> EnableGrabMode(string configFilePath, C
sqlStatements ??= new Dictionary<string, List<string>>();
OutBox("Grab mode");

Out(@"Refresh connection strings references...");
Out("Refresh connection strings references...");
config.ConnectionStringsRefs = new Dictionary<string, List<string>>();

foreach (var migrationDirectory in config.MigrationDirectories)
{
Out($@"Looking in {migrationDirectory}...");
Out($"Looking in {migrationDirectory}...");
GrabConnectionStringsRefsFromModules(config.ConnectionStringsRefs, migrationDirectory);
}

File.WriteAllText(configFilePath, JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }));

Out(@"Looking for migrations in migration directories recursively...");
sqlStatements = GrabSqlStatements(config);
return sqlStatements;
Out("Looking for migrations in migration directories recursively...");
return GrabSqlStatements(config);
}

private Dictionary<string, string> GrabConnectionStrings(string platformConfigFile)
Expand All @@ -182,11 +179,11 @@ private void GrabConnectionStringsRefsFromModules(Dictionary<string, List<string
{
var connKeyRegex = new Regex(@"\.GetConnectionString\(""(?<connkey>((?!GetConnectionString)[\w.])*)""\)", RegexOptions.Singleline);
var moduleRegex = new Regex(@"[\\\w^\.-]*\\(?<module>.+)\.Web");
var moduleFiles = Directory.GetFiles(migrationDirectory, @"Module.cs", SearchOption.AllDirectories);
var moduleFiles = Directory.GetFiles(migrationDirectory, "Module.cs", SearchOption.AllDirectories);

foreach (var moduleFile in moduleFiles)
{
Out($@"Parse file {moduleFile}...");
Out($"Parse file {moduleFile}...");
var moduleName = moduleRegex.Match(moduleFile).Groups["module"].Value;
var content = File.ReadAllText(moduleFile);
var matches = connKeyRegex.Matches(content);
Expand Down Expand Up @@ -226,35 +223,35 @@ private void GrabSqlStatementsWithEFTool(Dictionary<string, List<string>> sqlSta
if (config.GrabMode == GrabMode.V2V3)
{
// Look for upgrade migrations
migrationFiles = Directory.GetFiles(migrationDirectory, @"20000*2.Designer.cs", SearchOption.AllDirectories);
migrationFiles = Directory.GetFiles(migrationDirectory, "20000*2.Designer.cs", SearchOption.AllDirectories);
}
else
{
// look for at least one migration
migrationFiles = Directory.GetFiles(migrationDirectory, @"2*.Designer.cs", SearchOption.AllDirectories);
migrationFiles = Directory.GetFiles(migrationDirectory, "2*.Designer.cs", SearchOption.AllDirectories);
migrationFiles = migrationFiles.GroupBy(x => new FileInfo(x).Directory?.FullName).Select(x => x.FirstOrDefault()).ToArray();
}

Out($@"Found {migrationFiles.Length} migrations in directory {migrationDirectory}");
Out($"Found {migrationFiles.Length} migrations in directory {migrationDirectory}");

foreach (var migrationFile in migrationFiles)
{
var moduleName = moduleRegex.Match(migrationFile).Groups["module"].Value;

if (moduleName.EndsWith(@".Data"))
if (moduleName.EndsWith(".Data"))
{
var moduleRegexData = new Regex(@"(?<module>.+)\.Data");
moduleName = moduleRegexData.Match(moduleName).Groups["module"].Value;
}

// Set migrations range to extract. Leave it empty for all migrations
var migrationName = config.GrabMode == GrabMode.V2V3
? $@"0 {migrationNameRegex.Match(File.ReadAllText(migrationFile)).Groups["migration"].Value}"
? $"0 {migrationNameRegex.Match(File.ReadAllText(migrationFile)).Groups["migration"].Value}"
: string.Empty;

var statementsFilePath = Path.Combine(new DirectoryInfo(config.StatementsDirectory).FullName, $@"{moduleName}.sql");
var statementsFilePath = Path.Combine(new DirectoryInfo(config.StatementsDirectory).FullName, $"{moduleName}.sql");

Out($@"Extract migrations for module {moduleName}...");
Out($"Extract migrations for module {moduleName}...");

// Run dotnet-ef to extract migrations in idempotent manner
var fileInfo = new FileInfo(migrationFile);
Expand All @@ -263,21 +260,21 @@ private void GrabSqlStatementsWithEFTool(Dictionary<string, List<string>> sqlSta
{
WorkingDirectory = fileInfo.Directory?.Parent?.FullName ?? string.Empty,
FileName = "dotnet",
Arguments = $@"ef migrations script {migrationName} -o {statementsFilePath} -i {(config.VerboseEFTool ? "-v" : "")}",
Arguments = $"ef migrations script {migrationName} -o {statementsFilePath} -i {(config.VerboseEFTool ? "-v" : "")}",
});

efTool?.WaitForExit();

sqlStatements.Add(moduleName, SplitStatements(File.ReadAllText(statementsFilePath)));

Out(@"OK.");
Out("OK.");
}
}

private Dictionary<string, List<string>> ReadSavedStatements(string statementsDirectory)
{
var result = new Dictionary<string, List<string>>();
var migrationFiles = Directory.GetFiles(statementsDirectory, @"*.sql");
var migrationFiles = Directory.GetFiles(statementsDirectory, "*.sql");

foreach (var migrationFile in migrationFiles)
{
Expand Down Expand Up @@ -305,17 +302,17 @@ private List<string> SplitStatements(string statements)
return result;
}

private void Fail(string text)
private static void Fail(string text)
{
Assert.Fail($@"{DateTime.Now}: {text}");
Assert.Fail($"{DateTime.Now}: {text}");
}

private void Out(string text)
private static void Out(string text)
{
Log.Information($@"{DateTime.Now}: {text}");
Log.Information($"{DateTime.Now}: {text}");
}

private void OutBox(string text)
private static void OutBox(string text)
{
Out(new string('=', text.Length));
Out(text);
Expand Down
Loading

0 comments on commit 4a11354

Please sign in to comment.