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) 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; return BuildScript.Failure;
} }

View File

@@ -22,12 +22,12 @@ namespace Semmle.Autobuild.CSharp
} }
catch (InvalidEnvironmentException ex) catch (InvalidEnvironmentException ex)
{ {
Console.WriteLine("The environment is invalid: {0}", ex.Message); Console.WriteLine($"The environment is invalid: {ex.Message}");
} }
} }
catch (ArgumentOutOfRangeException ex) 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; return 1;
} }

View File

@@ -22,12 +22,12 @@ namespace Semmle.Autobuild.Cpp
} }
catch (InvalidEnvironmentException ex) catch (InvalidEnvironmentException ex)
{ {
Console.WriteLine("The environment is invalid: {0}", ex.Message); Console.WriteLine($"The environment is invalid: {ex.Message}");
} }
} }
catch (ArgumentOutOfRangeException ex) 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; return 1;
} }

View File

@@ -128,9 +128,9 @@ namespace Semmle.Autobuild.Shared
command.Argument("/t:" + target); command.Argument("/t:" + target);
if (platform is not null) if (platform is not null)
command.Argument(string.Format("/p:Platform=\"{0}\"", platform)); command.Argument($"/p:Platform=\"{platform}\"");
if (configuration is not null) 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`; // 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: // 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] catch // lgtm[cs/catch-of-all-exceptions]
// Generic catch clause - Version constructor throws about 5 different 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; var result = Name;
if (Version is not null) if (Version is not null)
result = string.Format("{0}, Version={1}", result, Version); result = $"{result}, Version={Version}";
if (Culture is not null) if (Culture is not null)
result = string.Format("{0}, Culture={1}", result, Culture); result = $"{result}, Culture={Culture}";
if (PublicKeyToken is not null) if (PublicKeyToken is not null)
result = string.Format("{0}, PublicKeyToken={1}", result, PublicKeyToken); result = $"{result}, PublicKeyToken={PublicKeyToken}";
return result; return result;
} }
} }
@@ -82,8 +82,8 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
if (Version is not null) if (Version is not null)
{ {
if (Culture is not null) if (Culture is not null)
yield return string.Format("{0}, Version={1}, Culture={2}", Name, Version, Culture); yield return $"{Name}, Version={Version}, Culture={Culture}";
yield return string.Format("{0}, Version={1}", Name, Version); yield return $"{Name}, Version={Version}";
} }
yield return Name; yield return Name;
yield return Name.ToLowerInvariant(); yield return Name.ToLowerInvariant();

View File

@@ -151,7 +151,7 @@ namespace Semmle.Extraction.CSharp.Standalone
} }
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] 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}"); logger.Log(Severity.Info, $"Extraction completed in {overallStopwatch.Elapsed}");

View File

@@ -14,7 +14,7 @@ namespace Semmle.Extraction.CSharp.Entities
PopulateModifiers(trapFile); PopulateModifiers(trapFile);
ContainingType!.PopulateGenerics(); 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); trapFile.destructor_location(this, Location);
} }

View File

@@ -63,7 +63,7 @@ namespace Semmle.Extraction.CSharp.Entities
{ {
if (method.MethodKind == MethodKind.ReducedExtension) 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); return OrdinaryMethodFactory.Instance.CreateEntityFromSymbol(cx, method);

View File

@@ -54,7 +54,7 @@ namespace Semmle.Extraction.CSharp
this.addAssemblyTrapPrefix = addAssemblyTrapPrefix; this.addAssemblyTrapPrefix = addAssemblyTrapPrefix;
this.progressMonitor = pm; this.progressMonitor = pm;
Logger.Log(Severity.Info, "EXTRACTION STARTING at {0}", DateTime.Now); Logger.LogInfo($"EXTRACTION STARTING at {DateTime.Now}");
stopWatch.Start(); stopWatch.Start();
} }
@@ -175,7 +175,7 @@ namespace Semmle.Extraction.CSharp
} }
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] 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] 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() public virtual void Dispose()
{ {
stopWatch.Stop(); 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) 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 else
Logger.Log(Severity.Info, "EXTRACTION SUCCEEDED in {0}", stopWatch.Elapsed); Logger.LogInfo($"EXTRACTION SUCCEEDED in {stopWatch.Elapsed}");
compilationTrapFile?.Dispose(); compilationTrapFile?.Dispose();
} }
@@ -345,9 +345,9 @@ namespace Semmle.Extraction.CSharp
/// </summary> /// </summary>
public void LogExtractorInfo() public void LogExtractorInfo()
{ {
Logger.Log(Severity.Info, " Extractor: {0}", Environment.GetCommandLineArgs().First()); Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs().First()}");
Logger.Log(Severity.Info, " Extractor version: {0}", Version); Logger.LogInfo($" Extractor version: {Version}");
Logger.Log(Severity.Info, " Current working directory: {0}", Directory.GetCurrentDirectory()); Logger.LogInfo($" Current working directory: {Directory.GetCurrentDirectory()}");
} }
private static string Version private static string Version

View File

@@ -38,12 +38,12 @@ namespace Semmle.Extraction.CSharp
{ {
if (action != AnalysisAction.UpToDate) if (action != AnalysisAction.UpToDate)
{ {
logger.Log(Severity.Info, " {0} ({1})", source, var state = action == AnalysisAction.Extracted
action == AnalysisAction.Extracted ? time.ToString()
? time.ToString() : action == AnalysisAction.Excluded
: action == AnalysisAction.Excluded ? "excluded"
? "excluded" : "up to date";
: "up to date"); logger.LogInfo($" {source} ({state})");
} }
} }
@@ -110,7 +110,7 @@ namespace Semmle.Extraction.CSharp
var compilerVersion = new CompilerVersion(options); var compilerVersion = new CompilerVersion(options);
if (compilerVersion.SkipExtraction) 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; return ExitCode.Ok;
} }
@@ -133,14 +133,14 @@ namespace Semmle.Extraction.CSharp
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.Append(" Failed to parse command line: ").AppendList(" ", compilerArgs); sb.Append(" Failed to parse command line: ").AppendList(" ", compilerArgs);
logger.Log(Severity.Error, sb.ToString()); logger.LogError(sb.ToString());
++analyser.CompilationErrors; ++analyser.CompilationErrors;
return ExitCode.Failed; return ExitCode.Failed;
} }
if (!analyser.BeginInitialize(compilerVersion.ArgsWithResponse)) 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; return ExitCode.Ok;
} }
@@ -148,14 +148,14 @@ namespace Semmle.Extraction.CSharp
} }
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] 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; return ExitCode.Errors;
} }
} }
private static void AddSourceFilesFromProjects(IEnumerable<string> projectsToLoad, IList<string> compilerArguments, ILogger logger) 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 projects = new Queue<string>(projectsToLoad);
var processed = new HashSet<string>(); var processed = new HashSet<string>();
while (projects.Count > 0) while (projects.Count > 0)
@@ -168,7 +168,7 @@ namespace Semmle.Extraction.CSharp
} }
processed.Add(fi.FullName); 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); var csProj = new CsProjFile(fi);
@@ -242,7 +242,7 @@ namespace Semmle.Extraction.CSharp
{ {
lock (analyser) 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; ++analyser.CompilationErrors;
} }
} }
@@ -264,7 +264,7 @@ namespace Semmle.Extraction.CSharp
{ {
lock (analyser) 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; ++analyser.CompilationErrors;
} }
} }
@@ -285,9 +285,9 @@ namespace Semmle.Extraction.CSharp
try try
{ {
using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); 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); 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) lock (ret)
{ {
@@ -298,7 +298,7 @@ namespace Semmle.Extraction.CSharp
{ {
lock (analyser) 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; ++analyser.CompilationErrors;
} }
} }
@@ -327,7 +327,7 @@ namespace Semmle.Extraction.CSharp
if (syntaxTrees.Count == 0) if (syntaxTrees.Count == 0)
{ {
analyser.Logger.Log(Severity.Error, " No source files"); analyser.Logger.LogError(" No source files");
++analyser.CompilationErrors; ++analyser.CompilationErrors;
if (analyser is TracingAnalyser) if (analyser is TracingAnalyser)
{ {
@@ -347,7 +347,7 @@ namespace Semmle.Extraction.CSharp
} }
sw.Stop(); 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 elapsed = sw.Elapsed;
var currentProcess = Process.GetCurrentProcess(); var currentProcess = Process.GetCurrentProcess();
@@ -369,7 +369,7 @@ namespace Semmle.Extraction.CSharp
}; };
analyser.LogPerformance(performance); analyser.LogPerformance(performance);
analyser.Logger.Log(Severity.Info, " Extraction took {0}", sw.Elapsed); analyser.Logger.LogInfo($" Extraction took {sw.Elapsed}");
postProcess(); postProcess();

View File

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

View File

@@ -50,7 +50,7 @@ namespace Semmle.Extraction
++Errors; ++Errors;
if (Errors == maxErrors) 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)}")) if (TryMove(tmpFile, $"{root}-{hash}.trap{TrapExtension(trapCompression)}"))
return; 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); FileUtils.TryDelete(tmpFile);
} }
} }
catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] 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 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.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[FAIL] {0}: {1}", info.TestDisplayName, info.ExceptionMessage); Console.WriteLine($"[FAIL] {info.TestDisplayName}: {info.ExceptionMessage}");
if (info.ExceptionStackTrace != null) if (info.ExceptionStackTrace != null)
Console.WriteLine(info.ExceptionStackTrace); Console.WriteLine(info.ExceptionStackTrace);
@@ -55,7 +55,7 @@ public class Testrunner
lock (ConsoleLock) lock (ConsoleLock)
{ {
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[SKIP] {0}: {1}", info.TestDisplayName, info.SkipReason); Console.WriteLine($"[SKIP] {info.TestDisplayName}: {info.SkipReason}");
Console.ResetColor(); Console.ResetColor();
} }
} }