Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Config framework implementation #17545

Merged
merged 10 commits into from
May 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -273,5 +273,33 @@ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-----------------------------------------------------------------------------

***************

The software includes Microsoft.Extensions.Configuration. The MIT License set out below is provided for informational purposes only. It is not the license that governs any part of the software.

The MIT License (MIT)

Copyright (c) .NET Foundation and Contributors

All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

-------------END OF THIRD PARTY NOTICE----------------------------------------

3 changes: 2 additions & 1 deletion src/Accounts/Accounts.Test/Mocks/MockDataStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,8 @@ public Stream OpenForExclusiveWrite(string path)
() =>
{
writeLocks[path] = false;
virtualStore[path] = Encoding.UTF8.GetString(buffer);
// trim \0 otherwise json fails to parse
virtualStore[path] = Encoding.UTF8.GetString(buffer).TrimEnd('\0');
}
);
}
Expand Down
57 changes: 56 additions & 1 deletion src/Accounts/Accounts/Accounts.format.ps1xml
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,61 @@
</ListEntries>
</ListControl>
</View>

<View>
<Name>Microsoft.Azure.Commands.Profile.Models.PSConfig</Name>
<ViewSelectedBy>
<TypeName>Microsoft.Azure.Commands.Profile.Models.PSConfig</TypeName>
</ViewSelectedBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Alignment>Left</Alignment>
<Label>Key</Label>
</TableColumnHeader>
<TableColumnHeader>
<Alignment>Left</Alignment>
<Label>Value</Label>
</TableColumnHeader>
<TableColumnHeader>
<Alignment>Left</Alignment>
<Label>Applies To</Label>
</TableColumnHeader>
<TableColumnHeader>
<Alignment>Left</Alignment>
<Label>Scope</Label>
</TableColumnHeader>
<TableColumnHeader>
<Alignment>Left</Alignment>
<Label>Help Message</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<Alignment>Left</Alignment>
<PropertyName>Key</PropertyName>
</TableColumnItem>
<TableColumnItem>
<Alignment>Left</Alignment>
<PropertyName>Value</PropertyName>
</TableColumnItem>
<TableColumnItem>
<Alignment>Left</Alignment>
<PropertyName>AppliesTo</PropertyName>
</TableColumnItem>
<TableColumnItem>
<Alignment>Left</Alignment>
<PropertyName>Scope</PropertyName>
</TableColumnItem>
<TableColumnItem>
<Alignment>Left</Alignment>
<PropertyName>HelpMessage</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Az.Accounts.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ CmdletsToExport = 'Disable-AzDataCollection', 'Disable-AzContextAutosave',
'Set-AzDefault', 'Get-AzDefault', 'Clear-AzDefault',
'Register-AzModule', 'Enable-AzureRmAlias', 'Disable-AzureRmAlias',
'Uninstall-AzureRm', 'Invoke-AzRestMethod', 'Get-AzAccessToken',
'Open-AzSurveyLink'
'Open-AzSurveyLink', 'Get-AzConfig', 'Update-AzConfig', 'Clear-AzConfig'

# Variables to export from this module
# VariablesToExport = @()
Expand Down
6 changes: 5 additions & 1 deletion src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
-->

