C#: Change string.Format calls to interpolated strings

This commit is contained in:
Tamas Vajk
2024-06-27 09:20:44 +02:00
parent 4a98436884
commit 0c34b4535a
17 changed files with 58 additions and 58 deletions

View File

@@ -39,7 +39,7 @@ namespace Semmle.Autobuild.CSharp
if (notDotNetProject is not null)
{
builder.Logger.Log(Severity.Info, "Not using .NET Core because of incompatible project {0}", notDotNetProject);
builder.Logger.LogInfo($"Not using .NET Core because of incompatible project {notDotNetProject}");
return BuildScript.Failure;
}

View File

@@ -22,12 +22,12 @@ namespace Semmle.Autobuild.CSharp
}
catch (InvalidEnvironmentException ex)
{
Console.WriteLine("The environment is invalid: {0}", ex.Message);
Console.WriteLine($"The environment is invalid: {ex.Message}");
}
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
}
return 1;
}

View File

@@ -22,12 +22,12 @@ namespace Semmle.Autobuild.Cpp
}
catch (InvalidEnvironmentException ex)
{
Console.WriteLine("The environment is invalid: {0}", ex.Message);
Console.WriteLine($"The environment is invalid: {ex.Message}");
}
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine("The value \"{0}\" for parameter \"{1}\" is invalid", ex.ActualValue, ex.ParamName);
Console.WriteLine($"The value \"{ex.ActualValue}\" for parameter \"{ex.ParamName}\" is invalid");
}
return 1;
}

View File

@@ -128,9 +128,9 @@ namespace Semmle.Autobuild.Shared
command.Argument("/t:" + target);
if (platform is not null)
command.Argument(string.Format("/p:Platform=\"{0}\"", platform));
command.Argument($"/p:Platform=\"{platform}\"");
if (configuration is not null)
command.Argument(string.Format("/p:Configuration=\"{0}\"", configuration));
command.Argument($"/p:Configuration=\"{configuration}\"");
// append the build script which invokes msbuild to the overall build script `ret`;
// we insert a check that building the current project or solution was successful:

View File

@@ -66,7 +66,7 @@ namespace Semmle.Autobuild.Shared
catch // lgtm[cs/catch-of-all-exceptions]
// Generic catch clause - Version constructor throws about 5 different exceptions.
{
builder.Logger.Log(Severity.Warning, "Project {0} has invalid tools version {1}", path, toolsVersion);
builder.Logger.LogWarning($"Project {path} has invalid tools version {toolsVersion}");
}
}

View File

@@ -60,11 +60,11 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
{
var result = Name;
if (Version is not null)
result = string.Format("{0}, Version={1}", result, Version);
result = $"{result}, Version={Version}";
if (Culture is not null)
result = string.Format("{0}, Culture={1}", result, Culture);
result = $"{result}, Culture={Culture}";
if (PublicKeyToken is not null)
result = string.Format("{0}, PublicKeyToken={1}", result, PublicKeyToken);
result = $"{result}, PublicKeyToken={PublicKeyToken}";
return result;
}
}
@@ -82,8 +82,8 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
if (Version is not null)
{
if (Culture is not null)
yield return string.Format("{0}, Version={1}, Culture={2}", Name, Version, Culture);
yield return string.Format("{0}, Version={1}", Name, Version);
yield return $"{Name}, Version={Version}, Culture={Culture}";
yield return $"{Name}, Version={Version}";
}
yield return Name;
yield return Name.ToLowerInvariant();

View File

@@ -151,7 +151,7 @@ namespace Semmle.Extraction.CSharp.Standalone
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
fileLogger.Log(Severity.Error, " Unhandled exception: {0}", ex);
fileLogger.LogError($" Unhandled exception: {ex}");
}
logger.Log(Severity.Info, $"Extraction completed in {overallStopwatch.Elapsed}");

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateModifiers(trapFile);
ContainingType!.PopulateGenerics();
trapFile.destructors(this, string.Format("~{0}", Symbol.ContainingType.Name), ContainingType, OriginalDefinition(Context, this, Symbol));
trapFile.destructors(this, $"~{Symbol.ContainingType.Name}", ContainingType, OriginalDefinition(Context, this, Symbol));
trapFile.destructor_location(this, Location);
}

