Skip to content
Open
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
9 changes: 9 additions & 0 deletions StabilityMatrix.Avalonia/Languages/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions StabilityMatrix.Avalonia/Languages/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -1883,4 +1883,7 @@ Account tokens will not be viewable after saving, please make a note of them if
<data name="Error_DocumentationPageLoadFailed" xml:space="preserve">
<value>Could not load this page. Check your connection and try again.</value>
</data>
<data name="Error_PythonPackageDetailsLoadFailed" xml:space="preserve">
<value>Could not load details for this package. Reselect to retry.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Core.Exceptions;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;

namespace StabilityMatrix.Avalonia.ViewModels.Dialogs;

public partial class PythonPackagesItemViewModel(ISettingsManager settingsManager) : ViewModelBase
public partial class PythonPackagesItemViewModel : ViewModelBase
{
[ObservableProperty]
private PipPackageInfo package;
Expand All @@ -27,6 +25,15 @@ public partial class PythonPackagesItemViewModel(ISettingsManager settingsManage
[ObservableProperty]
private bool isLoading;

/// <summary>
/// Message of the last failed attempt to load <see cref="PipShowResult"/>, shown in the details pane
/// </summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasLoadError))]
public partial string? LoadErrorMessage { get; set; }

public bool HasLoadError => LoadErrorMessage is not null;

/// <summary>
/// True if selected version is newer than the installed version
/// </summary>
Expand Down Expand Up @@ -79,16 +86,18 @@ value is null
}

/// <summary>
/// Loads the pip show result if not already loaded
/// Loads the pip show result if not already loaded or loading. A failed load can be retried
/// by calling this again; errors other than <see cref="ProcessException"/> are rethrown.
/// </summary>
public async Task LoadExtraInfo(DirectoryPath venvPath, PyBaseInstall pyBaseInstall)
public async Task LoadExtraInfo(Func<Task<IPyVenvRunner>> createVenvRunner)
{
if (PipShowResult is not null)
if (PipShowResult is not null || IsLoading)
{
return;
}

IsLoading = true;
LoadErrorMessage = null;

try
{
Expand All @@ -98,27 +107,32 @@ public async Task LoadExtraInfo(DirectoryPath venvPath, PyBaseInstall pyBaseInst
}
else
{
await using var venvRunner = await pyBaseInstall.CreateVenvRunnerAsync(
venvPath,
workingDirectory: venvPath.Parent,
environmentVariables: settingsManager.Settings.EnvironmentVariables
);
await using var venvRunner = await createVenvRunner();

PipShowResult = await venvRunner.PipShow(Package.Name);
var pipShowResult = await venvRunner.PipShow(Package.Name);

// Attempt to get known index url
var indexUrl = GetKnownIndexUrl(Package.Name, Package.Version);
var pipIndexResult = await venvRunner.PipIndex(Package.Name, indexUrl);

if (await venvRunner.PipIndex(Package.Name, indexUrl) is { } pipIndexResult)
// Only mark as loaded once both calls succeed, so a failed index lookup is retried
PipShowResult = pipShowResult;

if (pipIndexResult is not null)
{
AvailableVersions = pipIndexResult.AvailableVersions;
SelectedVersion = Package.Version;
}
}
}
catch (ProcessException)
catch (Exception e) when (e is not OperationCanceledException)
{
// Ignore
LoadErrorMessage = e.Message;

if (e is not ProcessException)
{
throw;
}
}
finally
{
Expand Down
142 changes: 117 additions & 25 deletions StabilityMatrix.Avalonia/ViewModels/Dialogs/PythonPackagesViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,20 @@ public partial class PythonPackagesViewModel : ContentDialogViewModelBase
private readonly IPrerequisiteHelper prerequisiteHelper;
private PyBaseInstall? pyBaseInstall;

/// <summary>
/// Lets only one package's details load at a time. Typing in the search box moves the
/// selection on almost every keystroke, which would otherwise start overlapping pip
/// processes against the same venv (each one rewriting its pyvenv.cfg).
/// </summary>
private readonly SemaphoreSlim extraInfoLock = new(1, 1);

private CancellationTokenSource? extraInfoCts;

/// <summary>
/// Replaces how venv runners are created, so tests can run without a real Python install.
/// </summary>
internal Func<Task<IPyVenvRunner>>? VenvRunnerFactory { get; set; }

public DirectoryPath? VenvPath { get; set; }

public PyVersion? PythonVersion { get; set; }
Expand Down Expand Up @@ -85,7 +99,7 @@ private void PostConstruct()
.Connect()
.DeferUntilLoaded()
.Filter(searchPredicate)
.Transform(p => new PythonPackagesItemViewModel(settingsManager) { Package = p })
.Transform(p => new PythonPackagesItemViewModel { Package = p })
.SortBy(vm => vm.Package.Name)
.ObserveOn(SynchronizationContext.Current!)
.Bind(Packages)
Expand All @@ -107,17 +121,7 @@ private async Task Refresh()
}
else
{
pyBaseInstall ??= new PyBaseInstall(
await pyInstallationManager.GetInstallationAsync(
PythonVersion ?? PyInstallationManager.Python_3_10_11
)
);

await using var venvRunner = await pyBaseInstall.CreateVenvRunnerAsync(
VenvPath,
workingDirectory: VenvPath.Parent,
environmentVariables: settingsManager.Settings.EnvironmentVariables
);
await using var venvRunner = await CreateVenvRunnerAsync();

var packages = await venvRunner.PipList();

Expand All @@ -143,16 +147,7 @@ private async Task RefreshBackground()
if (VenvPath is null)
return;

pyBaseInstall ??= new PyBaseInstall(
await pyInstallationManager.GetInstallationAsync(
PythonVersion ?? PyInstallationManager.Python_3_10_11
)
);
await using var venvRunner = await pyBaseInstall.CreateVenvRunnerAsync(
VenvPath,
workingDirectory: VenvPath.Parent,
environmentVariables: settingsManager.Settings.EnvironmentVariables
);
await using var venvRunner = await CreateVenvRunnerAsync();

var packages = await venvRunner.PipList();

Expand All @@ -169,20 +164,117 @@ await pyInstallationManager.GetInstallationAsync(
});
}

private async Task<IPyVenvRunner> CreateVenvRunnerAsync()
{
if (VenvRunnerFactory is not null)
{
return await VenvRunnerFactory();
}

ArgumentNullException.ThrowIfNull(VenvPath);

pyBaseInstall ??= new PyBaseInstall(
await pyInstallationManager.GetInstallationAsync(
PythonVersion ?? PyInstallationManager.Python_3_10_11
)
);

return await pyBaseInstall.CreateVenvRunnerAsync(
VenvPath,
workingDirectory: VenvPath.Parent,
environmentVariables: settingsManager.Settings.EnvironmentVariables
);
}

/// <summary>
/// Load the selected package's show info if not already loaded
/// </summary>
partial void OnSelectedPackageChanged(PythonPackagesItemViewModel? value)
{
if (value is null)
// A load still waiting for its turn is no longer wanted once the selection moves on
extraInfoCts?.Cancel();
extraInfoCts?.Dispose();
extraInfoCts = null;

if (value is null || (VenvPath is null && !Design.IsDesignMode))
{
return;
}

var cts = new CancellationTokenSource();
extraInfoCts = cts;

LoadExtraInfoAsync(value, cts.Token)
.SafeFireAndForget(ex =>
logger.LogWarning(ex, "Failed to load details for Python package {Name}", value.Package.Name)
);
}

private async Task LoadExtraInfoAsync(
PythonPackagesItemViewModel item,
CancellationToken cancellationToken
)
{
try
{
await extraInfoLock.WaitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
return;
}

if (value.PipShowResult is null)
try
{
// Skip if the selection moved on while waiting; the item itself skips if already loaded
if (!ReferenceEquals(SelectedPackage, item))
{
return;
}

await item.LoadExtraInfo(CreateVenvRunnerAsync);
}
finally
{
ReleaseExtraInfoLock();
}
}

private void ReleaseExtraInfoLock()
{
try
{
value.LoadExtraInfo(VenvPath!, pyBaseInstall!).SafeFireAndForget();
extraInfoLock.Release();
}
catch (ObjectDisposedException)
{
// The dialog was closed and disposed while a load was still running
}
}

/// <inheritdoc />
public override void OnUnloaded()
{
base.OnUnloaded();

// Drop any load still waiting for its turn once the dialog closes
extraInfoCts?.Cancel();
extraInfoCts?.Dispose();
extraInfoCts = null;
}

/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
extraInfoCts?.Cancel();
extraInfoCts?.Dispose();
extraInfoCts = null;
extraInfoLock.Dispose();
}

