Skip to content

Commit

Permalink
cmdlet related
Browse files Browse the repository at this point in the history
  • Loading branch information
isra-fel committed Mar 24, 2022
1 parent e54b3cb commit 3f59938
Show file tree
Hide file tree
Showing 10 changed files with 1,033 additions and 2 deletions.
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.Common.Authentication.Config.PSConfig</Name>
<ViewSelectedBy>
<TypeName>Microsoft.Azure.Commands.Common.Authentication.Config.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
110 changes: 110 additions & 0 deletions src/Accounts/Accounts/Config/ClearConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// ----------------------------------------------------------------------------------
//
// 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.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))]
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 => (bool)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 Microsoft.WindowsAzure.Commands.Common.CustomAttributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Common.Authentication.Config
{
[CmdletPreview("The cmdlet group \"AzConfig\" is in preview. Feedback is welcome: https://github.com/Azure/azure-powershell/discussions")]
public abstract class ConfigCommandBase : AzureRMCmdlet
{
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)
{
_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);
}
}
}
}
66 changes: 66 additions & 0 deletions src/Accounts/Accounts/Config/GetConfigCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// ----------------------------------------------------------------------------------
//
// 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.ResourceManager.Common;
using Microsoft.Azure.PowerShell.Common.Config;
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(VerbsCommon.Get, AzureRMConstants.AzureRMPrefix + "Config")]
[OutputType(typeof(PSConfig))]
public class GetConfigCommand : ConfigCommandBase, IDynamicParameters
{
public GetConfigCommand() : base()
{
}

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

public override void ExecuteCmdlet()
{
ConfigFilter filter = CreateConfigFilter();

IEnumerable<ConfigData> configs = ConfigManager.ListConfigs(filter);
WriteObject(configs.Select(x => new PSConfig(x)), true);
}

private ConfigFilter CreateConfigFilter()
{
ConfigFilter filter = new ConfigFilter() { AppliesTo = AppliesTo };
IEnumerable<string> configKeysFromInput = GetConfigsSpecifiedByUser().Where(x => (bool)x.Value).Select(x => x.Key);
if (configKeysFromInput.Any())
{
filter.Keys = configKeysFromInput;
}

return filter;
}
}
}
Loading

0 comments on commit 3f59938

Please sign in to comment.