Skip to content

Commit

Permalink
Switch to file-scoped namespaces (#779)
Browse files Browse the repository at this point in the history
  • Loading branch information
premun authored Nov 26, 2021
1 parent d4888e6 commit 2863beb
Show file tree
Hide file tree
Showing 322 changed files with 22,694 additions and 23,015 deletions.
1 change: 1 addition & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ csharp_space_between_square_brackets = false

# Analyzers
dotnet_code_quality.ca1802.api_surface = private, internal
csharp_style_namespace_declarations=file_scoped:suggestion

# C++ Files
[*.{cpp,h,in}]
Expand Down
5 changes: 3 additions & 2 deletions XHarness.sln
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29920.165
# Visual Studio Version 17
VisualStudioVersion = 17.1.31911.260
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{A275E4CF-6AF3-439A-B72B-A2EDAE49A5C6}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
global.json = global.json
EndProjectSection
EndProject
Expand Down
25 changes: 12 additions & 13 deletions src/Microsoft.DotNet.XHarness.Android/AdbExitCodes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

namespace Microsoft.DotNet.XHarness.Android
namespace Microsoft.DotNet.XHarness.Android;

/// <summary>
/// Exit codes we monitor from ADB commands
/// </summary>
public enum AdbExitCodes
{
/// <summary>
/// Exit codes we monitor from ADB commands
/// </summary>
public enum AdbExitCodes
{
SUCCESS = 0,
INSTRUMENTATION_SUCCESS = -1,
INSTRUMENTATION_TIMEOUT = -2,
ADB_BROKEN_PIPE = 224,
ADB_UNINSTALL_APP_NOT_ON_DEVICE = 255,
ADB_UNINSTALL_APP_NOT_ON_EMULATOR = 1,
}
SUCCESS = 0,
INSTRUMENTATION_SUCCESS = -1,
INSTRUMENTATION_TIMEOUT = -2,
ADB_BROKEN_PIPE = 224,
ADB_UNINSTALL_APP_NOT_ON_DEVICE = 255,
ADB_UNINSTALL_APP_NOT_ON_EMULATOR = 1,
}
845 changes: 422 additions & 423 deletions src/Microsoft.DotNet.XHarness.Android/AdbRunner.cs

Large diffs are not rendered by default.

45 changes: 22 additions & 23 deletions src/Microsoft.DotNet.XHarness.Android/ApkHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,33 @@
using System.IO.Compression;
using System.Linq;

namespace Microsoft.DotNet.XHarness.Android
namespace Microsoft.DotNet.XHarness.Android;

public static class ApkHelper
{
public static class ApkHelper
public static List<string> GetApkSupportedArchitectures(string apkPath)
{
public static List<string> GetApkSupportedArchitectures(string apkPath)
if (string.IsNullOrEmpty(apkPath))
{
throw new ArgumentException("Please supply a value for apkPath");
}
if (!File.Exists(apkPath))
{
if (string.IsNullOrEmpty(apkPath))
{
throw new ArgumentException("Please supply a value for apkPath");
}
if (!File.Exists(apkPath))
{
throw new FileNotFoundException($"Invalid APK Path: '{apkPath}'", apkPath);
}
if (!Path.GetExtension(apkPath).Equals(".apk", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Only know how to open APK files.");
}
throw new FileNotFoundException($"Invalid APK Path: '{apkPath}'", apkPath);
}
if (!Path.GetExtension(apkPath).Equals(".apk", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Only know how to open APK files.");
}

using (ZipArchive archive = ZipFile.Open(apkPath, ZipArchiveMode.Read))
{
// Enumerate all folders under /lib inside the zip
var allLibFolders = archive.Entries.Where(e => e.FullName.StartsWith("lib/"))
.Select(e => e.FullName[4..e.FullName.IndexOf('/', 4)])
.Distinct().ToList();
using (ZipArchive archive = ZipFile.Open(apkPath, ZipArchiveMode.Read))
{
// Enumerate all folders under /lib inside the zip
var allLibFolders = archive.Entries.Where(e => e.FullName.StartsWith("lib/"))
.Select(e => e.FullName[4..e.FullName.IndexOf('/', 4)])
.Distinct().ToList();

return allLibFolders;
}
return allLibFolders;
}
}
}
149 changes: 74 additions & 75 deletions src/Microsoft.DotNet.XHarness.Android/Execution/AdbProcessManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,101 +5,100 @@
using System.Threading;
using Microsoft.Extensions.Logging;

namespace Microsoft.DotNet.XHarness.Android.Execution
namespace Microsoft.DotNet.XHarness.Android.Execution;

public class AdbProcessManager : IAdbProcessManager
{
public class AdbProcessManager : IAdbProcessManager
{
private readonly ILogger _log;
public AdbProcessManager(ILogger logger) => _log = logger;
private readonly ILogger _log;
public AdbProcessManager(ILogger logger) => _log = logger;

/// <summary>
/// Whenever there are multiple devices attached to a system, most ADB commands will fail
/// unless the specific device id is provided with -s {device serial #}
/// </summary>
public string DeviceSerial { get; set; } = string.Empty;
/// <summary>
/// Whenever there are multiple devices attached to a system, most ADB commands will fail
/// unless the specific device id is provided with -s {device serial #}
/// </summary>
public string DeviceSerial { get; set; } = string.Empty;

public ProcessExecutionResults Run(string adbExePath, string arguments) => Run(adbExePath, arguments, TimeSpan.FromMinutes(5));
public ProcessExecutionResults Run(string adbExePath, string arguments) => Run(adbExePath, arguments, TimeSpan.FromMinutes(5));

public ProcessExecutionResults Run(string adbExePath, string arguments, TimeSpan timeOut)
{
string deviceSerialArgs = string.IsNullOrEmpty(DeviceSerial) ? string.Empty : $"-s {DeviceSerial}";
public ProcessExecutionResults Run(string adbExePath, string arguments, TimeSpan timeOut)
{
string deviceSerialArgs = string.IsNullOrEmpty(DeviceSerial) ? string.Empty : $"-s {DeviceSerial}";

_log.LogDebug($"Executing command: '{adbExePath} {deviceSerialArgs} {arguments}'");
_log.LogDebug($"Executing command: '{adbExePath} {deviceSerialArgs} {arguments}'");

var processStartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(adbExePath) ?? throw new ArgumentNullException(nameof(adbExePath)),
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = adbExePath,
Arguments = $"{deviceSerialArgs} {arguments}",
};
var p = new Process() { StartInfo = processStartInfo };
var standardOut = new StringBuilder();
var standardErr = new StringBuilder();

p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
var processStartInfo = new ProcessStartInfo
{
CreateNoWindow = true,
UseShellExecute = false,
WorkingDirectory = Path.GetDirectoryName(adbExePath) ?? throw new ArgumentNullException(nameof(adbExePath)),
RedirectStandardOutput = true,
RedirectStandardError = true,
FileName = adbExePath,
Arguments = $"{deviceSerialArgs} {arguments}",
};
var p = new Process() { StartInfo = processStartInfo };
var standardOut = new StringBuilder();
var standardErr = new StringBuilder();

p.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
{
lock (standardOut)
{
lock (standardOut)
if (e.Data != null)
{
if (e.Data != null)
{
standardOut.AppendLine(e.Data);
}
standardOut.AppendLine(e.Data);
}
};
}
};

p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e)
p.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e)
{
lock (standardErr)
{
lock (standardErr)
if (e.Data != null)
{
if (e.Data != null)
{
standardErr.AppendLine(e.Data);
}
standardErr.AppendLine(e.Data);
}
};
}
};

p.Start();
p.Start();

p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.BeginErrorReadLine();

bool timedOut = false;
int exitCode;
bool timedOut = false;
int exitCode;

// (int.MaxValue ms is about 24 days). Large values are effectively timeouts for the outer harness
if (!p.WaitForExit((int)Math.Min(timeOut.TotalMilliseconds, int.MaxValue)))
{
_log.LogError("Waiting for command timed out: execution may be compromised.");
timedOut = true;
exitCode = (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT;
// (int.MaxValue ms is about 24 days). Large values are effectively timeouts for the outer harness
if (!p.WaitForExit((int)Math.Min(timeOut.TotalMilliseconds, int.MaxValue)))
{
_log.LogError("Waiting for command timed out: execution may be compromised.");
timedOut = true;
exitCode = (int)AdbExitCodes.INSTRUMENTATION_TIMEOUT;

// try to terminate the process
try { p.Kill (); } catch { }
}
else
{
// we exited normally, call WaitForExit() again to ensure redirected standard output is processed
p.WaitForExit();
exitCode = p.ExitCode;
}
// try to terminate the process
try { p.Kill(); } catch { }
}
else
{
// we exited normally, call WaitForExit() again to ensure redirected standard output is processed
p.WaitForExit();
exitCode = p.ExitCode;
}

p.Close();
p.Close();

lock (standardOut)
lock (standardErr)
lock (standardOut)
lock (standardErr)
{
return new ProcessExecutionResults()
{
return new ProcessExecutionResults()
{
ExitCode = exitCode,
StandardOutput = standardOut.ToString(),
StandardError = standardErr.ToString(),
TimedOut = timedOut
};
}
}
ExitCode = exitCode,
StandardOutput = standardOut.ToString(),
StandardError = standardErr.ToString(),
TimedOut = timedOut
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@

using Microsoft.Extensions.Logging;

namespace Microsoft.DotNet.XHarness.Android.Execution
namespace Microsoft.DotNet.XHarness.Android.Execution;

internal class AdbReportFactory
{
internal class AdbReportFactory
// This method return proper ReportManager based on API number of current device
// It allows to apply different logic for bugreport generation on API 21-23 and above
internal static IReportManager CreateReportManager(ILogger log, int api)
{
// This method return proper ReportManager based on API number of current device
// It allows to apply different logic for bugreport generation on API 21-23 and above
internal static IReportManager CreateReportManager(ILogger log, int api)
{
if (api > 23) return new NewReportManager(log);
else return new Api23AndOlderReportManager(log);
}
if (api > 23) return new NewReportManager(log);
else return new Api23AndOlderReportManager(log);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,35 @@
using System.Threading;
using Microsoft.Extensions.Logging;

namespace Microsoft.DotNet.XHarness.Android.Execution
namespace Microsoft.DotNet.XHarness.Android.Execution;

internal class Api23AndOlderReportManager : IReportManager
{
internal class Api23AndOlderReportManager : IReportManager
private readonly ILogger _log;

public Api23AndOlderReportManager(ILogger log)
{
_log = log;
}

public string DumpBugReport(AdbRunner runner, string outputFilePathWithoutFormat)
{
private readonly ILogger _log;
// give some time for bug report to be available
Thread.Sleep(3000);

public Api23AndOlderReportManager(ILogger log)
var result = runner.RunAdbCommand($"bugreport", TimeSpan.FromMinutes(5));

if (result.ExitCode != 0)
{
_log = log;
// Could throw here, but it would tear down a possibly otherwise acceptable execution.
_log.LogError($"Error getting ADB bugreport:{Environment.NewLine}{result}");
return string.Empty;
}

public string DumpBugReport(AdbRunner runner, string outputFilePathWithoutFormat)
else
{
// give some time for bug report to be available
Thread.Sleep(3000);

var result = runner.RunAdbCommand($"bugreport", TimeSpan.FromMinutes(5));

if (result.ExitCode != 0)
{
// Could throw here, but it would tear down a possibly otherwise acceptable execution.
_log.LogError($"Error getting ADB bugreport:{Environment.NewLine}{result}");
return string.Empty;
}
else
{
File.WriteAllText($"{outputFilePathWithoutFormat}.txt", result.StandardOutput);
_log.LogInformation($"Wrote ADB bugreport to {outputFilePathWithoutFormat}.txt");
return $"{outputFilePathWithoutFormat}.txt";
}
File.WriteAllText($"{outputFilePathWithoutFormat}.txt", result.StandardOutput);
_log.LogInformation($"Wrote ADB bugreport to {outputFilePathWithoutFormat}.txt");
return $"{outputFilePathWithoutFormat}.txt";
}
}
}
Loading

0 comments on commit 2863beb

Please sign in to comment.