base.Dispose(disposing);
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ public async Task OpenPythonPackagesDialog()
if (Package is not { FullPath: not null })
return;

var vm = vmFactory.Get<PythonPackagesViewModel>(vm =>
using var vm = vmFactory.Get<PythonPackagesViewModel>(vm =>
{
vm.VenvPath = new DirectoryPath(Package.FullPath, "venv");
vm.PythonVersion = PyVersion.Parse(Package.PythonVersion);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@
<TextBlock Text="{Binding PipShowResult.License}" TextWrapping="WrapWithOverflow" />
<HyperlinkButton NavigateUri="{Binding PipShowResult.HomePage}" />
<TextBlock Text="{Binding PipShowResult.Summary}" TextWrapping="WrapWithOverflow" />
<TextBlock
Foreground="{DynamicResource ThemeRedColor}"
IsVisible="{Binding HasLoadError}"
Text="{x:Static lang:Resources.Error_PythonPackageDetailsLoadFailed}"
TextWrapping="WrapWithOverflow"
ToolTip.Tip="{Binding LoadErrorMessage}" />
</StackPanel>

<!-- Loading indicator -->
Expand Down
18 changes: 12 additions & 6 deletions StabilityMatrix.Core/Python/PipIndexResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@ public partial record PipIndexResult

public static PipIndexResult Parse(string output)
{
var match = AvailableVersionsRegex().Matches(output);

var versions = output
var versionsMatch = output
.SplitLines()
.Select(line => AvailableVersionsRegex().Match(line))
.First(m => m.Success)
.Groups["versions"].Value
.Split(
.FirstOrDefault(m => m.Success);

// Output without an "Available versions:" line (e.g. only warnings) has no versions to offer
if (versionsMatch is null)
{
return new PipIndexResult { AvailableVersions = [] };
}

var versions = versionsMatch
.Groups["versions"]
.Value.Split(
new[] { ',' },
StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries
)
Expand Down
9 changes: 6 additions & 3 deletions StabilityMatrix.Core/Python/PipShowResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,15 @@ public static PipShowResult Parse(string output)
var indexOfLicense = GetIndexBySubstring(lines, "License:");
var indexOfLocation = GetIndexBySubstring(lines, "Location:");

var licenseText =
indexOfLicense == -1 ? null : string.Join('\n', lines[indexOfLicense..indexOfLocation]);
// A multi-line license runs up to the "Location:" line. If that line is missing or comes
// first, only take the "License:" line itself.
var licenseEnd = indexOfLocation > indexOfLicense ? indexOfLocation : indexOfLicense + 1;

var licenseText = indexOfLicense == -1 ? null : string.Join('\n', lines[indexOfLicense..licenseEnd]);

if (indexOfLicense != -1)
{
lines.RemoveRange(indexOfLicense, indexOfLocation - indexOfLicense);
lines.RemoveRange(indexOfLicense, licenseEnd - indexOfLicense);
}

var linesDict = new Dictionary<string, string>();
Expand Down
Loading
Loading