-
Notifications
You must be signed in to change notification settings - Fork 564
[xabt] implement $(Device) and ComputeAvailableDevices MSBuild target
#10576
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
211 changes: 211 additions & 0 deletions
211
src/Xamarin.Android.Build.Tasks/Tasks/GetAvailableAndroidDevices.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| #nullable enable | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Text.RegularExpressions; | ||
| using Microsoft.Android.Build.Tasks; | ||
| using Microsoft.Build.Framework; | ||
| using Microsoft.Build.Utilities; | ||
|
|
||
| namespace Xamarin.Android.Tasks; | ||
|
|
||
| /// <summary> | ||
| /// MSBuild task that queries available Android devices and emulators using 'adb devices -l'. | ||
| /// Returns a list of devices with metadata for device selection in dotnet run. | ||
| /// </summary> | ||
| public class GetAvailableAndroidDevices : AndroidAdb | ||
| { | ||
| enum DeviceType | ||
| { | ||
| Device, | ||
| Emulator | ||
| } | ||
|
|
||
| // Pattern to match device lines: <serial> <state> [key:value ...] | ||
| // Example: emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 | ||
| static readonly Regex AdbDevicesRegex = new(@"^([^\s]+)\s+(device|offline|unauthorized|no permissions)\s*(.*)$", RegexOptions.Compiled); | ||
|
|
||
| readonly List<string> output = []; | ||
|
|
||
| [Output] | ||
| public ITaskItem [] Devices { get; set; } = []; | ||
|
|
||
| public GetAvailableAndroidDevices () | ||
| { | ||
| Command = "devices"; | ||
| Arguments = "-l"; | ||
| } | ||
|
|
||
| protected override void LogEventsFromTextOutput (string singleLine, MessageImportance messageImportance) | ||
| { | ||
| base.LogEventsFromTextOutput (singleLine, messageImportance); | ||
| output.Add (singleLine); | ||
| } | ||
|
|
||
| protected override void LogToolCommand (string message) => Log.LogDebugMessage (message); | ||
|
|
||
| public override bool RunTask () | ||
| { | ||
| if (!base.RunTask ()) | ||
| return false; | ||
|
|
||
| var devices = ParseAdbDevicesOutput (output); | ||
| Devices = devices.ToArray (); | ||
|
|
||
| Log.LogDebugMessage ($"Found {Devices.Length} Android device(s)/emulator(s)"); | ||
|
|
||
| return !Log.HasLoggedErrors; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Parses the output of 'adb devices -l' command. | ||
| /// Example output: | ||
| /// List of devices attached | ||
| /// emulator-5554 device product:sdk_gphone64_arm64 model:sdk_gphone64_arm64 device:emu64a transport_id:1 | ||
| /// 0A041FDD400327 device usb:1-1 product:raven model:Pixel_6_Pro device:raven transport_id:2 | ||
| /// </summary> | ||
| List<ITaskItem> ParseAdbDevicesOutput (List<string> lines) | ||
| { | ||
| var devices = new List<ITaskItem> (); | ||
|
|
||
| foreach (var line in lines) { | ||
| // Skip the header line "List of devices attached" | ||
| if (line.Contains ("List of devices") || string.IsNullOrWhiteSpace (line)) | ||
| continue; | ||
|
|
||
| var match = AdbDevicesRegex.Match (line); | ||
| if (!match.Success) | ||
| continue; | ||
|
|
||
| var serial = match.Groups [1].Value.Trim (); | ||
| var state = match.Groups [2].Value.Trim (); | ||
| var properties = match.Groups [3].Value.Trim (); | ||
|
|
||
| // Parse key:value pairs from the properties string | ||
| var propDict = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase); | ||
| if (!string.IsNullOrWhiteSpace (properties)) { | ||
| // Split by whitespace and parse key:value pairs | ||
| var pairs = properties.Split ([' '], StringSplitOptions.RemoveEmptyEntries); | ||
| foreach (var pair in pairs) { | ||
| var colonIndex = pair.IndexOf (':'); | ||
| if (colonIndex > 0 && colonIndex < pair.Length - 1) { | ||
| var key = pair.Substring (0, colonIndex); | ||
| var value = pair.Substring (colonIndex + 1); | ||
| propDict [key] = value; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Determine device type: Emulator or Device | ||
| var deviceType = serial.StartsWith ("emulator-", StringComparison.OrdinalIgnoreCase) ? DeviceType.Emulator : DeviceType.Device; | ||
|
|
||
| // Build a friendly description | ||
| var description = BuildDeviceDescription (serial, propDict, deviceType); | ||
|
|
||
| // Map adb state to device status | ||
| var status = MapAdbStateToStatus (state); | ||
|
|
||
| // Create the MSBuild item | ||
| var item = new TaskItem (serial); | ||
| item.SetMetadata ("Description", description); | ||
| item.SetMetadata ("Type", deviceType.ToString ()); | ||
| item.SetMetadata ("Status", status); | ||
|
|
||
| // Add optional metadata for additional information | ||
| if (propDict.TryGetValue ("model", out var model)) | ||
| item.SetMetadata ("Model", model); | ||
| if (propDict.TryGetValue ("product", out var product)) | ||
| item.SetMetadata ("Product", product); | ||
| if (propDict.TryGetValue ("device", out var device)) | ||
| item.SetMetadata ("Device", device); | ||
| if (propDict.TryGetValue ("transport_id", out var transportId)) | ||
| item.SetMetadata ("TransportId", transportId); | ||
|
|
||
| devices.Add (item); | ||
| } | ||
|
|
||
| return devices; | ||
| } | ||
|
|
||
| string BuildDeviceDescription (string serial, Dictionary<string, string> properties, DeviceType deviceType) | ||
| { | ||
| // Try to build a human-friendly description | ||
| // Priority: AVD name (for emulators) > model > product > device > serial | ||
|
|
||
| // For emulators, try to get the AVD display name | ||
| if (deviceType == DeviceType.Emulator) { | ||
| var avdName = GetEmulatorAvdDisplayName (serial); | ||
| if (!string.IsNullOrEmpty (avdName)) | ||
| return avdName!; | ||
| } | ||
|
|
||
| if (properties.TryGetValue ("model", out var model) && !string.IsNullOrEmpty (model)) { | ||
| // Clean up model name - replace underscores with spaces | ||
| model = model.Replace ('_', ' '); | ||
| return model; | ||
| } | ||
|
|
||
| if (properties.TryGetValue ("product", out var product) && !string.IsNullOrEmpty (product)) { | ||
| product = product.Replace ('_', ' '); | ||
| return product; | ||
| } | ||
|
|
||
| if (properties.TryGetValue ("device", out var device) && !string.IsNullOrEmpty (device)) { | ||
| device = device.Replace ('_', ' '); | ||
| return device; | ||
| } | ||
|
|
||
| // Fallback to serial number | ||
| return serial; | ||
| } | ||
|
|
||
| static string MapAdbStateToStatus (string adbState) | ||
| { | ||
| // Map adb device states to the spec's status values | ||
| return adbState.ToLowerInvariant () switch { | ||
| "device" => "Online", | ||
| "offline" => "Offline", | ||
| "unauthorized" => "Unauthorized", | ||
| "no permissions" => "NoPermissions", | ||
| _ => "Unknown", | ||
| }; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Queries the emulator for its AVD name using 'adb -s <serial> emu avd name' | ||
| /// and formats it as a friendly display name. | ||
| /// </summary> | ||
| protected virtual string? GetEmulatorAvdDisplayName (string serial) | ||
| { | ||
| try { | ||
| var adbPath = System.IO.Path.Combine (ToolPath, ToolExe); | ||
| var outputLines = new List<string> (); | ||
|
|
||
| var exitCode = MonoAndroidHelper.RunProcess ( | ||
| adbPath, | ||
| $"-s {serial} emu avd name", | ||
| Log, | ||
| onOutput: (sender, e) => { | ||
| if (!string.IsNullOrEmpty (e.Data)) { | ||
| outputLines.Add (e.Data); | ||
| base.LogEventsFromTextOutput (e.Data, MessageImportance.Normal); | ||
| } | ||
| }, | ||
| logWarningOnFailure: false | ||
| ); | ||
|
|
||
| if (exitCode == 0 && outputLines.Count > 0) { | ||
| var avdName = outputLines [0].Trim (); | ||
| // Verify it's not the "OK" response | ||
| if (!string.IsNullOrEmpty (avdName) && !avdName.Equals ("OK", StringComparison.OrdinalIgnoreCase)) { | ||
| // Format the AVD name: replace underscores with spaces | ||
| return avdName.Replace ('_', ' '); | ||
| } | ||
| } | ||
| } catch (Exception ex) { | ||
| Log.LogDebugMessage ($"Failed to get AVD display name for {serial}: {ex}"); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there any possible world where there's some way to do input/output tracking here for incrementality purposes?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It has to query each time because you could click the X on the emulator, unplug the device, etc.
It was taking 55ms on my machine, but we can see if there are different
adbcommands that are faster in the future. I was also thinking about reading files on disk like%userprofile%\.android\avd\pixel_7_-_api_36.inithat could be faster than launching a new process.