Skip to content

Commit

Permalink
Avoid setting Console.InputEncoding (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
dfederm authored Oct 2, 2024
1 parent 80fed1d commit f755c42
Showing 1 changed file with 11 additions and 26 deletions.
37 changes: 11 additions & 26 deletions src/Common/SourceControl/Git.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@ namespace Microsoft.MSBuildCache.SourceControl;

public static class Git
{
#if NETFRAMEWORK
private static readonly object InputEncodingLock = new object();
#endif

// UTF8 - NO BOM
private static readonly Encoding InputEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);

Expand Down Expand Up @@ -45,32 +41,13 @@ public static async Task<T> RunAsync<T>(
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
#if !NETFRAMEWORK
process.StartInfo.StandardInputEncoding = InputEncoding;
#endif

Stopwatch sw = Stopwatch.StartNew();

#if NETFRAMEWORK
// In .NET Framework the StandardInputEncoding is always Console.InputEncoding and determines at process start time.
// Because we need to redirect StandardInputEncoding, temporarily set Console.InputEncoding to what we need until the
// process is started. Use a lock to avoid collisions.
lock (InputEncodingLock)
{
Encoding originalConsoleInputEncoding = Console.InputEncoding;
try
{
Console.InputEncoding = InputEncoding;

process.Start();
}
finally
{
Console.InputEncoding = originalConsoleInputEncoding;
}
}
#else
process.StartInfo.StandardInputEncoding = InputEncoding;

process.Start();
#endif

static void KillProcess(Process process)
{
Expand All @@ -89,10 +66,18 @@ static void KillProcess(Process process)

using (cancellationToken.Register(() => KillProcess(process)))
{
#if NETFRAMEWORK
// In .NET Framework the StandardInputEncoding cannot be set and is always Console.InputEncoding.
// To work around, wrap the underlying stream in a writer with the correct encoding.
using (StreamWriter stdin = new StreamWriter(process.StandardInput.BaseStream, InputEncoding, 4096))
#else
using (StreamWriter stdin = process.StandardInput)
#endif
using (StreamReader stdout = process.StandardOutput)
using (StreamReader stderr = process.StandardError)
{
stdin.AutoFlush = true;

Task<T> resultTask = Task.Run(async () =>
{
try
Expand Down

0 comments on commit f755c42

Please sign in to comment.