internal PSModuleInfo LoadModuleByName(string name, bool loadToGlobalScope, bool importMembers = true) { // TODO: where do we handle FileNotFoundExceptions etc? var path = new Path(name).NormalizeSlashes(); if (name.Contains(path.CorrectSlash) || path.HasExtension()) { // check if it's already loaded var moduleInfo = _executionContext.SessionState.LoadedModules.Get(path); if (moduleInfo != null) { return moduleInfo; } // load it otherwise moduleInfo = LoadModuleByPath(path); // modules are loaded either to global or module scope, never to local scope var targetScope = loadToGlobalScope ? ModuleIntrinsics.ModuleImportScopes.Global : ModuleIntrinsics.ModuleImportScopes.Module; _executionContext.SessionState.LoadedModules.Add(moduleInfo, targetScope); if (importMembers) { _executionContext.SessionState.LoadedModules.ImportMembers(moduleInfo, targetScope); } return moduleInfo; } // otherwise we'd need to look in our module paths for a module throw new NotImplementedException("Currently you can only a specific module file, not installed modules"); }
internal override void SetSessionStateItem(Path name, object value, bool writeItem) { PSVariable variable = null; if (value != null) { variable = value as PSVariable; if (variable == null) { variable = new PSVariable(name, value); } else if (String.Compare(name, variable.Name, true, System.Globalization.CultureInfo.CurrentCulture) != 0) { PSVariable var = new PSVariable(name, variable.Value, variable.Options, variable.Attributes); var.Description = variable.Description; variable = var; } } else { variable = new PSVariable(name, null); } // TODO: can be Force'ed PSVariable item = base.SessionState.SessionStateGlobal.SetVariable(variable) as PSVariable; if (writeItem && (item != null)) { WriteItemObject(item, item.Name, false); } }
internal override void SetSessionStateItem(Path path, object value, bool writeItem) { if (value == null) { Environment.SetEnvironmentVariable(path, null); } else { if (value is DictionaryEntry) { value = ((DictionaryEntry)value).Value; } string str = value as string; if (str == null) { str = PSObject.AsPSObject(value).ToString(); } Environment.SetEnvironmentVariable(path, str); DictionaryEntry item = new DictionaryEntry(path, str); if (writeItem) { WriteItemObject(item, path, false); } } }
public IEnumerable <string> GetFilesystemExpansions(string cmdStart, string replacableEnd) { replacableEnd = StripQuotes(replacableEnd); var p = new System.Management.Path(replacableEnd).NormalizeSlashes().ResolveTilde(); var startPath = new System.Management.Path("."); string lookFor = replacableEnd; if (p.ToString().Contains(p.CorrectSlash)) { // we already deal with a path var escapedSlash = p.CorrectSlash; if (escapedSlash.Equals(@"\")) { escapedSlash = @"\\"; } if (!p.HasDrive() && !Regex.IsMatch(p, @"^\.+" + escapedSlash)) { p = new System.Management.Path(".").Combine(p); } if (p.EndsWithSlash()) { startPath = p; lookFor = ""; } else { startPath = p.GetParentPath(null); lookFor = p.GetChildNameOrSelfIfNoChild(); } } var dirinfo = new DirectoryInfo(startPath); if (!dirinfo.Exists) { return(Enumerable.Empty <string>()); } var expansions = new List <string>(); var pattern = new WildcardPattern(lookFor + "*"); bool allowHidden = lookFor.Length > 0; // add directories expansions.AddRange( from subdir in dirinfo.GetDirectories() where pattern.IsMatch(subdir.Name) && (allowHidden || (subdir.Attributes & FileAttributes.Hidden) == 0) orderby subdir.Name ascending select QuoteIfNecessary(startPath.Combine(subdir.Name).AppendSlashAtEnd()) ); // add files expansions.AddRange( from file in dirinfo.GetFiles() where pattern.IsMatch(file.Name) && (allowHidden || (file.Attributes & FileAttributes.Hidden) == 0) orderby file.Name ascending select QuoteIfNecessary(startPath.Combine(file.Name)) ); return(expansions); }
public static string CalculateFullPath(Path curLocation, Path changeCommandStr) { // TODO: sburnicki rewrite that stuff with pathintrinsics var changeCommand = (changeCommandStr ?? string.Empty).NormalizeSlashes(); var currentLocation = curLocation.NormalizeSlashes(); bool applyParts = false; Path resultPath; // use the input 'changeCommand' path if it's // 'rooted' otherwise we go from the currentLocation if (changeCommand.HasDrive()) { // windows case where changeCommand == "/" or "\" but the currentLocation has a "C:" drive string currentLocationDrive = currentLocation.GetDrive(); if (changeCommand.StartsWithSlash() && !changeCommand.GetDrive().Equals(currentLocationDrive, StringComparison.InvariantCultureIgnoreCase)) { resultPath = new Path(currentLocation.CorrectSlash, currentLocation.WrongSlash, string.Format("{0}:{1}", currentLocationDrive, changeCommand)); } else { resultPath = changeCommand; } } else { applyParts = true; resultPath = currentLocation; } var correctSeparator = Char.Parse(currentLocation.CorrectSlash); var changeParts = changeCommand.ToString().Split(correctSeparator).Where(s => !string.IsNullOrEmpty(s)); foreach (var part in changeParts) { // ignore single dot as it does nothing... if (part == ".") { continue; } // ignore trying to go up a dir from the root dir if (part == ".." && resultPath.IsRootPath()) { continue; } if (part == "..") { resultPath = resultPath.GetParentPath(currentLocation.GetDrive()); } else if (applyParts) { resultPath = resultPath.Combine(part); } } return resultPath.ApplyDriveSlash(); }
internal override object GetSessionStateItem(Path name) { // TODO: deal with empty path if (string.Equals("variable:" + name.CorrectSlash, name, StringComparison.CurrentCultureIgnoreCase)) return true; return SessionState.SessionStateGlobal.GetVariable(name); }
internal override object GetSessionStateItem(Path name) { string environmentVariable = Environment.GetEnvironmentVariable(name); if (environmentVariable != null) { return new DictionaryEntry(name, environmentVariable); } return null; }
public void ShouldApplyNavigation(string normalSlash, string currentLocation, string changeCommand, string expectedFullPath, string errorMessage) { var currLocation = new Path(normalSlash, normalSlash == "\\" ? "/" : "\\", currentLocation); var changePath = new Path(normalSlash, normalSlash == "\\" ? "/" : "\\", changeCommand); var result = PathNavigation.CalculateFullPath(currLocation, changePath); result.ShouldEqual(expectedFullPath, errorMessage); }
internal override object GetSessionStateItem(Path name) { Path path = PathIntrinsics.RemoveDriveName(name); path = path.TrimStartSlash(); string environmentVariable = Environment.GetEnvironmentVariable(path); if (environmentVariable != null) { return new DictionaryEntry(path, environmentVariable); } return null; }
private PSModuleInfo LoadModuleByPath(Path path) { // ALWAYS derive from global scope: the Scope parameter only defines where stuff is imported to var sessionState = new SessionState(_executionContext.SessionStateGlobal.RootSessionState); sessionState.IsScriptScope = true; sessionState.PSVariable.Set("PSScriptRoot", path.GetDirectory()); var moduleInfo = new PSModuleInfo(path, path.GetFileNameWithoutExtension(), sessionState); sessionState.SetModule(moduleInfo); LoadFileIntoModule(moduleInfo, path); return moduleInfo; }
protected override string NormalizeRelativePath(string path, string basePath) { var normPath = new Path(path).NormalizeSlashes(); var normBase = new Path(basePath).NormalizeSlashes(); if (!normPath.StartsWith(normBase)) { var ex = new PSArgumentException("Path is outside of base path!", "PathOutsideBasePath", ErrorCategory.InvalidArgument); WriteError(ex.ErrorRecord); return null; } return new Path(path.Substring(basePath.Length)).TrimStartSlash().ToString(); }
protected override void NewItem(System.Management.Path path, string itemTypeName, object newItemValue) { path = NormalizePath(path); var type = GetItemType(itemTypeName); if (type.Equals(ItemType.Unknown)) { throw new PSInvalidOperationException("Cannot create an item of unknown type"); } System.IO.FileMode mode = System.IO.FileMode.CreateNew; if (Force.IsPresent) { mode = System.IO.FileMode.Create; CreateIntermediateDirectories(path); } if (type.Equals(ItemType.Directory)) { var dirinfo = new System.IO.DirectoryInfo(path.ToString()); dirinfo.Create(); WriteItemObject(dirinfo, path, true); return; } // else ItemType is File if (!ShouldProcess(path)) { return; } try { using (var stream = new System.IO.FileStream(path, mode, System.IO.FileAccess.Write, System.IO.FileShare.None)) { if (newItemValue != null) { var writer = new System.IO.StreamWriter(stream); writer.Write(newItemValue.ToString()); writer.Flush(); writer.Close(); } } WriteItemObject(new System.IO.FileInfo(path), path, false); } catch (System.IO.IOException ex) { WriteError(new ErrorRecord(ex, "NewItem", ErrorCategory.WriteError, path)); } }
private void LoadFileIntoModule(PSModuleInfo moduleInfo, Path path) { // prevents accidental loops while loading a module moduleInfo.NestingDepth++; if (moduleInfo.NestingDepth > 10) { var msg = "The module is too deeply nested. A module can be only nested 10 times. Make sure to check" + " the loading order of your module"; throw new PSInvalidOperationException(msg, "Modules_ModuleTooDeeplyNested", ErrorCategory.InvalidOperation); } moduleInfo.Path = path; // update path for nested modules var stringComparer = StringComparer.InvariantCultureIgnoreCase; var ext = path.GetExtension(); if (_scriptExtensions.Contains(ext, stringComparer)) { moduleInfo.ModuleType = ModuleType.Script; LoadScriptModule(moduleInfo, path); // actually load the script } else if (_binaryExtensions.Contains(ext, stringComparer)) { moduleInfo.ModuleType = ModuleType.Binary; LoadBinaryModule(moduleInfo, path); } else if (_manifestExtensions.Contains(ext, stringComparer)) { moduleInfo.ModuleType = ModuleType.Manifest; LoadManifestModule(moduleInfo, path); } else { var msg = "The extension '" + ext + "' is currently not supported"; throw new PSInvalidOperationException(msg, "Modules_InvalidFileExtension", ErrorCategory.InvalidOperation, null, false); } moduleInfo.ValidateExportedMembers(); }
public object GetContentWriterDynamicParameters(Path path) { throw new NotImplementedException(); }
public IContentWriter GetContentWriter(Path path) { throw new NotImplementedException(); }
public object ClearContentDynamicParameters(Path path) { throw new NotImplementedException(); }
public void ClearContent(Path path) { throw new NotImplementedException(); }
protected override void SetItem(Path name, object value) { throw new NotImplementedException(); }
protected override void RenameItem(Path name, Path newName) { throw new NotImplementedException(); }
protected override void RemoveItem(Path path, bool recurse) { throw new NotImplementedException(); }
protected override void NewItem(Path path, string type, object newItem) { throw new NotImplementedException(); }
protected override bool ItemExists(Path path) { if (string.IsNullOrEmpty(path) || path.IsRootPath()) { return true; } return null != GetSessionStateItem(path); }
protected override bool IsValidPath(Path path) { throw new NotImplementedException(); }
protected override void CopyItem(Path path, Path copyPath, bool recurse) { throw new NotImplementedException(); }
internal abstract void SetSessionStateItem(Path name, object value, bool writeItem);
internal abstract object GetSessionStateItem(Path name);
internal static System.Management.Path ShouldEqual(this System.Management.Path inputPath, System.Management.Path expectedPath, string message = null) { Assert.AreEqual((string)expectedPath, (string)inputPath, message); return(inputPath); }
internal static string PathShouldEqual(this System.Management.Path actual, System.Management.Path expected, string message = null) { return(PathShouldEqual((string)actual, (string)expected, message)); }
//TODO: remove these functions from all subclasses - they are never in use! internal abstract void RemoveSessionStateItem(Path name);
protected override void GetChildNames(Path path, ReturnContainers returnContainers) { throw new NotImplementedException(); }
protected override void ClearItem(Path path) { throw new NotImplementedException(); }
protected override void GetItem(Path name) { throw new NotImplementedException(); }
protected override void GetChildItems(Path path, bool recurse) { if (path == "\\") path = string.Empty; if (string.IsNullOrEmpty(path)) { IDictionary sessionStateTable = GetSessionStateTable(); foreach (DictionaryEntry entry in sessionStateTable) { WriteItemObject(entry.Value, (string)entry.Key, false); } } else { object item = GetSessionStateItem(path); if (item != null) { WriteItemObject(item, path, false); } } }
protected override bool HasChildItems(Path path) { throw new NotImplementedException(); }