View File

@@ -63,7 +63,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
if (method.MethodKind == MethodKind.ReducedExtension)
{
cx.ExtractionContext.Logger.Log(Semmle.Util.Logging.Severity.Warning, "Reduced extension method symbols should not be directly extracted.");
cx.ExtractionContext.Logger.LogWarning("Reduced extension method symbols should not be directly extracted.");
}
return OrdinaryMethodFactory.Instance.CreateEntityFromSymbol(cx, method);

View File

@@ -54,7 +54,7 @@ namespace Semmle.Extraction.CSharp
this.addAssemblyTrapPrefix = addAssemblyTrapPrefix;
this.progressMonitor = pm;
Logger.Log(Severity.Info, "EXTRACTION STARTING at {0}", DateTime.Now);
Logger.LogInfo($"EXTRACTION STARTING at {DateTime.Now}");
stopWatch.Start();
}
@@ -175,7 +175,7 @@ namespace Semmle.Extraction.CSharp
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
Logger.Log(Severity.Error, " Unhandled exception analyzing {0}: {1}", r.FilePath, ex);
Logger.LogError($" Unhandled exception analyzing {r.FilePath}: {ex}");
}
}
@@ -251,7 +251,7 @@ namespace Semmle.Extraction.CSharp
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
Logger.Log(Severity.Error, " Unhandled exception analyzing {0}: {1}", "compilation", ex);
Logger.LogError($" Unhandled exception analyzing compilation: {ex}");
}
}
@@ -315,12 +315,12 @@ namespace Semmle.Extraction.CSharp
public virtual void Dispose()
{
stopWatch.Stop();
Logger.Log(Severity.Info, " Peak working set = {0} MB", Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024));
Logger.LogInfo($" Peak working set = {Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024)} MB");
if (TotalErrors > 0)
Logger.Log(Severity.Info, "EXTRACTION FAILED with {0} error{1} in {2}", TotalErrors, TotalErrors == 1 ? "" : "s", stopWatch.Elapsed);
Logger.LogInfo($"EXTRACTION FAILED with {TotalErrors} error{(TotalErrors == 1 ? "" : "s")} in {stopWatch.Elapsed}");
else
Logger.Log(Severity.Info, "EXTRACTION SUCCEEDED in {0}", stopWatch.Elapsed);
Logger.LogInfo($"EXTRACTION SUCCEEDED in {stopWatch.Elapsed}");
compilationTrapFile?.Dispose();
}
@@ -345,9 +345,9 @@ namespace Semmle.Extraction.CSharp
/// </summary>
public void LogExtractorInfo()
{
Logger.Log(Severity.Info, " Extractor: {0}", Environment.GetCommandLineArgs().First());
Logger.Log(Severity.Info, " Extractor version: {0}", Version);
Logger.Log(Severity.Info, " Current working directory: {0}", Directory.GetCurrentDirectory());
Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs().First()}");
Logger.LogInfo($" Extractor version: {Version}");
Logger.LogInfo($" Current working directory: {Directory.GetCurrentDirectory()}");
}
private static string Version

View File

