|
| 1 | +// ---------------------------------------------------------------------------------- |
| 2 | +// |
| 3 | +// Copyright Microsoft Corporation |
| 4 | +// Licensed under the Apache License, Version 2.0 (the 'License'); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an 'AS IS' BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | +// ---------------------------------------------------------------------------------- |
| 14 | + |
| 15 | +using Microsoft.Azure.Commands.Common.Authentication; |
| 16 | +using Microsoft.Azure.Commands.Common.Authentication.Abstractions; |
| 17 | +using System; |
| 18 | +using System.Collections.Generic; |
| 19 | +using System.IO; |
| 20 | +using System.Linq; |
| 21 | +using System.Management.Automation; |
| 22 | +using System.Text.RegularExpressions; |
| 23 | + |
| 24 | +namespace Microsoft.Azure.Commands.Profile.AzureRmAlias |
| 25 | +{ |
| 26 | + public class AliasHelper |
| 27 | + { |
| 28 | + private const string STARTALIASIMPORTMARKER = "#Begin Azure PowerShell alias import"; |
| 29 | + private const string ENDALIASIMPORTMARKER = "#End Azure PowerShell alias import"; |
| 30 | + |
| 31 | + private IDataStore _dataStore; |
| 32 | + |
| 33 | + public AliasHelper(IDataStore dataStore) |
| 34 | + { |
| 35 | + _dataStore = dataStore; |
| 36 | + FileUtilities.DataStore = dataStore; |
| 37 | + } |
| 38 | + |
| 39 | + public AliasHelper() : this(AzureSession.Instance.DataStore) |
| 40 | + { |
| 41 | + } |
| 42 | + |
| 43 | + public static string GetProfilePath(string Scope, SessionState sessionState) |
| 44 | + { |
| 45 | + var userprofile = ""; |
| 46 | + if (Scope != null && Scope.Equals("CurrentUser")) |
| 47 | + { |
| 48 | + var editionType = sessionState.PSVariable.GetValue("PSEdition") as string; |
| 49 | + var psFolder = string.Equals(editionType, "Desktop", StringComparison.OrdinalIgnoreCase) ? "WindowsPowerShell" : "PowerShell"; |
| 50 | + userprofile = Path.Combine(sessionState.PSVariable.GetValue("env:USERPROFILE").ToString(), "Documents", psFolder, "profile.ps1"); |
| 51 | + } |
| 52 | + |
| 53 | + else if (Scope != null && Scope.Equals("LocalMachine")) |
| 54 | + { |
| 55 | + userprofile = Path.Combine(sessionState.PSVariable.GetValue("PSHOME").ToString(), "profile.ps1"); |
| 56 | + } |
| 57 | + |
| 58 | + return userprofile; |
| 59 | + } |
| 60 | + |
| 61 | + public void RemoveAliasesInProfile(string userprofile, string[] Module, Dictionary<string, object> mapping) |
| 62 | + { |
| 63 | + ParseFile(userprofile, Module, out string filecontent, out List<string> modulesToKeep, add: false); |
| 64 | + |
| 65 | + // Add script to enable aliases to profile if there are any modules to keep |
| 66 | + CreateFileEntry(modulesToKeep, filecontent, userprofile, mapping); |
| 67 | + } |
| 68 | + |
| 69 | + public void AddAliasesToProfile(string userprofile, string[] Module, Dictionary<string, object> mapping) |
| 70 | + { |
| 71 | + CreateProfileIfNotExists(userprofile); |
| 72 | + |
| 73 | + ParseFile(userprofile, Module, out string filecontent, out List<string> modulesToKeep, add: true); |
| 74 | + |
| 75 | + if (Module == null) |
| 76 | + { |
| 77 | + CreateFileEntry(mapping.Keys.ToList(), filecontent, userprofile, mapping); |
| 78 | + } |
| 79 | + else |
| 80 | + { |
| 81 | + CreateFileEntry(modulesToKeep, filecontent, userprofile, mapping); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + public void ParseFile(string userprofile, string[] Module, out string filecontent, out List<string> modulesToKeep, bool add) |
| 86 | + { |
| 87 | + filecontent = ""; |
| 88 | + modulesToKeep = new List<String>(); |
| 89 | + if (add) |
| 90 | + { |
| 91 | + modulesToKeep = Module?.ToList(); |
| 92 | + } |
| 93 | + |
| 94 | + |
| 95 | + string originalText = _dataStore.ReadFileAsText(userprofile.ToString()); |
| 96 | + if (originalText.Contains(STARTALIASIMPORTMARKER)) |
| 97 | + { |
| 98 | + // Add back profile code unrelated to Azure PowerShell aliases |
| 99 | + var splitOriginalText = originalText.Split(new string[] { STARTALIASIMPORTMARKER, ENDALIASIMPORTMARKER }, StringSplitOptions.None); |
| 100 | + filecontent += splitOriginalText[0].Trim(); |
| 101 | + if (splitOriginalText.Length > 2) |
| 102 | + { |
| 103 | + filecontent += Environment.NewLine + splitOriginalText[2].Trim() + Environment.NewLine; |
| 104 | + } |
| 105 | + |
| 106 | + if (Module != null) |
| 107 | + { |
| 108 | + // Add modules currently in the profile to the list of modules to enable. |
| 109 | + var regex = new Regex(@"Az\.[a-zA-Z0-9\.]+(,\s|\s-)"); |
| 110 | + Match match = regex.Match(splitOriginalText[1].Split(new string[] { "Import-Module Az.Profile" }, StringSplitOptions.None)[1]); |
| 111 | + while (match.Success) |
| 112 | + { |
| 113 | + if (add) |
| 114 | + { |
| 115 | + if (!modulesToKeep.Contains(match.ToString().Substring(0, match.ToString().Length - 2), StringComparer.CurrentCultureIgnoreCase)) |
| 116 | + { |
| 117 | + modulesToKeep.Add(match.ToString().Substring(0, match.ToString().Length - 2)); |
| 118 | + } |
| 119 | + match = match.NextMatch(); |
| 120 | + } |
| 121 | + else |
| 122 | + { |
| 123 | + if (!Module.Contains(match.ToString().Substring(0, match.ToString().Length - 2), StringComparer.CurrentCultureIgnoreCase)) |
| 124 | + { |
| 125 | + modulesToKeep.Add(match.ToString().Substring(0, match.ToString().Length - 2)); |
| 126 | + } |
| 127 | + match = match.NextMatch(); |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + else |
| 133 | + { |
| 134 | + filecontent = originalText; |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + public void CreateFileEntry(List<string> modulesToKeep, string filecontent, string userprofile, Dictionary<string, object> mapping) |
| 139 | + { |
| 140 | + if (modulesToKeep.Count > 0) |
| 141 | + { |
| 142 | + filecontent += STARTALIASIMPORTMARKER + Environment.NewLine + "Import-Module Az.Profile -ErrorAction SilentlyContinue -ErrorVariable importError" + |
| 143 | + Environment.NewLine + "if ($importerror.Count -eq 0) { " + Environment.NewLine; |
| 144 | + |
| 145 | + var validModules = new List<string>(); |
| 146 | + foreach (var name in modulesToKeep) |
| 147 | + { |
| 148 | + if (mapping.ContainsKey(name)) |
| 149 | + { |
| 150 | + validModules.Add(name); |
| 151 | + } |
| 152 | + } |
| 153 | + filecontent += " Enable-AzureRmAlias -Module " + string.Join(", ", validModules) + " -ErrorAction SilentlyContinue; " + Environment.NewLine; |
| 154 | + |
| 155 | + filecontent += "}" + Environment.NewLine + ENDALIASIMPORTMARKER; |
| 156 | + } |
| 157 | + |
| 158 | + ExecuteFileActionWithFriendlyError(() => |
| 159 | + { |
| 160 | + FileUtilities.EnsureDirectoryExists(Path.GetDirectoryName(userprofile)); |
| 161 | + _dataStore.WriteFile(userprofile, filecontent); |
| 162 | + }); |
| 163 | + } |
| 164 | + |
| 165 | + public void CreateProfileIfNotExists(string userprofile) |
| 166 | + { |
| 167 | + ExecuteFileActionWithFriendlyError(() => |
| 168 | + { |
| 169 | + FileUtilities.EnsureDirectoryExists(Path.GetDirectoryName(userprofile)); |
| 170 | + if (!_dataStore.FileExists(userprofile)) |
| 171 | + { |
| 172 | + _dataStore.WriteFile(userprofile, Environment.NewLine); |
| 173 | + } |
| 174 | + }); |
| 175 | + } |
| 176 | + |
| 177 | + private static void ExecuteFileActionWithFriendlyError(Action fileAction) |
| 178 | + { |
| 179 | + try |
| 180 | + { |
| 181 | + fileAction(); |
| 182 | + } |
| 183 | + catch (UnauthorizedAccessException accessException) when (accessException?.Message != null && accessException.Message.ToLower().Contains("denied")) |
| 184 | + { |
| 185 | + throw new UnauthorizedAccessException(Properties.Resources.AliasImportFailure, accessException); |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | +} |
0 commit comments