From db1dcee1954dd9ef60175bad2fa4be82d8158723 Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Thu, 12 Nov 2026 15:27:54 -0800 Subject: [PATCH 1/9] initial impl --- .../1.31/powershell-agreement-consent.md | 21 ++ .../CommonFiles/PowerShellCmdlet.cs | 60 ++++++ .../Export-WinGetPackage.md | 43 ++++- .../Find-WinGetPackage.md | 22 ++- .../Get-WinGetPackage.md | 22 ++- .../Install-WinGetPackage.md | 43 ++++- .../Repair-WinGetPackage.md | 45 ++++- .../Uninstall-WinGetPackage.md | 23 ++- .../Update-WinGetPackage.md | 43 ++++- .../Cmdlets/Common/FinderCmdlet.cs | 6 + .../Cmdlets/ExportPackageCmdlet.cs | 2 + .../Cmdlets/FindPackageCmdlet.cs | 1 + .../Cmdlets/GetPackageCmdlet.cs | 1 + .../Cmdlets/InstallPackageCmdlet.cs | 2 + .../Cmdlets/InstallerSelectionCmdlet.cs | 6 + .../Cmdlets/RepairPackageCmdlet.cs | 8 + .../Cmdlets/UninstallPackageCmdlet.cs | 1 + .../Cmdlets/UpdatePackageCmdlet.cs | 2 + .../Commands/Common/FinderCommand.cs | 103 +++++++++- .../Commands/Common/InstallCommand.cs | 3 + .../Commands/Common/PackageCommand.cs | 54 ++++++ .../Commands/DownloadCommand.cs | 8 + .../Commands/InstallerPackageCommand.cs | 2 + .../Commands/RepairPackageCommand.cs | 19 ++ .../Exceptions/NoSourcesAvailableException.cs | 27 +++ .../PackageAgreementsNotAcceptedException.cs | 28 +++ .../PackageAgreementsUnavailableException.cs | 29 +++ .../Helpers/AgreementConsent.cs | 180 ++++++++++++++++++ .../Properties/Resources.Designer.cs | 144 ++++++++++++++ .../Properties/Resources.resx | 61 ++++++ .../Microsoft.WinGet.DSC.psm1 | 15 ++ .../tests/Microsoft.WinGet.Client.Tests.ps1 | 47 +++++ .../tests/Microsoft.WinGet.DSC.Tests.ps1 | 12 ++ 33 files changed, 1071 insertions(+), 12 deletions(-) create mode 100644 doc/release-notes/1.31/powershell-agreement-consent.md create mode 100644 src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/NoSourcesAvailableException.cs create mode 100644 src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsNotAcceptedException.cs create mode 100644 src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsUnavailableException.cs create mode 100644 src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs diff --git a/doc/release-notes/1.31/powershell-agreement-consent.md b/doc/release-notes/1.31/powershell-agreement-consent.md new file mode 100644 index 0000000000..cdd0d606ef --- /dev/null +++ b/doc/release-notes/1.31/powershell-agreement-consent.md @@ -0,0 +1,21 @@ +## New Features + +### PowerShell module asks for consent to source and package agreements + +Microsoft.WinGet.Client now shows source and package agreements and asks for consent before +accepting them, instead of accepting them silently. Accepted source agreements are saved, so each +source asks only once until its agreements change. If you decline a source's agreements, that source +is left out of the results. If you decline a package's agreements, the package is not installed. + +* `-AcceptSourceAgreements` is available on `Find-`, `Get-`, `Install-`, `Update-`, `Uninstall-`, + `Repair-` and `Export-WinGetPackage`. +* `-AcceptPackageAgreements` is available on `Install-`, `Update-`, `Repair-` and + `Export-WinGetPackage`. `Repair-WinGetPackage` can now repair packages that have agreements. +* When the host cannot prompt, such as with `-NonInteractive`, the agreements are still accepted but + are shown in a warning. This behavior is deprecated: a future release will require the switches + in non-interactive use, so update scripts and automation to pass them. +* The `WinGetPackage` resource in Microsoft.WinGet.DSC has a new `AcceptAgreements` property, which + defaults to `true` and passes both switches. + +Accepting a package's agreements also accepts the agreements of any dependencies that are installed +with it. diff --git a/src/PowerShell/CommonFiles/PowerShellCmdlet.cs b/src/PowerShell/CommonFiles/PowerShellCmdlet.cs index ac4d7ba6f4..e5e7a8e26f 100644 --- a/src/PowerShell/CommonFiles/PowerShellCmdlet.cs +++ b/src/PowerShell/CommonFiles/PowerShellCmdlet.cs @@ -510,6 +510,66 @@ internal bool ShouldProcess(string target) return shouldProcess; } + /// + /// Asks the user to confirm an action. Each prompt is answered on its own, so that one answer + /// cannot apply to content the user has not seen. + /// + /// The question to ask. + /// The caption of the prompt. + /// The user's answer, or null if the host cannot prompt the user. + internal bool? ShouldContinue(string query, string caption) + { + if (!this.IsInteractive()) + { + return null; + } + + bool? result = null; + this.ExecuteInPowerShellThread(() => + { + try + { + result = this.psCmdlet.ShouldContinue(query, caption); + } + catch (PSInvalidOperationException) + { + // The host is in non-interactive mode. + result = null; + } + catch (System.Management.Automation.Host.HostException) + { + // The host does not support prompting. + result = null; + } + }); + return result; + } + + /// + /// Determines whether the user can be prompted. + /// + /// True if the host can prompt the user. + internal bool IsInteractive() + { + if (!Environment.UserInteractive || this.psCmdlet.Host?.UI == null) + { + return false; + } + + foreach (string arg in Environment.GetCommandLineArgs()) + { + // Matches -NonInteractive and its abbreviations, with either prefix character. + if (arg.Length >= 5 && + (arg[0] == '-' || arg[0] == '/') && + "noninteractive".StartsWith(arg.Substring(1), StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + + return true; + } + private void Complete() { this.queuedStreams.CompleteAdding(); diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Export-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Export-WinGetPackage.md index e6e81882b7..0d0e5b1d77 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Export-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Export-WinGetPackage.md @@ -21,7 +21,7 @@ Export-WinGetPackage [-DownloadDirectory ] [-AllowHashMismatch] [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [-Version ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] [-MatchOption ] - [-WhatIf] [-Confirm] [] + [-AcceptPackageAgreements] [-AcceptSourceAgreements] [-WhatIf] [-Confirm] [] ``` ### GivenSet @@ -30,7 +30,7 @@ Export-WinGetPackage [-DownloadDirectory ] [-AllowHashMismatch] Export-WinGetPackage [-DownloadDirectory ] [-AllowHashMismatch] [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [[-PSCatalogPackage] ] - [-Version ] [-WhatIf] [-Confirm] [] + [-Version ] [-AcceptPackageAgreements] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -81,6 +81,45 @@ folder name is created by concatenating the package identifier and version numbe ## PARAMETERS +### -AcceptPackageAgreements + +Accepts the agreements of the package that is selected. The agreements are shown as a warning. +Without this parameter, an interactive session asks you to accept or decline them; declining stops +the operation for that package. In a non-interactive session, the agreements are currently accepted +and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: FoundSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -AllowHashMismatch Allows you to download package even when the SHA256 hash for an installer or a dependency does not diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Find-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Find-WinGetPackage.md index 30e3ed283e..7d842217b3 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Find-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Find-WinGetPackage.md @@ -17,7 +17,7 @@ Searches for packages from configured sources. ``` Find-WinGetPackage [-Tag ] [-Command ] [-Count ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] [-MatchOption ] - [] + [-AcceptSourceAgreements] [] ``` ## DESCRIPTION @@ -65,6 +65,26 @@ searches all configured sources. The command performs a case-sensitive full text ## PARAMETERS +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Command Specify the name of the command defined in the package manifest. diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Get-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Get-WinGetPackage.md index 754712368f..9a21b99bdb 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Get-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Get-WinGetPackage.md @@ -17,7 +17,7 @@ Lists installed packages. ``` Get-WinGetPackage [-Tag ] [-Command ] [-Count ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] [-MatchOption ] - [] + [-AcceptSourceAgreements] [] ``` ## DESCRIPTION @@ -63,6 +63,26 @@ This example shows how to list all packages that have an available upgrade from ## PARAMETERS +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Command Specify the name of the command defined in the package manifest. diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Install-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Install-WinGetPackage.md index 037d872cd4..1cd71589a3 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Install-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Install-WinGetPackage.md @@ -22,7 +22,7 @@ Install-WinGetPackage [-Mode ] [-Override ] [-Cust [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [-Version ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] [-MatchOption ] - [-WhatIf] [-Confirm] [] + [-AcceptPackageAgreements] [-AcceptSourceAgreements] [-WhatIf] [-Confirm] [] ``` ### GivenSet @@ -32,7 +32,7 @@ Install-WinGetPackage [-Mode ] [-Override ] [-Cust [-Location ] [-Log ] [-Force] [-Header ] [-AllowHashMismatch] [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [[-PSCatalogPackage] ] - [-Version ] [-WhatIf] [-Confirm] [] + [-Version ] [-AcceptPackageAgreements] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -85,6 +85,45 @@ matches with the version of `7.4.4.0`. ## PARAMETERS +### -AcceptPackageAgreements + +Accepts the agreements of the package that is selected. The agreements are shown as a warning. +Without this parameter, an interactive session asks you to accept or decline them; declining stops +the operation for that package. In a non-interactive session, the agreements are currently accepted +and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: FoundSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -AllowHashMismatch Allows you to download package even when the SHA256 hash for an installer or a dependency does not diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md index 8dd0b982fc..9cac0e68af 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md @@ -17,14 +17,16 @@ Repairs a WinGet Package. ``` Repair-WinGetPackage [-Mode ] [-Log ] [-Version ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] - [-MatchOption ] [-ProgressAction ] [-WhatIf] [-Confirm] + [-MatchOption ] [-AcceptPackageAgreements] [-AcceptSourceAgreements] + [-ProgressAction ] [-WhatIf] [-Confirm] [] ``` ### GivenSet ``` Repair-WinGetPackage [-Mode ] [-Log ] [[-PSCatalogPackage] ] - [-Version ] [-ProgressAction ] [-WhatIf] [-Confirm] [] + [-Version ] [-AcceptPackageAgreements] [-ProgressAction ] [-WhatIf] + [-Confirm] [] ``` ## DESCRIPTION @@ -63,6 +65,45 @@ This example shows how to repair a package using the package name. ## PARAMETERS +### -AcceptPackageAgreements + +Accepts the agreements of the package that is selected. The agreements are shown as a warning. +Without this parameter, an interactive session asks you to accept or decline them; declining stops +the operation for that package. In a non-interactive session, the agreements are currently accepted +and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: FoundSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Id Specify the package identifier to search for. By default, the command does a case-insensitive diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Uninstall-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Uninstall-WinGetPackage.md index 91d92f7078..cc475af461 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Uninstall-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Uninstall-WinGetPackage.md @@ -19,7 +19,8 @@ Uninstalls a WinGet Package. ``` Uninstall-WinGetPackage [-Mode ] [-Force] [-Log ] [-Version ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] - [-MatchOption ] [-WhatIf] [-Confirm] [] + [-MatchOption ] [-AcceptSourceAgreements] [-WhatIf] [-Confirm] + [] ``` ### GivenSet @@ -79,6 +80,26 @@ matches with the version of `7.4.4.0`. ## PARAMETERS +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: FoundSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Force Force the uninstall to run. diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Update-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Update-WinGetPackage.md index 5e51d65de0..cda625d660 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Update-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Update-WinGetPackage.md @@ -22,7 +22,7 @@ Update-WinGetPackage [-IncludeUnknown] [-Mode ] [-Override [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [-Version ] [-Id ] [-Name ] [-Moniker ] [-Source ] [[-Query] ] [-MatchOption ] - [-WhatIf] [-Confirm] [] + [-AcceptPackageAgreements] [-AcceptSourceAgreements] [-WhatIf] [-Confirm] [] ``` ### GivenSet @@ -32,7 +32,7 @@ Update-WinGetPackage [-IncludeUnknown] [-Mode ] [-Override [-Location ] [-Log ] [-Force] [-Header ] [-AllowHashMismatch] [-Architecture ] [-InstallerType ] [-Locale ] [-Scope ] [-SkipDependencies] [[-PSCatalogPackage] ] - [-Version ] [-WhatIf] [-Confirm] [] + [-Version ] [-AcceptPackageAgreements] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION @@ -91,6 +91,45 @@ This example shows how to update all packages that have an available upgrade fro ## PARAMETERS +### -AcceptPackageAgreements + +Accepts the agreements of the package that is selected. The agreements are shown as a warning. +Without this parameter, an interactive session asks you to accept or decline them; declining stops +the operation for that package. In a non-interactive session, the agreements are currently accepted +and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -AcceptSourceAgreements + +Accepts the agreements of every source that is searched. When the agreements of a source have not +been accepted before, they are shown as a warning and the acceptance is recorded, so later commands +don't ask again. Without this parameter, an interactive session asks you to accept or decline them; +declined sources are excluded from the search. In a non-interactive session, the agreements are +currently accepted and shown as a warning. A future release will require this parameter instead. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: FoundSet +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -AllowHashMismatch Allows you to download package even when the SHA256 hash for an installer or a dependency does not diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/Common/FinderCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/Common/FinderCmdlet.cs index e92481820e..d94128776f 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/Common/FinderCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/Common/FinderCmdlet.cs @@ -65,5 +65,11 @@ public abstract class FinderCmdlet : PSCmdlet ParameterSetName = Constants.FoundSet, ValueFromPipelineByPropertyName = true)] public PSPackageFieldMatchOption MatchOption { get; set; } = PSPackageFieldMatchOption.ContainsCaseInsensitive; + + /// + /// Gets or sets a value indicating whether to accept the source agreements without prompting. + /// + [Parameter(ParameterSetName = Constants.FoundSet)] + public SwitchParameter AcceptSourceAgreements { get; set; } } } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/ExportPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/ExportPackageCmdlet.cs index f7ae923557..2b9ee02ffb 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/ExportPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/ExportPackageCmdlet.cs @@ -66,6 +66,8 @@ protected override void ProcessRecord() this.AllowHashMismatch.ToBool(), this.SkipDependencies.ToBool(), this.Locale); + this.command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); + this.command.AcceptPackageAgreements = this.AcceptPackageAgreements.ToBool(); this.command.Download( this.DownloadDirectory, this.MatchOption.ToString(), diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/FindPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/FindPackageCmdlet.cs index cf020fd00a..d5c6ab4dce 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/FindPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/FindPackageCmdlet.cs @@ -35,6 +35,7 @@ protected override void ProcessRecord() this.Tag, this.Command, this.Count); + command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); command.Find(this.MatchOption.ToString()); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/GetPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/GetPackageCmdlet.cs index 9338faba32..ca14b939a3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/GetPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/GetPackageCmdlet.cs @@ -35,6 +35,7 @@ protected override void ProcessRecord() this.Tag, this.Command, this.Count); + command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); command.Get(this.MatchOption.ToString()); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallPackageCmdlet.cs index 37a1d07522..037690c2cc 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallPackageCmdlet.cs @@ -48,6 +48,8 @@ protected override void ProcessRecord() this.Source, this.Query, this.SkipDependencies.ToBool()); + this.command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); + this.command.AcceptPackageAgreements = this.AcceptPackageAgreements.ToBool(); this.command.Install(this.MatchOption.ToString(), this.Scope.ToString(), this.Architecture.ToString(), this.Mode.ToString(), this.InstallerType.ToString()); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallerSelectionCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallerSelectionCmdlet.cs index 7876cb6eab..2d92c9b96e 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallerSelectionCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/InstallerSelectionCmdlet.cs @@ -51,5 +51,11 @@ public abstract class InstallerSelectionCmdlet : PackageCmdlet /// [Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter SkipDependencies { get; set; } + + /// + /// Gets or sets a value indicating whether to accept the package agreements without prompting. + /// + [Parameter] + public SwitchParameter AcceptPackageAgreements { get; set; } } } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/RepairPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/RepairPackageCmdlet.cs index 4dc8b7b7b5..daf22343d8 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/RepairPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/RepairPackageCmdlet.cs @@ -50,6 +50,12 @@ public sealed class RepairPackageCmdlet : PackageCmdlet [Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } + /// + /// Gets or sets a value indicating whether to accept the package agreements without prompting. + /// + [Parameter] + public SwitchParameter AcceptPackageAgreements { get; set; } + /// /// Repairs a package from the local system. /// @@ -67,6 +73,8 @@ protected override void ProcessRecord() this.Moniker, this.Source, this.Query); + this.command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); + this.command.AcceptPackageAgreements = this.AcceptPackageAgreements.ToBool(); this.command.Repair(this.MatchOption.ToString(), this.Mode.ToString()); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UninstallPackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UninstallPackageCmdlet.cs index bf61b6de02..04a0a74f7c 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UninstallPackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UninstallPackageCmdlet.cs @@ -60,6 +60,7 @@ protected override void ProcessRecord() this.Moniker, this.Source, this.Query); + this.command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); this.command.Uninstall(this.MatchOption.ToString(), this.Mode.ToString(), this.Force.ToBool()); } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UpdatePackageCmdlet.cs b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UpdatePackageCmdlet.cs index d6cedc0b9b..a61de918b3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UpdatePackageCmdlet.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Cmdlets/UpdatePackageCmdlet.cs @@ -52,6 +52,8 @@ protected override void ProcessRecord() this.Source, this.Query, this.SkipDependencies); + command.AcceptSourceAgreements = this.AcceptSourceAgreements.ToBool(); + command.AcceptPackageAgreements = this.AcceptPackageAgreements.ToBool(); command.Update(this.IncludeUnknown.ToBool(), this.MatchOption.ToString(), this.Scope.ToString(), this.Architecture.ToString(), this.Mode.ToString(), this.InstallerType.ToString()); } } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs index 16cf70686e..df808b4abc 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs @@ -15,6 +15,8 @@ namespace Microsoft.WinGet.Client.Engine.Commands.Common using Microsoft.WinGet.Client.Engine.Attributes; using Microsoft.WinGet.Client.Engine.Exceptions; using Microsoft.WinGet.Client.Engine.Helpers; + using Microsoft.WinGet.Common.Command; + using Microsoft.WinGet.Resources; /// /// This is the base class for all commands that might need to search for a package. It contains an initial @@ -31,6 +33,11 @@ internal FinderCommand(PSCmdlet psCmdlet) { } + /// + /// Gets or sets a value indicating whether the user accepted the agreements of all sources. + /// + public bool AcceptSourceAgreements { get; set; } + /// /// Gets or sets the field that is matched against the identifier of a package. /// @@ -158,6 +165,7 @@ private PackageCatalogReference GetPackageCatalogReference(CompositeSearchBehavi { CreateCompositePackageCatalogOptions options = ManagementDeploymentFactory.Instance.CreateCreateCompositePackageCatalogOptions(); IReadOnlyList references = this.GetPackageCatalogReferences(this.Source); + bool anyExcluded = false; for (var i = 0; i < references.Count; i++) { var reference = references[i]; @@ -175,14 +183,107 @@ private PackageCatalogReference GetPackageCatalogReference(CompositeSearchBehavi if (!isExplicit) { - options.Catalogs.Add(reference); + if (this.ObtainSourceAgreementsConsent(reference)) + { + options.Catalogs.Add(reference); + } + else + { + anyExcluded = true; + } } } + // Searches of installed packages can continue without any remote source. + if (anyExcluded && options.Catalogs.Count == 0 && behavior != CompositeSearchBehavior.LocalCatalogs) + { + throw new NoSourcesAvailableException(); + } + options.CompositeSearchBehavior = behavior; return PackageManagerWrapper.Instance.CreateCompositePackageCatalog(options); } + /// + /// Obtains consent to the agreements of a source. + /// + /// The source. + /// True if the source can be used; false if it must be excluded. + private bool ObtainSourceAgreementsConsent(PackageCatalogReference reference) + { + string sourceName = reference.Info.Name; + string? agreements; + + try + { + if (reference.SourceAgreementsSatisfied) + { + return true; + } + + agreements = AgreementConsent.FormatSourceAgreements(reference, includeImplicitFields: true); + } + catch (Exception e) when (AgreementConsent.IsMissingContract(e)) + { + // The server cannot report whether the agreements were accepted, so keep its behavior of accepting them. + string? legacyAgreements = null; + try + { + legacyAgreements = AgreementConsent.FormatSourceAgreements(reference, includeImplicitFields: false); + } + catch (Exception legacyException) + { + this.Write(StreamType.Warning, string.Format(Resources.SourceAgreementsUnavailableUnsupported, sourceName, legacyException.Message)); + } + + if (legacyAgreements != null) + { + this.Write(StreamType.Warning, legacyAgreements + Environment.NewLine + string.Format(Resources.AgreementsAcceptedUnsupported, AgreementConsent.AcceptSourceAgreementsParameter)); + } + + return true; + } + catch (Exception e) + { + this.Write(StreamType.Warning, string.Format(Resources.SourceAgreementsUnavailable, sourceName, e.Message)); + return false; + } + + // The agreements are not satisfied, but there are none to show; the source removed them all. + if (agreements == null) + { + return true; + } + + AgreementConsent.Decision decision = AgreementConsent.Obtain( + this, + agreements, + Resources.SourceAgreementsPrompt, + Resources.SourceAgreementsCaption, + this.AcceptSourceAgreements, + AgreementConsent.AcceptSourceAgreementsParameter); + + switch (decision) + { + case AgreementConsent.Decision.Accepted: + try + { + reference.SaveAcceptedSourceAgreements(); + } + catch + { + // Failing to record acceptance only means that the user will be asked again. + } + + return true; + case AgreementConsent.Decision.AcceptedWithoutPrompt: + return true; + default: + this.Write(StreamType.Warning, string.Format(Resources.SourceAgreementsDeclined, sourceName)); + return false; + } + } + private FindPackagesOptions GetFindPackagesOptions(uint limit, PackageFieldMatchOption match) { var options = ManagementDeploymentFactory.Instance.CreateFindPackagesOptions(); diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/InstallCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/InstallCommand.cs index 7bcac8d927..7f6e2d0066 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/InstallCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/InstallCommand.cs @@ -81,6 +81,9 @@ internal virtual InstallOptions GetInstallOptions(PackageVersionId? version, str options.SkipDependencies = this.SkipDependencies; options.Force = this.Force; options.PackageInstallMode = PSEnumHelpers.ToPackageInstallMode(mode); + + // Consent to the package agreements is obtained before the options are created. + options.AcceptPackageAgreements = true; if (version != null) { options.PackageVersionId = version; diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs index 4bbd65b142..5d867c5af2 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs @@ -15,6 +15,7 @@ namespace Microsoft.WinGet.Client.Engine.Commands.Common using Microsoft.WinGet.Client.Engine.Extensions; using Microsoft.WinGet.Client.Engine.Helpers; using Microsoft.WinGet.Client.Engine.PSObjects; + using Microsoft.WinGet.Resources; /// /// This is the base class for commands which operate on a specific package and version i.e., @@ -31,6 +32,11 @@ internal PackageCommand(PSCmdlet psCmdlet) { } + /// + /// Gets or sets a value indicating whether the user accepted the agreements of the package. + /// + public bool AcceptPackageAgreements { get; set; } + /// /// Gets or sets the package to directly install. /// @@ -69,6 +75,54 @@ internal PackageCommand(PSCmdlet psCmdlet) return null; } + /// + /// Obtains consent to the agreements of a package version, throwing if the user declines them. + /// + /// The package. + /// The version whose agreements apply; if null, there are none to obtain. + /// The preferred locale of the agreements. + internal void ObtainPackageAgreementsConsent(CatalogPackage package, PackageVersionInfo? versionInfo, string? locale = null) + { + if (versionInfo == null) + { + // The operation itself reports that there is no version to use. + return; + } + + string description = $"{package.Name} [{package.Id}] Version {versionInfo.Version}"; + string? agreements; + + try + { + CatalogPackageMetadata metadata = string.IsNullOrEmpty(locale) + ? versionInfo.GetCatalogPackageMetadata() + : versionInfo.GetCatalogPackageMetadata(locale); + agreements = AgreementConsent.FormatPackageAgreements(description, metadata?.Agreements); + } + catch (Exception e) + { + throw new PackageAgreementsUnavailableException(description, e); + } + + if (agreements == null) + { + return; + } + + AgreementConsent.Decision decision = AgreementConsent.Obtain( + this, + agreements, + Resources.PackageAgreementsPrompt, + Resources.PackageAgreementsCaption, + this.AcceptPackageAgreements, + AgreementConsent.AcceptPackageAgreementsParameter); + + if (decision == AgreementConsent.Decision.Declined) + { + throw new PackageAgreementsNotAcceptedException(description); + } + } + /// /// Sets the find package options for a query input that is looking for a specific package. /// DO NOT pass PackageFieldMatchOption WinRT enum type in this method. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/DownloadCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/DownloadCommand.cs index bf418bbd7d..4e2c9f10c6 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/DownloadCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/DownloadCommand.cs @@ -111,6 +111,11 @@ public void Download( PSEnumHelpers.ToPackageFieldMatchOption(psPackageFieldMatchOption), async (package, version) => { + // Without a version, the latest available version is downloaded. + PackageVersionInfo? versionInfo = version != null + ? package.GetPackageVersionInfo(version) + : (package.AvailableVersions.Count > 0 ? package.GetPackageVersionInfo(package.AvailableVersions[0]) : null); + this.ObtainPackageAgreementsConsent(package, versionInfo, this.Locale); DownloadOptions options = this.GetDownloadOptions(version); if (!string.IsNullOrEmpty(downloadDirectory)) @@ -166,6 +171,9 @@ private DownloadOptions GetDownloadOptions(PackageVersionId? version) options.AllowHashMismatch = this.AllowHashMismatch; options.SkipDependencies = this.SkipDependencies; + // Consent to the package agreements is obtained before the options are created. + options.AcceptPackageAgreements = true; + return options; } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/InstallerPackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/InstallerPackageCommand.cs index 5ed6a86925..22c932a8c3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/InstallerPackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/InstallerPackageCommand.cs @@ -105,6 +105,7 @@ public void Install( PSEnumHelpers.ToPackageFieldMatchOption(psPackageFieldMatchOption), async (package, version) => { + this.ObtainPackageAgreementsConsent(package, version != null ? package.GetPackageVersionInfo(version) : package.DefaultInstallVersion); InstallOptions options = this.GetInstallOptions(version, psPackageInstallMode); if (!PSEnumHelpers.IsDefaultEnum(psProcessorArchitecture)) { @@ -151,6 +152,7 @@ public void Update( PSEnumHelpers.ToPackageFieldMatchOption(psPackageFieldMatchOption), async (package, version) => { + this.ObtainPackageAgreementsConsent(package, version != null ? package.GetPackageVersionInfo(version) : package.DefaultInstallVersion); InstallOptions options = this.GetInstallOptions(version, psPackageInstallMode); options.AllowUpgradeToUnknownVersion = includeUnknown; diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs index f7476bdc0b..8fb012c14e 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs @@ -98,6 +98,7 @@ public void Repair( PSEnumHelpers.ToPackageFieldMatchOption(psPackageFieldMatchOption), async (package, version) => { + this.ObtainPackageAgreementsConsent(package, version != null ? package.GetPackageVersionInfo(version) : GetRepairVersionInfo(package)); var repairOptions = this.GetRepairOptions(version, PSEnumHelpers.ToPackageRepairMode(psPackageRepairMode)); return await this.RepairPackageAsync(package, repairOptions); })); @@ -134,6 +135,9 @@ private RepairOptions GetRepairOptions( options.PackageRepairMode = repairMode; + // Consent to the package agreements is obtained before the options are created. + options.AcceptPackageAgreements = true; + if (version != null) { options.PackageVersionId = version; @@ -142,6 +146,21 @@ private RepairOptions GetRepairOptions( return options; } + private static PackageVersionInfo? GetRepairVersionInfo(CatalogPackage package) + { + // Repair uses the available version matching the installed one, when there is one. + string? installedVersion = package.InstalledVersion?.Version; + for (int i = 0; i < package.AvailableVersions.Count; ++i) + { + if (package.AvailableVersions[i].Version == installedVersion) + { + return package.GetPackageVersionInfo(package.AvailableVersions[i]); + } + } + + return package.DefaultInstallVersion; + } + private async Task RepairPackageAsync( CatalogPackage catalogPackage, RepairOptions repairOptions) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/NoSourcesAvailableException.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/NoSourcesAvailableException.cs new file mode 100644 index 0000000000..060a77c772 --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/NoSourcesAvailableException.cs @@ -0,0 +1,27 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.Client.Engine.Exceptions +{ + using System; + using System.Management.Automation; + using Microsoft.WinGet.Resources; + + /// + /// No source could be used because none of their agreements were accepted or readable. + /// + [Serializable] + public class NoSourcesAvailableException : RuntimeException + { + /// + /// Initializes a new instance of the class. + /// + public NoSourcesAvailableException() + : base(Resources.NoSourcesAvailableExceptionMessage) + { + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsNotAcceptedException.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsNotAcceptedException.cs new file mode 100644 index 0000000000..194de482fe --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsNotAcceptedException.cs @@ -0,0 +1,28 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.Client.Engine.Exceptions +{ + using System; + using System.Management.Automation; + using Microsoft.WinGet.Resources; + + /// + /// The agreements of a package were not accepted. + /// + [Serializable] + public class PackageAgreementsNotAcceptedException : RuntimeException + { + /// + /// Initializes a new instance of the class. + /// + /// The package description. + public PackageAgreementsNotAcceptedException(string package) + : base(string.Format(Resources.PackageAgreementsNotAcceptedExceptionMessage, package)) + { + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsUnavailableException.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsUnavailableException.cs new file mode 100644 index 0000000000..1f6c9ba7ab --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Exceptions/PackageAgreementsUnavailableException.cs @@ -0,0 +1,29 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.Client.Engine.Exceptions +{ + using System; + using System.Management.Automation; + using Microsoft.WinGet.Resources; + + /// + /// The agreements of a package could not be read. + /// + [Serializable] + public class PackageAgreementsUnavailableException : RuntimeException + { + /// + /// Initializes a new instance of the class. + /// + /// The package description. + /// The exception that lead to this one. + public PackageAgreementsUnavailableException(string package, Exception inner) + : base(string.Format(Resources.PackageAgreementsUnavailableExceptionMessage, package), inner) + { + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs new file mode 100644 index 0000000000..3551306f27 --- /dev/null +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs @@ -0,0 +1,180 @@ +// ----------------------------------------------------------------------------- +// +// Copyright (c) Microsoft Corporation. Licensed under the MIT License. +// +// ----------------------------------------------------------------------------- + +namespace Microsoft.WinGet.Client.Engine.Helpers +{ + using System; + using System.Collections.Generic; + using System.Runtime.InteropServices; + using System.Text; + using Microsoft.Management.Deployment; + using Microsoft.WinGet.Common.Command; + using Microsoft.WinGet.Resources; + + /// + /// Obtains the user's consent to source and package agreements. + /// + internal static class AgreementConsent + { + /// + /// The name of the parameter that accepts source agreements. + /// + public const string AcceptSourceAgreementsParameter = "-AcceptSourceAgreements"; + + /// + /// The name of the parameter that accepts package agreements. + /// + public const string AcceptPackageAgreementsParameter = "-AcceptPackageAgreements"; + + private const int ENoInterface = unchecked((int)0x80004002); + + /// + /// The result of obtaining consent. + /// + public enum Decision + { + /// + /// The user accepted the agreements, either by parameter or when prompted. + /// Acceptance may be recorded. + /// + Accepted, + + /// + /// The agreements were accepted because the user could not be prompted. + /// Acceptance must not be recorded. + /// + AcceptedWithoutPrompt, + + /// + /// The user declined the agreements. + /// + Declined, + } + + /// + /// Determines whether an exception indicates that the WinGet server does not implement a member. + /// + /// The exception. + /// True if the server is older than the member. + public static bool IsMissingContract(Exception e) + { + return e is InvalidCastException || (e is COMException && e.HResult == ENoInterface); + } + + /// + /// Formats the agreements of a source. + /// + /// The source. + /// Whether to include the implicit agreement fields; requires contract 31. + /// The formatted agreements, or null if there are none. + public static string? FormatSourceAgreements(PackageCatalogReference reference, bool includeImplicitFields) + { + StringBuilder builder = new StringBuilder(); + + // Enumerating WinRT collections through IEnumerable fails with the embedded projection, so index instead. + var agreements = reference.SourceAgreements; + for (int i = 0; i < agreements.Count; ++i) + { + SourceAgreement agreement = agreements[i]; + AppendAgreement(builder, agreement.Label, agreement.Text, agreement.Url); + } + + if (includeImplicitFields && (reference.ImplicitAgreementFields & ImplicitAgreementFields.Market) != 0) + { + AppendAgreement(builder, null, Resources.SourceAgreementsMarketMessage, null); + } + + if (builder.Length == 0) + { + return null; + } + + return string.Format(Resources.SourceAgreementsTitle, reference.Info.Name) + Environment.NewLine + builder.ToString(); + } + + /// + /// Formats the agreements of a package. + /// + /// The package description. + /// The agreements. + /// The formatted agreements, or null if there are none. + public static string? FormatPackageAgreements(string package, IReadOnlyList? agreements) + { + if (agreements == null) + { + return null; + } + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < agreements.Count; ++i) + { + PackageAgreement agreement = agreements[i]; + AppendAgreement(builder, agreement.Label, agreement.Text, agreement.Url); + } + + if (builder.Length == 0) + { + return null; + } + + return string.Format(Resources.PackageAgreementsTitle, package) + Environment.NewLine + builder.ToString(); + } + + /// + /// Obtains consent to a set of agreements. + /// + /// The cmdlet. + /// The formatted agreements. + /// The question to ask the user. + /// The caption of the prompt; Yes to All and No to All apply per caption. + /// Whether the user accepted the agreements with a parameter. + /// The name of the parameter that accepts the agreements. + /// The decision. + public static Decision Obtain( + PowerShellCmdlet cmdlet, + string agreements, + string prompt, + string caption, + bool acceptedByParameter, + string parameterName) + { + if (acceptedByParameter) + { + cmdlet.Write(StreamType.Warning, agreements + Environment.NewLine + string.Format(Resources.AgreementsAcceptedByParameter, parameterName)); + return Decision.Accepted; + } + + // The agreements are part of the query so that they are shown with the prompt; warnings + // written from the background thread may not be displayed until after it. + bool? answer = cmdlet.ShouldContinue(agreements + Environment.NewLine + prompt, caption); + if (answer == null) + { + cmdlet.Write(StreamType.Warning, agreements + Environment.NewLine + string.Format(Resources.AgreementsAcceptedNonInteractive, parameterName)); + return Decision.AcceptedWithoutPrompt; + } + + return answer.Value ? Decision.Accepted : Decision.Declined; + } + + private static void AppendAgreement(StringBuilder builder, string? label, string? text, string? url) + { + if (!string.IsNullOrWhiteSpace(label)) + { + builder.AppendLine(label); + } + + if (!string.IsNullOrWhiteSpace(text)) + { + builder.AppendLine(text); + } + + if (!string.IsNullOrWhiteSpace(url)) + { + builder.AppendLine(url); + } + } + } +} diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs index cd756085a3..8d7c8e423b 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs @@ -446,5 +446,149 @@ internal static string WinGetCLITimeoutExceptionMessage { return ResourceManager.GetString("WinGetCLITimeoutExceptionMessage", resourceCulture); } } + + /// + /// Looks up a localized string similar to The agreements above were accepted because {0} was specified.. + /// + internal static string AgreementsAcceptedByParameter { + get { + return ResourceManager.GetString("AgreementsAcceptedByParameter", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The agreements above were accepted because the user cannot be prompted. This beh[rest of string was truncated]. + /// + internal static string AgreementsAcceptedNonInteractive { + get { + return ResourceManager.GetString("AgreementsAcceptedNonInteractive", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The agreements above were accepted because the installed version of WinGet does [rest of string was truncated]. + /// + internal static string AgreementsAcceptedUnsupported { + get { + return ResourceManager.GetString("AgreementsAcceptedUnsupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No sources are available. The agreements of every source were either not accepte[rest of string was truncated]. + /// + internal static string NoSourcesAvailableExceptionMessage { + get { + return ResourceManager.GetString("NoSourcesAvailableExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The agreements for {0} were not accepted. Operation cancelled.. + /// + internal static string PackageAgreementsNotAcceptedExceptionMessage { + get { + return ResourceManager.GetString("PackageAgreementsNotAcceptedExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Package agreements. + /// + internal static string PackageAgreementsCaption { + get { + return ResourceManager.GetString("PackageAgreementsCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The publisher requires that you view the above information and accept the agreem[rest of string was truncated]. + /// + internal static string PackageAgreementsPrompt { + get { + return ResourceManager.GetString("PackageAgreementsPrompt", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Agreements for {0}. + /// + internal static string PackageAgreementsTitle { + get { + return ResourceManager.GetString("PackageAgreementsTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The agreements for {0} could not be read.. + /// + internal static string PackageAgreementsUnavailableExceptionMessage { + get { + return ResourceManager.GetString("PackageAgreementsUnavailableExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Source agreements. + /// + internal static string SourceAgreementsCaption { + get { + return ResourceManager.GetString("SourceAgreementsCaption", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The `{0}` source was not used because its agreements were not accepted.. + /// + internal static string SourceAgreementsDeclined { + get { + return ResourceManager.GetString("SourceAgreementsDeclined", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The source requires the current machine's 2-letter geographic region to be [rest of string was truncated]. + /// + internal static string SourceAgreementsMarketMessage { + get { + return ResourceManager.GetString("SourceAgreementsMarketMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Do you agree to all the source agreements terms?. + /// + internal static string SourceAgreementsPrompt { + get { + return ResourceManager.GetString("SourceAgreementsPrompt", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The `{0}` source requires that you view the following agreements before using.. + /// + internal static string SourceAgreementsTitle { + get { + return ResourceManager.GetString("SourceAgreementsTitle", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The `{0}` source was not used because its agreements could not be read: {1}. + /// + internal static string SourceAgreementsUnavailable { + get { + return ResourceManager.GetString("SourceAgreementsUnavailable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet accepts its agreements automatically. Error: {1}. + /// + internal static string SourceAgreementsUnavailableUnsupported { + get { + return ResourceManager.GetString("SourceAgreementsUnavailableUnsupported", resourceCulture); + } + } } } diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx index b5aae6b6ad..615f5e2198 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx @@ -264,4 +264,65 @@ An unexpected error happened while trying to repair the package. Error code:{0} {Locked="{0}"} {0} - The error code from the repair operation. + + Source agreements + Caption of the prompt that asks the user to accept the agreements of a source. + + + Package agreements + Caption of the prompt that asks the user to accept the agreements of a package. + + + The `{0}` source requires that you view the following agreements before using. + {Locked="{0}"} Message displayed to inform the user that a repository source requires viewing agreements before using. {0} is a placeholder replaced by the repository source name. + + + Do you agree to all the source agreements terms? + + + The source requires the current machine's 2-letter geographic region to be sent to the backend service to function properly (ex. "US"). + + + The `{0}` source was not used because its agreements were not accepted. + {Locked="{0}"} {0} is a placeholder replaced by the repository source name. + + + The `{0}` source was not used because its agreements could not be read: {1} + {Locked="{0}","{1}"} {0} is a placeholder replaced by the repository source name. {1} is a placeholder replaced by the error message. + + + The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet accepts its agreements automatically. Error: {1} + {Locked="{0}","{1}"} {0} is a placeholder replaced by the repository source name. {1} is a placeholder replaced by the error message. + + + No sources are available. The agreements of every source were either not accepted or could not be read. + + + Agreements for {0} + {Locked="{0}"} Followed by a list of license agreements. {0} is a placeholder replaced by the package name, identifier and version. + + + The publisher requires that you view the above information and accept the agreements before installing. +Do you agree to the terms? + + + The agreements for {0} were not accepted. Operation cancelled. + {Locked="{0}"} {0} is a placeholder replaced by the package name, identifier and version. + + + The agreements for {0} could not be read. + {Locked="{0}"} {0} is a placeholder replaced by the package name, identifier and version. + + + The agreements above were accepted because {0} was specified. + {Locked="{0}"} {0} is a placeholder replaced by a PowerShell parameter name, such as -AcceptSourceAgreements. + + + The agreements above were accepted because the user cannot be prompted. This behavior is deprecated; a future release will not accept agreements unless {0} is specified. + {Locked="{0}"} {0} is a placeholder replaced by a PowerShell parameter name, such as -AcceptSourceAgreements. + + + The agreements above were accepted because the installed version of WinGet does not support recording their acceptance. This behavior is deprecated; a future release will not accept agreements unless {0} is specified. + {Locked="{0}"} {0} is a placeholder replaced by a PowerShell parameter name, such as -AcceptSourceAgreements. + diff --git a/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 b/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 index 6e5d411565..d6d3639526 100644 --- a/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 +++ b/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 @@ -485,6 +485,9 @@ class WinGetPackage [DSCProperty()] [WinGetInstallMode]$InstallMode = [WinGetInstallMode]::Silent + [DscProperty()] + [bool]$AcceptAgreements = $true + [PSObject] hidden $CatalogPackage = $null [WinGetPackage] Get() @@ -495,12 +498,18 @@ class WinGetPackage } $result = [WinGetPackage]::new() + $result.AcceptAgreements = $this.AcceptAgreements $hashArgs = @{ Id = $this.Id MatchOption = $this.MatchOption } + if ($this.AcceptAgreements) + { + $hashArgs.Add("AcceptSourceAgreements", $true) + } + if (-not([string]::IsNullOrWhiteSpace($this.Source))) { $hashArgs.Add("Source", $this.Source) @@ -542,6 +551,12 @@ class WinGetPackage MatchOption = $this.MatchOption Mode = $this.InstallMode } + + if ($this.AcceptAgreements) + { + $hashArgs.Add("AcceptSourceAgreements", $true) + $hashArgs.Add("AcceptPackageAgreements", $true) + } if ($this.Ensure -eq [WinGetEnsure]::Present) { diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 index 4dfca7902a..4a46f20c81 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 @@ -367,6 +367,53 @@ Describe 'Install|Update|Uninstall-WinGetPackage' { } } +Describe 'Package agreements' { + + BeforeAll { + AddTestSource + + $agreementsPackageId = 'AppInstallerTest.CatalogPackageMetadata' + + # Matches the module's check for whether the user can be prompted. + $canPrompt = [Environment]::UserInteractive -and + -not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^[-/]noni' }) + } + + It 'Install with AcceptPackageAgreements shows the agreements' { + $result = Install-WinGetPackage -Id $agreementsPackageId -AcceptPackageAgreements -WarningVariable agreementWarnings -WarningAction SilentlyContinue + + $result.Status | Should -Be 'Ok' + $warningText = $agreementWarnings -join [Environment]::NewLine + $warningText | Should -BeLike '*testAgreementLabel*' + $warningText | Should -BeLike '*testAgreementText*' + $warningText | Should -BeLike '*https://testAgreementUrl.net*' + $warningText | Should -BeLike '*-AcceptPackageAgreements*' + } + + It 'Install without AcceptPackageAgreements in a non-interactive host accepts with a warning' { + if ($canPrompt) + { + Set-ItResult -Skipped -Because 'the host can prompt the user' + return + } + + $result = Install-WinGetPackage -Id $agreementsPackageId -WarningVariable agreementWarnings -WarningAction SilentlyContinue + + $result.Status | Should -Be 'Ok' + $warningText = $agreementWarnings -join [Environment]::NewLine + $warningText | Should -BeLike '*testAgreementLabel*' + $warningText | Should -BeLike '*-AcceptPackageAgreements*' + } + + AfterEach { + $installed = Get-WinGetPackage -Id $agreementsPackageId -MatchOption Equals + if ($installed.Count -gt 0) + { + Uninstall-WinGetPackage -Id $agreementsPackageId -MatchOption Equals + } + } +} + Describe 'Install|Repair|Uninstall-WinGetPackage' { BeforeAll { diff --git a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 index 827fb86505..97ef5daa11 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 @@ -171,6 +171,7 @@ Describe 'WinGetPackage' { $testPackageId = 'AppInstallerTest.TestExeInstaller' $testPackageVersion = '1.0.0.0' + $agreementsPackageId = 'AppInstallerTest.CatalogPackageMetadata' InvokeWinGetDSC -Name WinGetSource -Method Set -Property @{ Name = $testSourceName; Argument = $testSourceArg; Type = $testSourceType; TrustLevel = 'Trusted'; Explicit = $false } } @@ -178,6 +179,7 @@ Describe 'WinGetPackage' { It 'Get WinGetPackage' { $result = InvokeWinGetDSC -Name WinGetPackage -Method Get -Property @{ Id = $testPackageId; Version = $testPackageVersion } $result.Ensure | Should -Be 'Absent' + $result.AcceptAgreements | Should -Be $true } It 'Test WinGetPackage' { @@ -221,8 +223,18 @@ Describe 'WinGetPackage' { $result.Ensure | Should -Be 'Absent' } + It 'Install WinGetPackage with agreements' { + InvokeWinGetDSC -Name WinGetPackage -Method Set -Property @{ Id = $agreementsPackageId } + + $result = InvokeWinGetDSC -Name WinGetPackage -Method Get -Property @{ Id = $agreementsPackageId } + $result.Ensure | Should -Be 'Present' + + InvokeWinGetDSC -Name WinGetPackage -Method Set -Property @{ Ensure = 'Absent'; Id = $agreementsPackageId } + } + AfterAll { InvokeWinGetDSC -Name WinGetPackage -Method Set -Property @{ Ensure = 'Absent'; Id = $testPackageId} + InvokeWinGetDSC -Name WinGetPackage -Method Set -Property @{ Ensure = 'Absent'; Id = $agreementsPackageId} } } From cdbba42f9b1d35fafc4902c2160a9eb4669decea Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Thu, 12 Nov 2026 15:33:05 -0800 Subject: [PATCH 2/9] feedback --- .../1.31/powershell-agreement-consent.md | 4 +++- .../CommonFiles/PowerShellCmdlet.cs | 19 ++----------------- .../Commands/Common/PackageCommand.cs | 2 +- .../Helpers/AgreementConsent.cs | 2 +- .../Properties/Resources.Designer.cs | 11 ++++++++++- .../Properties/Resources.resx | 6 +++++- .../Microsoft.WinGet.DSC.psm1 | 1 - .../tests/Microsoft.WinGet.Client.Tests.ps1 | 2 +- .../tests/Microsoft.WinGet.DSC.Tests.ps1 | 1 - 9 files changed, 23 insertions(+), 25 deletions(-) diff --git a/doc/release-notes/1.31/powershell-agreement-consent.md b/doc/release-notes/1.31/powershell-agreement-consent.md index cdd0d606ef..4b5ff80094 100644 --- a/doc/release-notes/1.31/powershell-agreement-consent.md +++ b/doc/release-notes/1.31/powershell-agreement-consent.md @@ -15,7 +15,9 @@ is left out of the results. If you decline a package's agreements, the package i are shown in a warning. This behavior is deprecated: a future release will require the switches in non-interactive use, so update scripts and automation to pass them. * The `WinGetPackage` resource in Microsoft.WinGet.DSC has a new `AcceptAgreements` property, which - defaults to `true` and passes both switches. + defaults to `true` and passes both switches. The `true` default is also deprecated: a future + release will require `AcceptAgreements` to be set explicitly to accept agreements, so set it in + configurations that rely on it. Accepting a package's agreements also accepts the agreements of any dependencies that are installed with it. diff --git a/src/PowerShell/CommonFiles/PowerShellCmdlet.cs b/src/PowerShell/CommonFiles/PowerShellCmdlet.cs index e5e7a8e26f..d9dcba7cf8 100644 --- a/src/PowerShell/CommonFiles/PowerShellCmdlet.cs +++ b/src/PowerShell/CommonFiles/PowerShellCmdlet.cs @@ -551,23 +551,8 @@ internal bool ShouldProcess(string target) /// True if the host can prompt the user. internal bool IsInteractive() { - if (!Environment.UserInteractive || this.psCmdlet.Host?.UI == null) - { - return false; - } - - foreach (string arg in Environment.GetCommandLineArgs()) - { - // Matches -NonInteractive and its abbreviations, with either prefix character. - if (arg.Length >= 5 && - (arg[0] == '-' || arg[0] == '/') && - "noninteractive".StartsWith(arg.Substring(1), StringComparison.OrdinalIgnoreCase)) - { - return false; - } - } - - return true; + // A host started with -NonInteractive refuses to prompt, which ShouldContinue handles. + return Environment.UserInteractive && this.psCmdlet.Host?.UI != null; } private void Complete() diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs index 5d867c5af2..0e9d9b968a 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/PackageCommand.cs @@ -89,7 +89,7 @@ internal void ObtainPackageAgreementsConsent(CatalogPackage package, PackageVers return; } - string description = $"{package.Name} [{package.Id}] Version {versionInfo.Version}"; + string description = string.Format(Resources.PackageVersionDescription, package.Name, package.Id, versionInfo.Version); string? agreements; try diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs index 3551306f27..6e487aba80 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs @@ -129,7 +129,7 @@ public static bool IsMissingContract(Exception e) /// The cmdlet. /// The formatted agreements. /// The question to ask the user. - /// The caption of the prompt; Yes to All and No to All apply per caption. + /// The caption of the prompt. /// Whether the user accepted the agreements with a parameter. /// The name of the parameter that accepts the agreements. /// The decision. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs index 8d7c8e423b..172b460065 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs @@ -528,6 +528,15 @@ internal static string PackageAgreementsUnavailableExceptionMessage { } } + /// + /// Looks up a localized string similar to {0} [{1}] Version {2}. + /// + internal static string PackageVersionDescription { + get { + return ResourceManager.GetString("PackageVersionDescription", resourceCulture); + } + } + /// /// Looks up a localized string similar to Source agreements. /// @@ -583,7 +592,7 @@ internal static string SourceAgreementsUnavailable { } /// - /// Looks up a localized string similar to The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet accepts its agreements automatically. Error: {1}. + /// Looks up a localized string similar to The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet does not support source agreements. Error: {1}. /// internal static string SourceAgreementsUnavailableUnsupported { get { diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx index 615f5e2198..3f36e986c1 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.resx @@ -291,7 +291,7 @@ {Locked="{0}","{1}"} {0} is a placeholder replaced by the repository source name. {1} is a placeholder replaced by the error message. - The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet accepts its agreements automatically. Error: {1} + The agreements of the `{0}` source could not be read, so they were not shown. The source was used because the installed version of WinGet does not support source agreements. Error: {1} {Locked="{0}","{1}"} {0} is a placeholder replaced by the repository source name. {1} is a placeholder replaced by the error message. @@ -301,6 +301,10 @@ Agreements for {0} {Locked="{0}"} Followed by a list of license agreements. {0} is a placeholder replaced by the package name, identifier and version. + + {0} [{1}] Version {2} + {Locked="{0}","{1}","{2}"} Identifies a package version. {0} is a placeholder replaced by the package name. {1} is a placeholder replaced by the package identifier. {2} is a placeholder replaced by the package version. + The publisher requires that you view the above information and accept the agreements before installing. Do you agree to the terms? diff --git a/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 b/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 index d6d3639526..e8af225a37 100644 --- a/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 +++ b/src/PowerShell/Microsoft.WinGet.DSC/Microsoft.WinGet.DSC.psm1 @@ -498,7 +498,6 @@ class WinGetPackage } $result = [WinGetPackage]::new() - $result.AcceptAgreements = $this.AcceptAgreements $hashArgs = @{ Id = $this.Id diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 index 4a46f20c81..590c4903b3 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 @@ -374,7 +374,7 @@ Describe 'Package agreements' { $agreementsPackageId = 'AppInstallerTest.CatalogPackageMetadata' - # Matches the module's check for whether the user can be prompted. + # Approximates whether the host will prompt; a host started with -NonInteractive refuses to. $canPrompt = [Environment]::UserInteractive -and -not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^[-/]noni' }) } diff --git a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 index 97ef5daa11..e8a0915966 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 @@ -179,7 +179,6 @@ Describe 'WinGetPackage' { It 'Get WinGetPackage' { $result = InvokeWinGetDSC -Name WinGetPackage -Method Get -Property @{ Id = $testPackageId; Version = $testPackageVersion } $result.Ensure | Should -Be 'Absent' - $result.AcceptAgreements | Should -Be $true } It 'Test WinGetPackage' { From 01ad24fc3fe7b3e2036fdb32fa043d9c4e5d1864 Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Thu, 12 Nov 2026 15:44:55 -0800 Subject: [PATCH 3/9] source agreement PS tests --- .../tests/Microsoft.WinGet.Client.Tests.ps1 | 130 +++++++++++++++++- src/PowerShell/tests/RunTests.ps1 | 5 +- templates/jobs-powershell-module.yml | 4 +- 3 files changed, 134 insertions(+), 5 deletions(-) diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 index 590c4903b3..2568fe458d 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 @@ -10,7 +10,10 @@ [CmdletBinding()] param( # Whether to use production or developement targets. - [switch]$TargetProduction + [switch]$TargetProduction, + + # The root directory served by the localhost web server; source agreement tests are skipped without it. + [string]$StaticFileRootPath ) BeforeAll { @@ -414,6 +417,131 @@ Describe 'Package agreements' { } } +Describe 'Source agreements' { + + BeforeAll { + # The source serves only its information, so it cannot be searched. It is always targeted with -Source, + # and is removed after each test so that it does not break other searches. + $agreementsSourceName = 'TestPesterAgreementsRestSource' + $agreementsSourceUrl = "https://localhost:5001/TestKit/$agreementsSourceName" + $agreementsSourceDirectory = if ($StaticFileRootPath) { Join-Path $StaticFileRootPath $agreementsSourceName } else { $null } + + # Approximates whether the host will prompt; a host started with -NonInteractive refuses to. + $canPrompt = [Environment]::UserInteractive -and + -not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^[-/]noni' }) + + function WriteAgreementsSourceInformation([string]$agreementsIdentifier, [switch]$RequiresMarket) { + $data = [ordered]@{ + SourceIdentifier = $agreementsSourceName + ServerSupportedVersions = @('1.0.0') + SourceAgreements = [ordered]@{ + AgreementsIdentifier = $agreementsIdentifier + Agreements = @( + [ordered]@{ + AgreementLabel = 'Test Agreement' + Agreement = 'Test agreement text' + AgreementUrl = 'https://localhost:5001/TestKit/agreement' + } + ) + } + } + + if ($RequiresMarket) + { + $data.RequiredPackageMatchFields = @('Market') + } + + $null = New-Item -Path $agreementsSourceDirectory -ItemType Directory -Force + $information = ConvertTo-Json @{ Data = $data } -Depth 5 + [System.IO.File]::WriteAllText((Join-Path $agreementsSourceDirectory 'information'), $information) + } + + # Adding a source accepts its current agreements, so they are changed afterwards to make them unaccepted. + function AddAgreementsSourceWithUnacceptedAgreements([switch]$RequiresMarket) { + WriteAgreementsSourceInformation 'AgreementsV1' -RequiresMarket:$RequiresMarket + & $wingetExeName source add -n $agreementsSourceName -a $agreementsSourceUrl -t Microsoft.Rest --trust-level trusted --accept-source-agreements | Out-Null + $LASTEXITCODE | Should -Be 0 + WriteAgreementsSourceInformation 'AgreementsV2' -RequiresMarket:$RequiresMarket + } + + function FindInAgreementsSource([switch]$AcceptSourceAgreements) { + $warnings = [System.Collections.Generic.List[string]]::new() + $errorText = '' + + try + { + Find-WinGetPackage -Source $agreementsSourceName -Id 'AppInstallerTest.TestExampleInstaller' -AcceptSourceAgreements:$AcceptSourceAgreements -ErrorAction Stop 3>&1 | + Where-Object { $_ -is [System.Management.Automation.WarningRecord] } | + ForEach-Object { $warnings.Add($_.Message) } + } + catch + { + # Searching fails once the source is admitted, as it serves only its information. + $errorText = $_.ToString() + } + + [PSCustomObject]@{ + Warnings = $warnings -join [Environment]::NewLine + Error = $errorText + } + } + } + + It 'AcceptSourceAgreements shows the agreements and saves their acceptance' -Skip:(-not $StaticFileRootPath) { + AddAgreementsSourceWithUnacceptedAgreements -RequiresMarket + + $first = FindInAgreementsSource -AcceptSourceAgreements + $first.Warnings | Should -BeLike '*Test Agreement*' + $first.Warnings | Should -BeLike '*Test agreement text*' + $first.Warnings | Should -BeLike '*https://localhost:5001/TestKit/agreement*' + $first.Warnings | Should -BeLike '*geographic region*' + $first.Warnings | Should -BeLike '*-AcceptSourceAgreements*' + $first.Error | Should -Not -BeLike '*No sources are available*' + + $second = FindInAgreementsSource + $second.Warnings | Should -Not -BeLike '*Test Agreement*' + $second.Error | Should -Not -BeLike '*No sources are available*' + } + + It 'Without AcceptSourceAgreements in a non-interactive host accepts with a warning but does not save' -Skip:(-not $StaticFileRootPath) { + if ($canPrompt) + { + Set-ItResult -Skipped -Because 'the host can prompt the user' + return + } + + AddAgreementsSourceWithUnacceptedAgreements + + $first = FindInAgreementsSource + $first.Warnings | Should -BeLike '*Test Agreement*' + $first.Warnings | Should -BeLike '*deprecated*-AcceptSourceAgreements*' + $first.Error | Should -Not -BeLike '*No sources are available*' + + $second = FindInAgreementsSource + $second.Warnings | Should -BeLike '*Test Agreement*' + } + + It 'Unreadable agreements exclude the source' -Skip:(-not $StaticFileRootPath) { + AddAgreementsSourceWithUnacceptedAgreements + Remove-Item -Path (Join-Path $agreementsSourceDirectory 'information') -Force + + $result = FindInAgreementsSource -AcceptSourceAgreements + $result.Warnings | Should -BeLike "*$agreementsSourceName*could not be read*" + $result.Error | Should -BeLike '*No sources are available*' + } + + AfterEach { + if ($agreementsSourceDirectory) + { + & $wingetExeName source remove -n $agreementsSourceName | Out-Null + if (Test-Path $agreementsSourceDirectory) + { + Remove-Item -Path $agreementsSourceDirectory -Recurse -Force + } + } + } +} + Describe 'Install|Repair|Uninstall-WinGetPackage' { BeforeAll { diff --git a/src/PowerShell/tests/RunTests.ps1 b/src/PowerShell/tests/RunTests.ps1 index 4490d2acaf..e201612fc3 100644 --- a/src/PowerShell/tests/RunTests.ps1 +++ b/src/PowerShell/tests/RunTests.ps1 @@ -6,7 +6,8 @@ param( [string]$outputPath, [string]$packageLayoutPath, [switch]$TargetProduction, - [string]$ConfigurationTestDataPath + [string]$ConfigurationTestDataPath, + [string]$StaticFileRootPath ) # This updates pester not always necessary but worth noting @@ -56,7 +57,7 @@ $clientConfig = New-PesterConfiguration $clientConfig.TestResult.OutputFormat = "NUnitXML" $clientConfig.TestResult.OutputPath = "$outputPath\Tests-WinGetClient.XML" $clientConfig.TestResult.Enabled = $true -$clientConfig.Run.Container = New-PesterContainer -Path "$PSScriptRoot\Microsoft.WinGet.Client.Tests.ps1" -Data @{ TargetProduction = $TargetProduction } +$clientConfig.Run.Container = New-PesterContainer -Path "$PSScriptRoot\Microsoft.WinGet.Client.Tests.ps1" -Data @{ TargetProduction = $TargetProduction; StaticFileRootPath = $StaticFileRootPath } Invoke-Pester -Configuration $clientConfig diff --git a/templates/jobs-powershell-module.yml b/templates/jobs-powershell-module.yml index eeb2fa61ab..e2fecb62b1 100644 --- a/templates/jobs-powershell-module.yml +++ b/templates/jobs-powershell-module.yml @@ -88,11 +88,11 @@ jobs: - template: prime-windows-update.yml - - pwsh: .\RunTests.ps1 -testModulesPath $(Build.ArtifactStagingDirectory) -outputPath $(Pipeline.Workspace)\PesterTest -packageLayoutPath $(buildOutDir)\DevPackage + - pwsh: .\RunTests.ps1 -testModulesPath $(Build.ArtifactStagingDirectory) -outputPath $(Pipeline.Workspace)\PesterTest -packageLayoutPath $(buildOutDir)\DevPackage -StaticFileRootPath $(buildOutDir)\E2ETests\TestLocalIndex workingDirectory: $(wingetSourceRoot)\src\PowerShell\tests\ displayName: Run PowerShell 7 Tests - - powershell: .\RunTests.ps1 -testModulesPath $(Build.ArtifactStagingDirectory) -outputPath $(Pipeline.Workspace)\WPPesterTest + - powershell: .\RunTests.ps1 -testModulesPath $(Build.ArtifactStagingDirectory) -outputPath $(Pipeline.Workspace)\WPPesterTest -StaticFileRootPath $(buildOutDir)\E2ETests\TestLocalIndex workingDirectory: $(wingetSourceRoot)\src\PowerShell\tests\ displayName: Run Windows PowerShell Tests condition: succeededOrFailed() From 95e0ecd2ce632ea4048c957633de7241b8b8ab5c Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Thu, 12 Nov 2026 16:48:20 -0800 Subject: [PATCH 4/9] spelling --- .../Helpers/AgreementConsent.cs | 4 ++-- .../Properties/Resources.Designer.cs | 11 ++++++----- .../tests/Microsoft.WinGet.Client.Tests.ps1 | 4 ++-- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs index 6e487aba80..707c3919e7 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Helpers/AgreementConsent.cs @@ -29,7 +29,7 @@ internal static class AgreementConsent /// public const string AcceptPackageAgreementsParameter = "-AcceptPackageAgreements"; - private const int ENoInterface = unchecked((int)0x80004002); + private const int NoInterfaceHResult = unchecked((int)0x80004002); /// /// The result of obtaining consent. @@ -61,7 +61,7 @@ public enum Decision /// True if the server is older than the member. public static bool IsMissingContract(Exception e) { - return e is InvalidCastException || (e is COMException && e.HResult == ENoInterface); + return e is InvalidCastException || (e is COMException && e.HResult == NoInterfaceHResult); } /// diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs index 172b460065..802b1c4bba 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Properties/Resources.Designer.cs @@ -457,7 +457,7 @@ internal static string AgreementsAcceptedByParameter { } /// - /// Looks up a localized string similar to The agreements above were accepted because the user cannot be prompted. This beh[rest of string was truncated]. + /// Looks up a localized string similar to The agreements above were accepted because the user cannot be prompted. This behavior is deprecated; a future release will not accept agreements unless {0} is specified.. /// internal static string AgreementsAcceptedNonInteractive { get { @@ -466,7 +466,7 @@ internal static string AgreementsAcceptedNonInteractive { } /// - /// Looks up a localized string similar to The agreements above were accepted because the installed version of WinGet does [rest of string was truncated]. + /// Looks up a localized string similar to The agreements above were accepted because the installed version of WinGet does not support recording their acceptance. This behavior is deprecated; a future release will not accept agreements unless {0} is specified.. /// internal static string AgreementsAcceptedUnsupported { get { @@ -475,7 +475,7 @@ internal static string AgreementsAcceptedUnsupported { } /// - /// Looks up a localized string similar to No sources are available. The agreements of every source were either not accepte[rest of string was truncated]. + /// Looks up a localized string similar to No sources are available. The agreements of every source were either not accepted or could not be read.. /// internal static string NoSourcesAvailableExceptionMessage { get { @@ -502,7 +502,8 @@ internal static string PackageAgreementsCaption { } /// - /// Looks up a localized string similar to The publisher requires that you view the above information and accept the agreem[rest of string was truncated]. + /// Looks up a localized string similar to The publisher requires that you view the above information and accept the agreements before installing. + ///Do you agree to the terms?. /// internal static string PackageAgreementsPrompt { get { @@ -556,7 +557,7 @@ internal static string SourceAgreementsDeclined { } /// - /// Looks up a localized string similar to The source requires the current machine's 2-letter geographic region to be [rest of string was truncated]. + /// Looks up a localized string similar to The source requires the current machine's 2-letter geographic region to be sent to the backend service to function properly (ex. "US").. /// internal static string SourceAgreementsMarketMessage { get { diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 index 2568fe458d..b542a652dc 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 @@ -379,7 +379,7 @@ Describe 'Package agreements' { # Approximates whether the host will prompt; a host started with -NonInteractive refuses to. $canPrompt = [Environment]::UserInteractive -and - -not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^[-/]noni' }) + -not ([Environment]::GetCommandLineArgs() | Where-Object { $arg = $_.TrimStart('-', '/'); $arg.Length -ge 4 -and 'NonInteractive'.StartsWith($arg, [StringComparison]::OrdinalIgnoreCase) }) } It 'Install with AcceptPackageAgreements shows the agreements' { @@ -428,7 +428,7 @@ Describe 'Source agreements' { # Approximates whether the host will prompt; a host started with -NonInteractive refuses to. $canPrompt = [Environment]::UserInteractive -and - -not ([Environment]::GetCommandLineArgs() | Where-Object { $_ -match '^[-/]noni' }) + -not ([Environment]::GetCommandLineArgs() | Where-Object { $arg = $_.TrimStart('-', '/'); $arg.Length -ge 4 -and 'NonInteractive'.StartsWith($arg, [StringComparison]::OrdinalIgnoreCase) }) function WriteAgreementsSourceInformation([string]$agreementsIdentifier, [switch]$RequiresMarket) { $data = [ordered]@{ From ddc87551f78af048dc6967da065b96662468bf5c Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Fri, 13 Nov 2026 09:43:58 -0800 Subject: [PATCH 5/9] move function for style and make local builds more likely to catch it --- .../Microsoft.WinGet.Client.Cmdlets.csproj | 6 +--- .../Commands/RepairPackageCommand.cs | 30 +++++++++---------- .../Microsoft.WinGet.Client.Engine.csproj | 6 +--- ...rosoft.WinGet.Configuration.Cmdlets.csproj | 6 +--- ...crosoft.WinGet.Configuration.Engine.csproj | 6 +--- 5 files changed, 19 insertions(+), 35 deletions(-) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Microsoft.WinGet.Client.Cmdlets.csproj b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Microsoft.WinGet.Client.Cmdlets.csproj index ecc5539da9..9587cb4c45 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Microsoft.WinGet.Client.Cmdlets.csproj +++ b/src/PowerShell/Microsoft.WinGet.Client.Cmdlets/Microsoft.WinGet.Client.Cmdlets.csproj @@ -22,11 +22,7 @@ - - true - - - + true diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs index 8fb012c14e..3b66649b4c 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs @@ -120,6 +120,21 @@ public void Repair( } } + private static PackageVersionInfo? GetRepairVersionInfo(CatalogPackage package) + { + // Repair uses the available version matching the installed one, when there is one. + string? installedVersion = package.InstalledVersion?.Version; + for (int i = 0; i < package.AvailableVersions.Count; ++i) + { + if (package.AvailableVersions[i].Version == installedVersion) + { + return package.GetPackageVersionInfo(package.AvailableVersions[i]); + } + } + + return package.DefaultInstallVersion; + } + private RepairOptions GetRepairOptions( PackageVersionId? version, PackageRepairMode repairMode) @@ -146,21 +161,6 @@ private RepairOptions GetRepairOptions( return options; } - private static PackageVersionInfo? GetRepairVersionInfo(CatalogPackage package) - { - // Repair uses the available version matching the installed one, when there is one. - string? installedVersion = package.InstalledVersion?.Version; - for (int i = 0; i < package.AvailableVersions.Count; ++i) - { - if (package.AvailableVersions[i].Version == installedVersion) - { - return package.GetPackageVersionInfo(package.AvailableVersions[i]); - } - } - - return package.DefaultInstallVersion; - } - private async Task RepairPackageAsync( CatalogPackage catalogPackage, RepairOptions repairOptions) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Microsoft.WinGet.Client.Engine.csproj b/src/PowerShell/Microsoft.WinGet.Client.Engine/Microsoft.WinGet.Client.Engine.csproj index 86568e2494..c5e9bbd61f 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Microsoft.WinGet.Client.Engine.csproj +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Microsoft.WinGet.Client.Engine.csproj @@ -76,11 +76,7 @@ 1591 - - true - - - + true diff --git a/src/PowerShell/Microsoft.WinGet.Configuration.Cmdlets/Microsoft.WinGet.Configuration.Cmdlets.csproj b/src/PowerShell/Microsoft.WinGet.Configuration.Cmdlets/Microsoft.WinGet.Configuration.Cmdlets.csproj index 13593ed282..a92f3e6d7b 100644 --- a/src/PowerShell/Microsoft.WinGet.Configuration.Cmdlets/Microsoft.WinGet.Configuration.Cmdlets.csproj +++ b/src/PowerShell/Microsoft.WinGet.Configuration.Cmdlets/Microsoft.WinGet.Configuration.Cmdlets.csproj @@ -13,11 +13,7 @@ Debug;Release;ReleaseStatic - - true - - - + true diff --git a/src/PowerShell/Microsoft.WinGet.Configuration.Engine/Microsoft.WinGet.Configuration.Engine.csproj b/src/PowerShell/Microsoft.WinGet.Configuration.Engine/Microsoft.WinGet.Configuration.Engine.csproj index 2278d38060..5fd550ba4c 100644 --- a/src/PowerShell/Microsoft.WinGet.Configuration.Engine/Microsoft.WinGet.Configuration.Engine.csproj +++ b/src/PowerShell/Microsoft.WinGet.Configuration.Engine/Microsoft.WinGet.Configuration.Engine.csproj @@ -12,11 +12,7 @@ Debug;Release;ReleaseStatic - - true - - - + true From e757ecd5f65fc205b7412fdb7edf6190a488b68b Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Fri, 13 Nov 2026 11:13:38 -0800 Subject: [PATCH 6/9] PS test fix --- .../TestExeInstaller_PackageAgreements.yaml | 30 +++++++++++++++++++ .../tests/Microsoft.WinGet.Client.Tests.ps1 | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 src/AppInstallerCLIE2ETests/TestData/Manifests/TestExeInstaller_PackageAgreements.yaml diff --git a/src/AppInstallerCLIE2ETests/TestData/Manifests/TestExeInstaller_PackageAgreements.yaml b/src/AppInstallerCLIE2ETests/TestData/Manifests/TestExeInstaller_PackageAgreements.yaml new file mode 100644 index 0000000000..083a184d79 --- /dev/null +++ b/src/AppInstallerCLIE2ETests/TestData/Manifests/TestExeInstaller_PackageAgreements.yaml @@ -0,0 +1,30 @@ +# Manifest for verifying package agreement consent. Uses a unique product code so that it does not collide with other test packages. +# yaml-language-server: $schema=https://aka.ms/winget-manifest.singleton.1.5.0.schema.json + +PackageIdentifier: AppInstallerTest.PackageAgreements +PackageVersion: 1.0.0.0 +PackageName: TestPackageAgreements +PackageLocale: en-US +Publisher: AppInstallerTest +License: Test +ShortDescription: Test package with agreements +Installers: + - Architecture: x86 + InstallerUrl: https://localhost:5001/TestKit/AppInstallerTestExeInstaller/AppInstallerTestExeInstaller.exe + InstallerType: exe + InstallerSha256: + ProductCode: '{3B911E81-F86F-41DD-8FEA-C9B43B281FB9}' + InstallerSwitches: + Custom: '/ProductID {3B911E81-F86F-41DD-8FEA-C9B43B281FB9} /DisplayName TestPackageAgreements' + SilentWithProgress: /exeswp + Silent: /exesilent + Interactive: /exeinteractive + Language: /exeenus + Log: /LogFile + InstallLocation: /InstallDir +Agreements: + - AgreementLabel: testAgreementLabel + Agreement: testAgreementText + AgreementUrl: https://testAgreementUrl.net +ManifestType: singleton +ManifestVersion: 1.5.0 diff --git a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 index b542a652dc..7e17079408 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.Client.Tests.ps1 @@ -375,7 +375,7 @@ Describe 'Package agreements' { BeforeAll { AddTestSource - $agreementsPackageId = 'AppInstallerTest.CatalogPackageMetadata' + $agreementsPackageId = 'AppInstallerTest.PackageAgreements' # Approximates whether the host will prompt; a host started with -NonInteractive refuses to. $canPrompt = [Environment]::UserInteractive -and From ac66499a080f2f80d581d0cbf1dd29d5b91c314c Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Fri, 13 Nov 2026 15:48:10 -0800 Subject: [PATCH 7/9] consistent repair version selection --- .../Workflows/RepairFlow.cpp | 52 +++----------- .../PackageVersionSelection.cpp | 68 +++++++++++++++++++ .../Public/winget/PackageVersionSelection.h | 17 +++++ .../CatalogPackage.cpp | 14 ++++ .../CatalogPackage.h | 2 + .../PackageManager.idl | 9 +++ .../Repair-WinGetPackage.md | 2 +- .../Commands/RepairPackageCommand.cs | 37 ++++++---- 8 files changed, 144 insertions(+), 57 deletions(-) diff --git a/src/AppInstallerCLICore/Workflows/RepairFlow.cpp b/src/AppInstallerCLICore/Workflows/RepairFlow.cpp index 404c0e3c79..56d12350f6 100644 --- a/src/AppInstallerCLICore/Workflows/RepairFlow.cpp +++ b/src/AppInstallerCLICore/Workflows/RepairFlow.cpp @@ -237,29 +237,13 @@ namespace AppInstaller::CLI::Workflow bool IsInstallerMappingRequired(Execution::Context& context) { - InstallerTypeEnum installerTypeEnum = GetInstalledType(context); - - switch (installerTypeEnum) + std::shared_ptr package; + if (context.Contains(Execution::Data::Package)) { - case InstallerTypeEnum::Msi: - return false; - case InstallerTypeEnum::Msix: - // For MSIX packages that are from the Microsoft Store, selecting an installer is required. - if (context.Contains(Execution::Data::Package)) - { - auto availablePackages = context.Get()->GetAvailable(); - - if (availablePackages.size() == 1 && availablePackages[0]->GetSource() == WellKnownSource::MicrosoftStore) - { - return true; - } - } - - // For MSIX packages that are not from the Microsoft Store, selecting an installer is not required. - return false; - default: - return true; + package = context.Get(); } + + return IsAvailableVersionRequiredForRepair(package, context.Get()); } void HandleModifyOrUninstallerRepair(Execution::Context& context, RepairBehaviorEnum repairBehavior) @@ -471,33 +455,17 @@ namespace AppInstaller::CLI::Workflow } const auto& installedPackage = context.Get(); + std::string_view targetVersion = context.Args.Contains(Execution::Args::Type::TargetVersion) ? context.Args.GetArg(Execution::Args::Type::TargetVersion) : std::string_view{}; + std::string_view channel = context.Args.GetArg(Execution::Args::Type::Channel); - Utility::Version installedVersion = Utility::Version(installedPackage->GetProperty(PackageVersionProperty::Version)); - if (installedVersion.IsUnknown()) + auto key = GetRepairVersionKey(context.Get(), installedPackage, targetVersion, channel); + if (!key) { context.Reporter.Error() << Resource::String::NoApplicableInstallers << std::endl; AICLI_TERMINATE_CONTEXT(APPINSTALLER_CLI_ERROR_NO_APPLICABLE_INSTALLER); } - std::string_view requestedVersion = context.Args.Contains(Execution::Args::Type::TargetVersion) ? context.Args.GetArg(Execution::Args::Type::TargetVersion) : installedVersion.ToString(); - // If it's Store source with only one version unknown, use the unknown version for available version mapping. - const auto& package = context.Get(); - auto packageVersions = GetAvailableVersionsForInstalledVersion(package, installedPackage); - auto versionKeys = packageVersions->GetVersionKeys(); - if (versionKeys.size() == 1) - { - auto packageVersion = packageVersions->GetVersion(versionKeys.at(0)); - if (packageVersion->GetSource().IsWellKnownSource(WellKnownSource::MicrosoftStore) && - Utility::Version{ packageVersion->GetProperty(PackageVersionProperty::Version) }.IsUnknown()) - { - requestedVersion = ""; - } - } - - context << - GetManifestWithVersionFromPackage( - requestedVersion, - context.Args.GetArg(Execution::Args::Type::Channel), false); + context << GetManifestWithVersionFromPackage(key->Version, key->Channel, false); } void SelectApplicableInstallerIfNecessary(Execution::Context& context) diff --git a/src/AppInstallerRepositoryCore/PackageVersionSelection.cpp b/src/AppInstallerRepositoryCore/PackageVersionSelection.cpp index 1546e9a52c..665b045e80 100644 --- a/src/AppInstallerRepositoryCore/PackageVersionSelection.cpp +++ b/src/AppInstallerRepositoryCore/PackageVersionSelection.cpp @@ -305,4 +305,72 @@ namespace AppInstaller::Repository return std::nullopt; } + + bool IsAvailableVersionRequiredForRepair(const std::shared_ptr& composite, const std::shared_ptr& installedVersion) + { + std::string installedType = installedVersion->GetMetadata()[PackageVersionMetadata::InstalledType]; + + switch (Manifest::ConvertToInstallerTypeEnum(installedType)) + { + case Manifest::InstallerTypeEnum::Msi: + return false; + case Manifest::InstallerTypeEnum::Msix: + if (composite) + { + auto availablePackages = composite->GetAvailable(); + return availablePackages.size() == 1 && availablePackages[0]->GetSource().IsWellKnownSource(WellKnownSource::MicrosoftStore); + } + + return false; + default: + return true; + } + } + + std::optional GetRepairVersionKey( + const std::shared_ptr& composite, + const std::shared_ptr& installedVersion, + std::string_view requestedVersion, + std::string_view requestedChannel) + { + Utility::Version installed{ installedVersion->GetProperty(PackageVersionProperty::Version) }; + if (installed.IsUnknown()) + { + return std::nullopt; + } + + std::string version{ requestedVersion.empty() ? std::string_view{ installed.ToString() } : requestedVersion }; + + // If it's Store source with only one version unknown, use the unknown version for available version mapping. + auto packageVersions = GetAvailableVersionsForInstalledVersion(composite, installedVersion); + auto versionKeys = packageVersions->GetVersionKeys(); + if (versionKeys.size() == 1) + { + auto packageVersion = packageVersions->GetVersion(versionKeys.at(0)); + if (packageVersion && packageVersion->GetSource().IsWellKnownSource(WellKnownSource::MicrosoftStore) && + Utility::Version{ packageVersion->GetProperty(PackageVersionProperty::Version) }.IsUnknown()) + { + version.clear(); + } + } + + return PackageVersionKey{ "", version, std::string{ requestedChannel } }; + } + + std::shared_ptr GetRepairVersion(const std::shared_ptr& composite) + { + auto installedVersion = GetInstalledVersion(composite); + if (!installedVersion || !IsAvailableVersionRequiredForRepair(composite, installedVersion)) + { + return {}; + } + + auto key = GetRepairVersionKey(composite, installedVersion); + if (!key) + { + return {}; + } + + return GetAvailableVersionsForInstalledVersion(composite, installedVersion)->GetVersion(key.value()); + } } diff --git a/src/AppInstallerRepositoryCore/Public/winget/PackageVersionSelection.h b/src/AppInstallerRepositoryCore/Public/winget/PackageVersionSelection.h index eb1cd0b104..a3c22af4e1 100644 --- a/src/AppInstallerRepositoryCore/Public/winget/PackageVersionSelection.h +++ b/src/AppInstallerRepositoryCore/Public/winget/PackageVersionSelection.h @@ -41,4 +41,21 @@ namespace AppInstaller::Repository // Gets the source priority for a given composite package, taking into account installed relationships. std::optional GetSourcePriority(const std::shared_ptr& composite); + + // Determines whether repairing the installed version uses an available version of the package. + // MSI and MSIX packages not from the Microsoft Store are repaired by the platform without one. + // The composite may be null, such as when repairing from a manifest. + bool IsAvailableVersionRequiredForRepair(const std::shared_ptr& composite, const std::shared_ptr& installedVersion); + + // Gets the key of the available version used to repair the installed version. + // The requested version, if not empty, is used in place of the installed version. + // Returns nullopt if the installed version is unknown, as no available version can be mapped to it. + std::optional GetRepairVersionKey( + const std::shared_ptr& composite, + const std::shared_ptr& installedVersion, + std::string_view requestedVersion = {}, + std::string_view requestedChannel = {}); + + // Gets the available version used to repair the installed version of the package, or null if there isn't one. + std::shared_ptr GetRepairVersion(const std::shared_ptr& composite); } diff --git a/src/Microsoft.Management.Deployment/CatalogPackage.cpp b/src/Microsoft.Management.Deployment/CatalogPackage.cpp index b1477c5a5d..e583f240f7 100644 --- a/src/Microsoft.Management.Deployment/CatalogPackage.cpp +++ b/src/Microsoft.Management.Deployment/CatalogPackage.cpp @@ -181,4 +181,18 @@ namespace winrt::Microsoft::Management::Deployment::implementation { return AppInstaller::Repository::GetSourcePriority(m_package); } + + Microsoft::Management::Deployment::PackageVersionInfo CatalogPackage::RepairVersion() + { + std::shared_ptr<::AppInstaller::Repository::IPackageVersion> repairVersion = ::AppInstaller::Repository::GetRepairVersion(m_package); + if (!repairVersion) + { + return nullptr; + } + + auto packageVersionInfoImpl = winrt::make_self>(); + packageVersionInfoImpl->Initialize(std::move(repairVersion)); + return *packageVersionInfoImpl; + } } diff --git a/src/Microsoft.Management.Deployment/CatalogPackage.h b/src/Microsoft.Management.Deployment/CatalogPackage.h index 24f1e4dccb..0fe7148178 100644 --- a/src/Microsoft.Management.Deployment/CatalogPackage.h +++ b/src/Microsoft.Management.Deployment/CatalogPackage.h @@ -32,6 +32,8 @@ namespace winrt::Microsoft::Management::Deployment::implementation winrt::Microsoft::Management::Deployment::CheckInstalledStatusResult CheckInstalledStatus(); Windows::Foundation::IReference CatalogPriority(); + // Contract 31 + winrt::Microsoft::Management::Deployment::PackageVersionInfo RepairVersion(); #if !defined(INCLUDE_ONLY_INTERFACE_METHODS) private: diff --git a/src/Microsoft.Management.Deployment/PackageManager.idl b/src/Microsoft.Management.Deployment/PackageManager.idl index 6191a0a8f1..5c5d131661 100644 --- a/src/Microsoft.Management.Deployment/PackageManager.idl +++ b/src/Microsoft.Management.Deployment/PackageManager.idl @@ -652,6 +652,15 @@ namespace Microsoft.Management.Deployment /// May be null if the package refers only to an installed item. Windows.Foundation.IReference CatalogPriority { get; }; } + + [contract(Microsoft.Management.Deployment.WindowsPackageManagerContract, 31)] + { + /// Gets the available version whose manifest is used when repairing the installed version, such as + /// to present its agreements before setting RepairOptions.AcceptPackageAgreements. + /// Null if the package is not installed, the installed version has no matching available version, + /// or the repair does not use an available version (such as for MSI and non-Store MSIX packages). + PackageVersionInfo RepairVersion { get; }; + } } /// IMPLEMENTATION NOTE: CompositeSearchBehavior from winget/RepositorySource.h diff --git a/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md b/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md index 9cac0e68af..485873d3a6 100644 --- a/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md +++ b/src/PowerShell/Help/Microsoft.WinGet.Client/Repair-WinGetPackage.md @@ -67,7 +67,7 @@ This example shows how to repair a package using the package name. ### -AcceptPackageAgreements -Accepts the agreements of the package that is selected. The agreements are shown as a warning. +Accepts the agreements of the version of the package that the repair uses, which matches the installed version. The agreements are shown as a warning. Without this parameter, an interactive session asks you to accept or decline them; declining stops the operation for that package. In a non-interactive session, the agreements are currently accepted and shown as a warning. A future release will require this parameter instead. diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs index 3b66649b4c..5c62192ed3 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/RepairPackageCommand.cs @@ -98,8 +98,9 @@ public void Repair( PSEnumHelpers.ToPackageFieldMatchOption(psPackageFieldMatchOption), async (package, version) => { - this.ObtainPackageAgreementsConsent(package, version != null ? package.GetPackageVersionInfo(version) : GetRepairVersionInfo(package)); - var repairOptions = this.GetRepairOptions(version, PSEnumHelpers.ToPackageRepairMode(psPackageRepairMode)); + // Repair ignores the requested version, so consent is obtained for the version the repair uses. + bool acceptPackageAgreements = this.ObtainRepairAgreementsConsent(package); + var repairOptions = this.GetRepairOptions(version, PSEnumHelpers.ToPackageRepairMode(psPackageRepairMode), acceptPackageAgreements); return await this.RepairPackageAsync(package, repairOptions); })); @@ -120,24 +121,33 @@ public void Repair( } } - private static PackageVersionInfo? GetRepairVersionInfo(CatalogPackage package) + /// + /// Obtains consent to the agreements of the version that the repair uses. + /// + /// The package. + /// Whether the repair may accept the package agreements. + private bool ObtainRepairAgreementsConsent(CatalogPackage package) { - // Repair uses the available version matching the installed one, when there is one. - string? installedVersion = package.InstalledVersion?.Version; - for (int i = 0; i < package.AvailableVersions.Count; ++i) + PackageVersionInfo? repairVersion; + + try { - if (package.AvailableVersions[i].Version == installedVersion) - { - return package.GetPackageVersionInfo(package.AvailableVersions[i]); - } + repairVersion = package.RepairVersion; + } + catch (Exception e) when (AgreementConsent.IsMissingContract(e)) + { + // Older servers cannot identify the version, so the repair fails if it has agreements unless they were accepted by parameter. + return this.AcceptPackageAgreements; } - return package.DefaultInstallVersion; + this.ObtainPackageAgreementsConsent(package, repairVersion); + return true; } private RepairOptions GetRepairOptions( PackageVersionId? version, - PackageRepairMode repairMode) + PackageRepairMode repairMode, + bool acceptPackageAgreements) { var options = ManagementDeploymentFactory.Instance.CreateRepairOptions(); options.AllowHashMismatch = this.AllowHashMismatch; @@ -150,8 +160,7 @@ private RepairOptions GetRepairOptions( options.PackageRepairMode = repairMode; - // Consent to the package agreements is obtained before the options are created. - options.AcceptPackageAgreements = true; + options.AcceptPackageAgreements = acceptPackageAgreements; if (version != null) { From 0d20aacbe0304b914c630817ba6a87809da7d083 Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Fri, 13 Nov 2026 15:51:21 -0800 Subject: [PATCH 8/9] allow local searches --- .../Commands/Common/FinderCommand.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs index df808b4abc..77f311aada 100644 --- a/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs +++ b/src/PowerShell/Microsoft.WinGet.Client.Engine/Commands/Common/FinderCommand.cs @@ -194,8 +194,9 @@ private PackageCatalogReference GetPackageCatalogReference(CompositeSearchBehavi } } - // Searches of installed packages can continue without any remote source. - if (anyExcluded && options.Catalogs.Count == 0 && behavior != CompositeSearchBehavior.LocalCatalogs) + // Searches that include installed packages can continue without any remote source. + if (anyExcluded && options.Catalogs.Count == 0 && + (behavior == CompositeSearchBehavior.RemotePackagesFromRemoteCatalogs || behavior == CompositeSearchBehavior.RemotePackagesFromAllCatalogs)) { throw new NoSourcesAvailableException(); } From c028367c826014b49db977feb0a80bb06b1ece9e Mon Sep 17 00:00:00 2001 From: JohnMcPMS Date: Fri, 13 Nov 2026 15:52:18 -0800 Subject: [PATCH 9/9] use correct package --- src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 index e8a0915966..da2ac6de25 100644 --- a/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 +++ b/src/PowerShell/tests/Microsoft.WinGet.DSC.Tests.ps1 @@ -171,7 +171,7 @@ Describe 'WinGetPackage' { $testPackageId = 'AppInstallerTest.TestExeInstaller' $testPackageVersion = '1.0.0.0' - $agreementsPackageId = 'AppInstallerTest.CatalogPackageMetadata' + $agreementsPackageId = 'AppInstallerTest.PackageAgreements' InvokeWinGetDSC -Name WinGetSource -Method Set -Property @{ Name = $testSourceName; Argument = $testSourceArg; Type = $testSourceType; TrustLevel = 'Trusted'; Explicit = $false } }