@@ -38,12 +38,12 @@ namespace Semmle.Extraction.CSharp
{
if (action != AnalysisAction.UpToDate)
{
logger.Log(Severity.Info, " {0} ({1})", source,
action == AnalysisAction.Extracted
? time.ToString()
: action == AnalysisAction.Excluded
? "excluded"
: "up to date");
var state = action == AnalysisAction.Extracted
? time.ToString()
: action == AnalysisAction.Excluded
? "excluded"
: "up to date";
logger.LogInfo($" {source} ({state})");
}
}
@@ -110,7 +110,7 @@ namespace Semmle.Extraction.CSharp
var compilerVersion = new CompilerVersion(options);
if (compilerVersion.SkipExtraction)
{
logger.Log(Severity.Warning, " Unrecognized compiler '{0}' because {1}", compilerVersion.SpecifiedCompiler, compilerVersion.SkipReason);
logger.LogWarning($" Unrecognized compiler '{compilerVersion.SpecifiedCompiler}' because {compilerVersion.SkipReason}");
return ExitCode.Ok;
}
@@ -133,14 +133,14 @@ namespace Semmle.Extraction.CSharp
{
var sb = new StringBuilder();
sb.Append(" Failed to parse command line: ").AppendList(" ", compilerArgs);
logger.Log(Severity.Error, sb.ToString());
logger.LogError(sb.ToString());
++analyser.CompilationErrors;
return ExitCode.Failed;
}
if (!analyser.BeginInitialize(compilerVersion.ArgsWithResponse))
{
logger.Log(Severity.Info, "Skipping extraction since files have already been extracted");
logger.LogInfo("Skipping extraction since files have already been extracted");
return ExitCode.Ok;
}
@@ -148,14 +148,14 @@ namespace Semmle.Extraction.CSharp
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
logger.Log(Severity.Error, " Unhandled exception: {0}", ex);
logger.LogError($" Unhandled exception: {ex}");
return ExitCode.Errors;
}
}
private static void AddSourceFilesFromProjects(IEnumerable<string> projectsToLoad, IList<string> compilerArguments, ILogger logger)
{
logger.Log(Severity.Info, " Loading referenced projects.");
logger.LogInfo(" Loading referenced projects.");
var projects = new Queue<string>(projectsToLoad);
var processed = new HashSet<string>();
while (projects.Count > 0)
@@ -168,7 +168,7 @@ namespace Semmle.Extraction.CSharp
}
processed.Add(fi.FullName);
logger.Log(Severity.Info, " Processing referenced project: " + fi.FullName);
logger.LogInfo($" Processing referenced project: {fi.FullName}");
var csProj = new CsProjFile(fi);
@@ -242,7 +242,7 @@ namespace Semmle.Extraction.CSharp
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Reference '{0}' does not exist", clref.Reference);
analyser.Logger.LogError($" Reference '{clref.Reference}' does not exist");
++analyser.CompilationErrors;
}
}
@@ -264,7 +264,7 @@ namespace Semmle.Extraction.CSharp
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Unable to resolve reference '{0}'", clref.Reference);
analyser.Logger.LogError($" Unable to resolve reference '{clref.Reference}'");
++analyser.CompilationErrors;
}
}
@@ -285,9 +285,9 @@ namespace Semmle.Extraction.CSharp
try
{
using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
analyser.Logger.Log(Severity.Trace, $"Parsing source file: '{path}'");
analyser.Logger.LogTrace($"Parsing source file: '{path}'");
var tree = CSharpSyntaxTree.ParseText(SourceText.From(file, encoding), parseOptions, path);
analyser.Logger.Log(Severity.Trace, $"Source file parsed: '{path}'");
analyser.Logger.LogTrace($"Source file parsed: '{path}'");
lock (ret)
{
@@ -298,7 +298,7 @@ namespace Semmle.Extraction.CSharp
{
lock (analyser)
{
analyser.Logger.Log(Severity.Error, " Unable to open source file {0}: {1}", path, ex.Message);
analyser.Logger.LogError($" Unable to open source file {path}: {ex.Message}");
++analyser.CompilationErrors;
}
}
@@ -327,7 +327,7 @@ namespace Semmle.Extraction.CSharp
if (syntaxTrees.Count == 0)
{
analyser.Logger.Log(Severity.Error, " No source files");
analyser.Logger.LogError(" No source files");
++analyser.CompilationErrors;
if (analyser is TracingAnalyser)
{
@@ -347,7 +347,7 @@ namespace Semmle.Extraction.CSharp
}
sw.Stop();
analyser.Logger.Log(Severity.Info, " Models constructed in {0}", sw.Elapsed);
analyser.Logger.LogInfo($" Models constructed in {sw.Elapsed}");
var elapsed = sw.Elapsed;
var currentProcess = Process.GetCurrentProcess();
@@ -369,7 +369,7 @@ namespace Semmle.Extraction.CSharp
};
analyser.LogPerformance(performance);
analyser.Logger.Log(Severity.Info, " Extraction took {0}", sw.Elapsed);
analyser.Logger.LogInfo($" Extraction took {sw.Elapsed}");
postProcess();

View File

@@ -62,7 +62,7 @@ namespace Semmle.Extraction.CSharp
/// <returns>A Boolean indicating whether the same arguments have been logged previously.</returns>
private bool LogRoslynArgs(IEnumerable<string> roslynArgs)
{
Logger.Log(Severity.Info, $" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");
Logger.LogInfo($" Arguments to Roslyn: {string.Join(' ', roslynArgs)}");
var tempFile = Extractor.GetCSharpArgsLogPath(Path.GetRandomFileName());
@@ -77,7 +77,7 @@ namespace Semmle.Extraction.CSharp
var argsFile = Extractor.GetCSharpArgsLogPath(hash);
if (argsWritten)
Logger.Log(Severity.Info, $" Arguments have been written to {argsFile}");
Logger.LogInfo($" Arguments have been written to {argsFile}");
if (File.Exists(argsFile))
{
@@ -87,7 +87,7 @@ namespace Semmle.Extraction.CSharp
}
catch (IOException e)
{
Logger.Log(Severity.Warning, $" Failed to remove {tempFile}: {e.Message}");
Logger.LogWarning($" Failed to remove {tempFile}: {e.Message}");
}
return false;
}
@@ -98,7 +98,7 @@ namespace Semmle.Extraction.CSharp
}
catch (IOException e)
{
Logger.Log(Severity.Warning, $" Failed to move {tempFile} to {argsFile}: {e.Message}");
Logger.LogWarning($" Failed to move {tempFile} to {argsFile}: {e.Message}");
}
return true;
@@ -146,14 +146,14 @@ namespace Semmle.Extraction.CSharp
foreach (var error in filteredDiagnostics)
{
Logger.Log(Severity.Error, " Compilation error: {0}", error);
Logger.LogError($" Compilation error: {error}");
}
if (filteredDiagnostics.Count != 0)
{
foreach (var reference in compilation.References)
{
Logger.Log(Severity.Info, " Resolved reference {0}", reference.Display);
Logger.LogInfo($" Resolved reference {reference.Display}");
}
}

View File

@@ -203,7 +203,7 @@ namespace Semmle.Extraction
private void EnterScope()
{
if (currentRecursiveDepth >= maxRecursiveDepth)
throw new StackOverflowException(string.Format("Maximum nesting depth of {0} exceeded", maxRecursiveDepth));
throw new StackOverflowException($"Maximum nesting depth of {maxRecursiveDepth} exceeded");
++currentRecursiveDepth;
}

View File

@@ -50,7 +50,7 @@ namespace Semmle.Extraction
++Errors;
if (Errors == maxErrors)
{
Logger.LogInfo(" Stopping logging after {0} errors", Errors);
Logger.LogInfo($" Stopping logging after {Errors} errors");
}
}

