Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@
<Compile Include="..\Xamarin.Android.Build.Tasks\Tasks\BundleTool.cs" Link="Tasks\BundleTool.cs" />
<Compile Include="..\Xamarin.Android.Build.Tasks\Utilities\AssemblyIdentityMap.cs" Link="Utilities\AssemblyIdentityMap.cs" />
<Compile Include="..\Xamarin.Android.Build.Tasks\Utilities\JsonExtensions.cs" Link="Utilities\JsonExtensions.cs" />
<!-- Lint: Aapt2, ConvertResourcesCases, ValidateJavaVersion, etc. still use these helpers. -->
<Compile Include="..\Xamarin.Android.Build.Tasks\Utilities\MonoAndroidHelper.Shared.cs" Link="Utilities\MonoAndroidHelper.Shared.cs" />
</ItemGroup>

<!--
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
using System.Collections.Generic;
using System.Text;
using Microsoft.Android.Build.Tasks;
using Xamarin.Android.Tasks;
using Properties = Xamarin.Android.Tasks.Properties;

namespace Xamarin.Android.Tasks
namespace Microsoft.Android.Tasks
{
public class Lint : AndroidToolTask
public partial class Lint : AndroidToolTask
{
public override string TaskPrefix => "LNT";

Expand All @@ -34,15 +36,15 @@ public class Lint : AndroidToolTask
//super (p0, p1, p2, p3);
//~~~~~
//
const string CodeErrorRegExString = @"(?<file>.+\.*):(?<line>\d+):(?<text>.+)";
[GeneratedRegex (@"(?<file>.+\.*):(?<line>\d+):(?<text>.+)")]
private static partial Regex CodeErrorRegEx { get; }
// We also need to capture warning and errors which DONOT include file information
//
//Warning: The resource R.layout.main appears to be unused [UnusedResources]
//Warning: The resource R.string.app_name appears to be unused [UnusedResources]
//Warning: The resource R.string.hello appears to be unused [UnusedResources]
const string NoFileWarningOrErrorRegExString = @"(?<type>Warning|Error):(?<text>.+)";
Regex codeErrorRegEx = new Regex (CodeErrorRegExString, RegexOptions.Compiled);
Regex noFileWarningOrErrorRegEx = new Regex(NoFileWarningOrErrorRegExString, RegexOptions.Compiled);
[GeneratedRegex (@"(?<type>Warning|Error):(?<text>.+)")]
private static partial Regex NoFileWarningOrErrorRegEx { get; }
Dictionary<string, string>? _resource_name_case_map;
bool matched = false;
string? file;
Expand Down Expand Up @@ -187,7 +189,8 @@ protected override string ToolName {
{ "Instantiatable", new Version (4, 2, 0) },
};

static readonly Regex lintVersionRegex = new Regex (@"version[\t\s]+(?<version>[\d\.]+)", RegexOptions.Compiled);
[GeneratedRegex (@"version[\t\s]+(?<version>[\d\.]+)")]
private static partial Regex LintVersionRegex { get; }

public override bool RunTask ()
{
Expand Down Expand Up @@ -226,6 +229,7 @@ public override bool RunTask ()
{
Regex issueReplaceRegex = new Regex ($"\b{issueToRemove}\b(,)?");
if (!issues.IsNullOrEmpty () && issues.Contains (issueToRemove)) {
ArgumentNullException.ThrowIfNull (DisabledIssues);
var match = issueReplaceRegex.Match (DisabledIssues);
if (match.Success) {
issues = issues.Replace (match.Value, string.Empty);
Expand Down Expand Up @@ -277,9 +281,9 @@ protected override string GenerateFullPathToTool ()

protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance)
{
var match = codeErrorRegEx.Match (singleLine);
var match = CodeErrorRegEx.Match (singleLine);
if (!match.Success)
match = noFileWarningOrErrorRegEx.Match (singleLine);
match = NoFileWarningOrErrorRegEx.Match (singleLine);
if (match.Success) {
if (matched) {
// we are already in a warning/error ...
Expand Down Expand Up @@ -347,7 +351,7 @@ XDocument MergeConfigFiles()
config.Add (lintRoot);
foreach (var configFile in ConfigFiles ?? []) {
var doc = XDocument.Load (configFile.ItemSpec);
var issues = doc.Element ("lint").Elements ("issue");
var issues = (doc.Element ("lint") ?? throw new InvalidOperationException ($"'{configFile.ItemSpec}' has no <lint> root element.")).Elements ("issue");
lintRoot.Add (issues);
}
return config;
Expand Down Expand Up @@ -378,9 +382,9 @@ Version GetLintVersion (string tool, Dictionary<string, string> environmentVaria
var versionInfo = sb.ToString ();
if (result != 0 || versionInfo.Contains ("unknown")) {
// lets try to parse the lint-xx-x-x-dev.jar filename to get the version
var libPath = Path.Combine (Path.GetDirectoryName (tool), "..", "lib");
var libPath = Path.Combine (Path.GetDirectoryName (tool) ?? "", "..", "lib");
if (Directory.Exists (libPath)) {
Version v;
Version? v;
foreach (var file in Directory.EnumerateFiles (libPath, "lint-??.?.?-dev.jar")) {
var split = Path.GetFileName (file).Split ('-');
if (split.Length != 3)
Expand All @@ -396,8 +400,8 @@ Version GetLintVersion (string tool, Dictionary<string, string> environmentVaria
return new Version (1, 0);
}
// lint: version 26.0.2
var versionNumberMatch = lintVersionRegex.Match (versionInfo);
Version versionNumber;
var versionNumberMatch = LintVersionRegex.Match (versionInfo);
Version? versionNumber;
if (versionNumberMatch.Success && Version.TryParse (versionNumberMatch.Groups ["version"]?.Value, out versionNumber)) {
return versionNumber;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
#nullable enable

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Microsoft.Android.Tasks;

namespace Xamarin.Android.Build.Tests.Tasks
{
[TestFixture]
public class LintTests : BaseTest
{
const string TaskName = "Microsoft.Android.Tasks.Lint";

class TestableLint : Lint
{
public void Feed (string line) => LogEventsFromTextOutput (line, MessageImportance.Normal);
}

[Test]
public void ParsesLintOutput ()
{
var errors = new List<BuildErrorEventArgs> ();
var warnings = new List<BuildWarningEventArgs> ();
var targetDirectory = Path.Combine ("obj", "android");
var task = new TestableLint {
BuildEngine = new MockBuildEngine (TestContext.Out, errors, warnings),
TargetDirectory = targetDirectory,
};
foreach (var line in new [] {
"AndroidManifest.xml:19: Warning: <uses-permission> tag appears after <application> tag [ManifestOrder]",
"<uses-permission android:name=\"android.permission.INTERNET\" />",
"\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",
"android/src/sdldroidtest/SDLSurface.java:43: Error: Call requires API level 21 (current min is 10): new android.view.SurfaceView [NewApi]",
"super (p0, p1, p2, p3);",
"~~~~~",
"Warning: The resource R.layout.main appears to be unused [UnusedResources]",
"Warning: The resource R.string.app_name appears to be unused [UnusedResources]",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 💡 Testing — Consider adding a file-less Error: ... record (followed by a marker or another diagnostic to flush it), then asserting XA0103, an empty File, and the expected message. Both file-less records here exercise the Warning alternative of the newly generated NoFileWarningOrErrorRegEx; the existing error instead exercises CodeErrorRegEx. This would cover the other alternative without requiring an Android SDK or JDK.

{Rule: Test edge cases}

"\t^",
}) {
task.Feed (line);
}

Assert.AreEqual (3, warnings.Count);
Assert.AreEqual ("XA0102", warnings [0].Code);
Assert.AreEqual (Path.Combine (targetDirectory, "AndroidManifest.xml"), warnings [0].File);
Assert.AreEqual (19, warnings [0].LineNumber);
Assert.AreEqual (1, warnings [0].ColumnNumber);
Assert.AreEqual (" <uses-permission> tag appears after <application> tag [ManifestOrder]", warnings [0].Message);
Assert.AreEqual ("XA0102", warnings [1].Code);
Assert.AreEqual ("The resource R.layout.main appears to be unused [UnusedResources]", warnings [1].Message);
Assert.AreEqual ("XA0102", warnings [2].Code);
Assert.AreEqual ("The resource R.string.app_name appears to be unused [UnusedResources]", warnings [2].Message);

Assert.AreEqual (1, errors.Count);
Assert.AreEqual ("XA0103", errors [0].Code);
Assert.AreEqual (Path.Combine (targetDirectory, "android/src/sdldroidtest/SDLSurface.java"), errors [0].File);
Assert.AreEqual (43, errors [0].LineNumber);
Assert.AreEqual (0, errors [0].ColumnNumber);
Assert.AreEqual (" Call requires API level 21 (current min is 10): new android.view.SurfaceView [NewApi]", errors [0].Message);
}

[Test]
public void TaskRegistrationUsesFullAndCorePair ()
{
var entries = LoadRegistrations ();
Assert.AreEqual (2, entries.Length);
Assert.That (entries.Select (e => (string?) e.Attribute ("AssemblyFile")), Is.All.EqualTo ("$(_MicrosoftAndroidBuildTasksAssembly)"));
Assert.That (entries.Select (e => (string?) e.Attribute ("Runtime")), Is.All.EqualTo ("NET"));
var full = entries.Single (e => (string?) e.Attribute ("Condition") == " '$(MSBuildRuntimeType)' == 'Full' ");
var core = entries.Single (e => (string?) e.Attribute ("Condition") == " '$(MSBuildRuntimeType)' == 'Core' ");
Assert.AreEqual ("TaskHostFactory", (string?) full.Attribute ("TaskFactory"));
Assert.IsNull (core.Attribute ("TaskFactory"));
}

[TestCase (TaskName)]
[TestCase ("Lint")]
public void RegisteredTaskNamesExecute (string taskName)
{
string directory = Path.Combine (Root, "temp", TestName);
string toolPath = Path.Combine (directory, "tools");
string targetDirectory = Path.Combine (directory, "android project");
Directory.CreateDirectory (toolPath);
Directory.CreateDirectory (targetDirectory);
CreateFakeLint (toolPath);

string project = Path.Combine (directory, "lint.proj");
new XDocument (new XElement ("Project",
new XElement ("PropertyGroup",
new XElement ("_MicrosoftAndroidBuildTasksAssembly", typeof (Lint).Assembly.Location)),
LoadRegistrations (),
new XElement ("Target", new XAttribute ("Name", "Build"),
new XElement (taskName,
new XAttribute ("ToolPath", toolPath),
new XAttribute ("TargetDirectory", targetDirectory),
new XAttribute ("IntermediateOutputPath", directory),
new XAttribute ("JavaSdkPath", directory)))))
.Save (project);

string dotnet = Environment.GetEnvironmentVariable ("DOTNET_HOST_PATH") ?? "dotnet";
var result = NativeAotBootstrapTestTools.Run (dotnet, "msbuild", project, "-t:Build", "-v:minimal", "-nr:false");
string output = result.Output + result.Error;
Assert.AreEqual (0, result.ExitCode, output);
// `lint --version` reported 26.0.2, so the issues introduced up to 26.0.2 are disabled.
StringAssert.Contains ($"warning XA0102: args=--quiet --disable Instantiatable,StaticFieldLeak,UnusedResources,HardcodedDebugMode {targetDirectory}", output);
StringAssert.IsMatch (@"strings\.xml\(3,\d+\): warning XA0102: Unused resource \[UnusedResources\]", output);
}

static void CreateFakeLint (string toolPath)
{
if (OperatingSystem.IsWindows ()) {
File.WriteAllText (Path.Combine (toolPath, "lint.bat"), """
@echo off
if "%~1"=="--version" (
echo lint: version 26.0.2
exit /b 0
)
rem Match the shell fixture's $* expansion by removing argument quoting.
echo Warning: args=%~1 %~2 %~3 %~4
echo ^^
echo res\values\strings.xml:3: Warning: Unused resource [UnusedResources]
echo ~~~~
""".Replace ("\n", "\r\n"));
return;
}
string lint = Path.Combine (toolPath, "lint");
File.WriteAllText (lint, """
#!/bin/sh
if [ "$1" = "--version" ]; then
echo "lint: version 26.0.2"
exit 0
fi
echo "Warning: args=$*"
echo "^"
echo "res/values/strings.xml:3: Warning: Unused resource [UnusedResources]"
echo " ~~~~"
""");
File.SetUnixFileMode (lint, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}

static XElement [] LoadRegistrations ()
{
string commonTargets = Path.Combine (NativeAotBootstrapTestTools.FindRepositoryRoot (),
"src", "Xamarin.Android.Build.Tasks", "Xamarin.Android.Common.targets");
return XDocument.Load (commonTargets).Descendants ()
.Where (element => element.Name.LocalName == "UsingTask" && (string?) element.Attribute ("TaskName") == TaskName)
.Select (element => {
var registration = new XElement (element);
registration.Name = "UsingTask";
return registration;
})
.ToArray ();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;

namespace Xamarin.Android.Tasks;

// Helpers compile-linked into both Xamarin.Android.Build.Tasks and Microsoft.Android.Build.Tasks.
partial class MonoAndroidHelper
{
public static int RunProcess (string name, string args, DataReceivedEventHandler onOutput, DataReceivedEventHandler onError, Dictionary<string, string>? environmentVariables = null)
{
return RunProcess (TaskEnvironment.Fallback, name, args, onOutput, onError, environmentVariables);
}

public static int RunProcess (TaskEnvironment taskEnvironment, string name, string args, DataReceivedEventHandler onOutput, DataReceivedEventHandler onError, Dictionary<string, string>? environmentVariables = null)
{
if (taskEnvironment == null)
throw new ArgumentNullException (nameof (taskEnvironment));

var psi = taskEnvironment.GetProcessStartInfo ();
psi.FileName = name;
psi.Arguments = args;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
if (environmentVariables != null) {
foreach (var pair in environmentVariables) {
psi.EnvironmentVariables [pair.Key] = pair.Value;
}
}
Process p = new Process ();
p.StartInfo = psi;

p.OutputDataReceived += onOutput;
p.ErrorDataReceived += onError;
p.Start ();
p.BeginErrorReadLine ();
p.BeginOutputReadLine ();
p.WaitForExit ();
try {
return p.ExitCode;
} finally {
p.Close ();
}
}

public static Dictionary<string, string> ItemGroupToCaseMap (ITaskItem [] items)
{
var map = new Dictionary<string, string> (items.Length, StringComparer.Ordinal);
foreach (var item in items)
map [item.ItemSpec] = item.GetMetadata ("OriginalName");
return map;
}

public static string FixUpAndroidResourcePath (string file, string resourceDirectory, string resourceDirectoryFullPath, Dictionary<string, string> resource_name_case_map)
{
string? newfile = null;
if (file.StartsWith (resourceDirectory, StringComparison.InvariantCultureIgnoreCase)) {
newfile = file.Substring (resourceDirectory.Length).TrimStart (Path.DirectorySeparatorChar);
}
if (!resourceDirectoryFullPath.IsNullOrEmpty () && file.StartsWith (resourceDirectoryFullPath, StringComparison.InvariantCultureIgnoreCase)) {
newfile = file.Substring (resourceDirectoryFullPath.Length).TrimStart (Path.DirectorySeparatorChar);
}
if (!newfile.IsNullOrEmpty ()) {
if (resource_name_case_map.TryGetValue (newfile, out string? value))
newfile = value;
newfile = Path.Combine ("Resources", newfile);
return newfile;
}
return string.Empty;
}
}
Loading
Loading