## Upcoming Release
* Added a preview feature allowing user to control the configurations of Azure PowerShell by using the following cmdlets:
- `Get-AzConfig`
- `Update-AzConfig`
- `Clear-AzConfig`
* Upgraded System.Reflection.DispatchProxy on Windows PowerShell [#17856]

## Version 2.7.6
Expand Down Expand Up @@ -215,7 +219,7 @@
* Updated Add-AzEnvironment and Set-AzEnvironment to accept parameters AzureAttestationServiceEndpointResourceId and AzureAttestationServiceEndpointSuffix

## Version 1.6.6
* Add client-side telemetry info for Az 4.0 preview
* Add client-side telemetry info for Az 4.0 `preview`

## Version 1.6.5
* Update references in .psd1 to use relative path
Expand Down
114 changes: 114 additions & 0 deletions src/Accounts/Accounts/Config/ClearConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.PowerShell.Common.Config;
using Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[Cmdlet("Clear", "AzConfig", SupportsShouldProcess = true)]
[OutputType(typeof(bool))]
[CmdletPreview(PreviewMessage)]
public class ClearConfigCommand : ConfigCommandBase, IDynamicParameters
{
private const string ClearByKey = "ClearByKey";
private const string ClearAll = "ClearAll";

private const string ProcessMessage = "Clear the configs that apply to \"{0}\" by the following keys: {1}.";

private string ContinueMessage => $"Clear all the configs that apply to \"{AppliesTo}\" in scope {Scope}?";
private string ProcessTarget => $"Configs in scope {Scope}";

[Parameter(ParameterSetName = ClearAll, Mandatory = true, HelpMessage = "Clear all configs.")]
public SwitchParameter All { get; set; }

[Parameter(ParameterSetName = ClearAll, HelpMessage = "Do not ask for confirmation when clearing all configs.")]
public SwitchParameter Force { get; set; }

[Parameter(HelpMessage = "Returns true if cmdlet executes correctly.")]
public SwitchParameter PassThru { get; set; }

public new object GetDynamicParameters()
{
return GetDynamicParameters((ConfigDefinition config) =>
new RuntimeDefinedParameter(
config.Key,
typeof(SwitchParameter),
new Collection<Attribute>() {
new ParameterAttribute {
ParameterSetName = ClearByKey,
HelpMessage = config.HelpMessage
}
}));
}

public override void ExecuteCmdlet()
{
switch (ParameterSetName)
{
case ClearByKey:
ClearConfigByKey();
break;
case ClearAll:
ClearAllConfigs();
break;
}
if (PassThru)
{
WriteObject(true);
}
}

private void ClearConfigByKey()
{
IEnumerable<string> configKeysFromInput = GetConfigsSpecifiedByUser()
.Where(x => (SwitchParameter)x.Value)
.Select(x => x.Key);
if (!configKeysFromInput.Any())
{
WriteWarning($"Please specify the key(s) of the configs to clear. Run `help {MyInvocation.MyCommand.Name}` for more information.");
return;
}
base.ConfirmAction(
string.Format(ProcessMessage, AppliesTo, string.Join(", ", configKeysFromInput)),
ProcessTarget,
() => configKeysFromInput.ForEach(ClearConfigByKey));
}

private void ClearConfigByKey(string key)
{
ConfigManager.ClearConfig(new ClearConfigOptions(key, Scope)
{
AppliesTo = AppliesTo
});
}

private void ClearAllConfigs()
{
ConfirmAction(Force, ContinueMessage, ContinueMessage, ProcessTarget, () =>
{
ConfigManager.ClearConfig(new ClearConfigOptions(null, Scope)
{
AppliesTo = AppliesTo
});
});
}
}
}
98 changes: 98 additions & 0 deletions src/Accounts/Accounts/Config/ConfigCommandBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Exceptions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
public abstract class ConfigCommandBase : AzureRMCmdlet
{
protected const string PreviewMessage = "The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://aka.ms/azpsissue";

private readonly RuntimeDefinedParameterDictionary _dynamicParameters = new RuntimeDefinedParameterDictionary();

protected IConfigManager ConfigManager { get; }
protected IEnumerable<ConfigDefinition> ConfigDefinitions
{
get
{
if (_configDefinitions == null)
{
_configDefinitions = ConfigManager.ListConfigDefinitions();
}
return _configDefinitions;
}
}
private IEnumerable<ConfigDefinition> _configDefinitions;

public ConfigCommandBase() : base()
{
if (!AzureSession.Instance.TryGetComponent<IConfigManager>(nameof(IConfigManager), out var configManager))
{
throw new AzPSApplicationException($"Unexpected error: {nameof(IConfigManager)} has not been registered to the current session.");
}
ConfigManager = configManager;
}

[Parameter(HelpMessage = "Specifies what part of Azure PowerShell the config applies to. Possible values are:\n- \"" + ConfigFilter.GlobalAppliesTo + "\": the config applies to all modules and cmdlets of Azure PowerShell. \n- Module name: the config applies to a certain module of Azure PowerShell. For example, \"Az.Storage\".\n- Cmdlet name: the config applies to a certain cmdlet of Azure PowerShell. For example, \"Get-AzKeyVault\".\nIf not specified, when getting configs, output will be all of the above; when updating, it defaults to \"" + ConfigFilter.GlobalAppliesTo + "\"; when clearing, configs applying to any targets are cleared.")]
[ValidateNotNullOrEmpty]
public string AppliesTo { get; set; }

[Parameter(HelpMessage = "Determines the scope of config changes, for example, whether changes apply only to the current process, or to all sessions started by this user. By default it is CurrentUser.")]
public ConfigScope Scope { get; set; } = ConfigScope.CurrentUser;

protected override void BeginProcessing()
{
base.BeginProcessing();
ValidateParameters();
}

protected virtual void ValidateParameters()
{
if (!AppliesToHelper.TryParseAppliesTo(AppliesTo, out _))
{
throw new AzPSArgumentException($"{nameof(AppliesTo)} must be a valid module name, a cmdlet name, or \"{ConfigFilter.GlobalAppliesTo}\"", nameof(AppliesTo));
}
}

protected object GetDynamicParameters(Func<ConfigDefinition, RuntimeDefinedParameter> mapConfigToParameter)
{
_dynamicParameters.Clear();
foreach (var config in ConfigDefinitions)
isra-fel marked this conversation as resolved.
Show resolved Hide resolved
{
_dynamicParameters.Add(config.Key, mapConfigToParameter(config));
}
return _dynamicParameters;
}

/// <summary>
/// Gets the dynamic parameters and their values if specified.
/// </summary>
/// <returns></returns>
protected IEnumerable<(string Key, object Value)> GetConfigsSpecifiedByUser()
{
var configs = new Dictionary<string, object>();
foreach (var param in _dynamicParameters.Values.Where(p => p.IsSet))
{
yield return (param.Name, param.Value);
}
}
}
}
Loading