View File

@@ -183,13 +183,13 @@ namespace Semmle.Extraction
if (TryMove(tmpFile, $"{root}-{hash}.trap{TrapExtension(trapCompression)}"))
return;
}
logger.Log(Severity.Info, "Identical trap file for {0} already exists", TrapFile);
logger.LogInfo($"Identical trap file for {TrapFile} already exists");
FileUtils.TryDelete(tmpFile);
}
}
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions]
{
logger.Log(Severity.Error, "Failed to move the trap file from {0} to {1} because {2}", tmpFile, TrapFile, ex);
logger.LogError($"Failed to move the trap file from {tmpFile} to {TrapFile} because {ex}");
}
}

View File

@@ -20,6 +20,6 @@ namespace Semmle.Util.Logging
void LogDebug(string text, int? threadId = null) => Log(Severity.Debug, text, threadId);
void Log(Severity s, string text, params object?[] args) => Log(s, string.Format(text, args));
void LogTrace(string text, int? threadId = null) => Log(Severity.Trace, text, threadId);
}
}

View File

@@ -40,7 +40,7 @@ public class Testrunner
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[FAIL] {0}: {1}", info.TestDisplayName, info.ExceptionMessage);
Console.WriteLine($"[FAIL] {info.TestDisplayName}: {info.ExceptionMessage}");
if (info.ExceptionStackTrace != null)
Console.WriteLine(info.ExceptionStackTrace);
@@ -55,7 +55,7 @@ public class Testrunner
lock (ConsoleLock)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[SKIP] {0}: {1}", info.TestDisplayName, info.SkipReason);
Console.WriteLine($"[SKIP] {info.TestDisplayName}: {info.SkipReason}");
Console.ResetColor();
}
}