private void ParseParameters(IConfiguration configuration, IFileSystem fileSystem, PathInfo currentFileSystemLocation) { configuration.FeatureFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.FeatureDirectory); configuration.OutputFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.OutputDirectory); if (!string.IsNullOrEmpty(this.TestResultsFormat)) { configuration.TestResultsFormat = (TestResultsFormat)Enum.Parse(typeof(TestResultsFormat), this.TestResultsFormat, true); } if (!string.IsNullOrEmpty(this.TestResultsFile)) { configuration.AddTestResultFile(fileSystem.FileInfo.FromFileName(this.TestResultsFile)); } configuration.SystemUnderTestName = this.SystemUnderTestName; configuration.SystemUnderTestVersion = this.SystemUnderTestVersion; if (!string.IsNullOrEmpty(this.DocumentationFormat)) { configuration.DocumentationFormat = (DocumentationFormat)Enum.Parse(typeof(DocumentationFormat), this.DocumentationFormat, true); } if (!string.IsNullOrEmpty(this.Language)) { configuration.Language = this.Language; } }
public void Serialize(Item item, string path, string id, bool recursive, string target, string[] languages, PathInfo currentPathInfo) { if (item == null) { if (!String.IsNullOrEmpty(id)) { Database currentDb = Factory.GetDatabase(currentPathInfo.Drive.Name); item = currentDb.GetItem(new ID(id)); } else if (!String.IsNullOrEmpty(path)) { path = path.Replace('\\', '/'); item = PathUtilities.GetItem(path, currentPathInfo.Drive.Name, currentPathInfo.ProviderPath); } } if (item != null) { SerializeToTarget(item, target, recursive, languages); } else { throw new InvalidOperationException("No item has been specified to the Serialize-Item cmdlet."); } }
internal ResolvedPscxPathImpl(PathInfo resolvedPath) { _pathInfo = resolvedPath; _providerInfo = resolvedPath.Provider; _driveInfo = resolvedPath.Drive; _providerPath = resolvedPath.ProviderPath; _isUnresolved = false; }
private void ParseParameters(IConfiguration configuration, IFileSystem fileSystem, PathInfo currentFileSystemLocation) { configuration.FeatureFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.FeatureDirectory); configuration.OutputFolder = this.DetermineFeatureFolder(fileSystem, currentFileSystemLocation, this.OutputDirectory); if (!string.IsNullOrEmpty(this.TestResultsFormat)) { configuration.TestResultsFormat = (TestResultsFormat)Enum.Parse(typeof(TestResultsFormat), this.TestResultsFormat, true); } if (!string.IsNullOrEmpty(this.TestResultsFile)) { configuration.AddTestResultFile(fileSystem.FileInfo.FromFileName(this.TestResultsFile)); } configuration.SystemUnderTestName = this.SystemUnderTestName; configuration.SystemUnderTestVersion = this.SystemUnderTestVersion; if (!string.IsNullOrEmpty(this.DocumentationFormat)) { configuration.DocumentationFormat = (DocumentationFormat)Enum.Parse(typeof(DocumentationFormat), this.DocumentationFormat, true); } if (!string.IsNullOrEmpty(this.Language)) { configuration.Language = this.Language; } if (this.IncludeExperimentalFeatures.IsPresent) { configuration.EnableExperimentalFeatures(); } if (this.IncludeExperimentalFeatures.IsPresent) { configuration.EnableExperimentalFeatures(); } bool shouldEnableComments; if (bool.TryParse(this.EnableComments, out shouldEnableComments)) { if (!shouldEnableComments) { configuration.DisableComments(); } } }
private PathInfo ResolvePath(string pathToResolve, bool isLiteralPath, bool allowNonexistingPaths, PSCmdlet cmdlet) { CmdletProviderContext context = new CmdletProviderContext(cmdlet) { SuppressWildcardExpansion = isLiteralPath }; Collection<PathInfo> targetObject = new Collection<PathInfo>(); try { foreach (PathInfo info in cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, context)) { targetObject.Add(info); } } catch (PSNotSupportedException exception) { cmdlet.ThrowTerminatingError(new ErrorRecord(exception.ErrorRecord, exception)); } catch (DriveNotFoundException exception2) { cmdlet.ThrowTerminatingError(new ErrorRecord(exception2.ErrorRecord, exception2)); } catch (ProviderNotFoundException exception3) { cmdlet.ThrowTerminatingError(new ErrorRecord(exception3.ErrorRecord, exception3)); } catch (ItemNotFoundException exception4) { if (allowNonexistingPaths) { ProviderInfo provider = null; PSDriveInfo drive = null; string path = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, context, out provider, out drive); PathInfo item = new PathInfo(drive, provider, path, cmdlet.SessionState); targetObject.Add(item); } else { cmdlet.ThrowTerminatingError(new ErrorRecord(exception4.ErrorRecord, exception4)); } } if (targetObject.Count == 1) { return targetObject[0]; } Exception exception5 = PSTraceSource.NewNotSupportedException(); cmdlet.ThrowTerminatingError(new ErrorRecord(exception5, "NotSupported", ErrorCategory.NotImplemented, targetObject)); return null; }
/// <summary> /// Resets the current working drive and directory to the first /// entry on the working directory stack and removes that entry /// from the stack. /// </summary> /// <param name="stackName"> /// The ID of the stack to pop the location from. If it is null or /// empty the default stack is used. /// </param> /// <returns> /// A PathInfo object representing the location that was popped /// from the location stack and set as the new location. /// </returns> /// <exception cref="ArgumentException"> /// If the path on the stack does not exist, is not a container, or /// resolved to multiple containers. /// or /// If <paramref name="stackName"/> contains wildcard characters and resolves /// to multiple location stacks. /// or /// A stack was not found with the specified name. /// </exception> /// <exception cref="ProviderNotFoundException"> /// If the path on the stack refers to a provider that does not exist. /// </exception> /// <exception cref="DriveNotFoundException"> /// If the path on the stack refers to a drive that does not exist. /// </exception> /// <exception cref="ProviderInvocationException"> /// If the provider associated with the path on the stack threw an /// exception. /// </exception> internal PathInfo PopLocation(string stackName) { if (String.IsNullOrEmpty(stackName)) { stackName = _defaultStackName; } if (WildcardPattern.ContainsWildcardCharacters(stackName)) { // Need to glob the stack name, but it can only glob to a single. bool haveMatch = false; WildcardPattern stackNamePattern = WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase); foreach (string key in _workingLocationStack.Keys) { if (stackNamePattern.IsMatch(key)) { if (haveMatch) { throw PSTraceSource.NewArgumentException( "stackName", SessionStateStrings.StackNameResolvedToMultiple, stackName); } haveMatch = true; stackName = key; } } } PathInfo result = CurrentLocation; try { Stack <PathInfo> locationStack = null; if (!_workingLocationStack.TryGetValue(stackName, out locationStack)) { if (!string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase)) { throw PSTraceSource.NewArgumentException( "stackName", SessionStateStrings.StackNotFound, stackName); } return(null); } PathInfo poppedWorkingDirectory = locationStack.Pop(); Dbg.Diagnostics.Assert( poppedWorkingDirectory != null, "All items in the workingLocationStack should be " + "of type PathInfo"); string newPath = LocationGlobber.GetMshQualifiedPath( WildcardPattern.Escape(poppedWorkingDirectory.Path), poppedWorkingDirectory.GetDrive()); result = SetLocation(newPath); if (locationStack.Count == 0 && !String.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase)) { // Remove the stack from the stack list if it // no longer contains any paths. _workingLocationStack.Remove(stackName); } } catch (InvalidOperationException) { // This is a no-op. We stay with the current working // directory. } return(result); }
/// <summary> /// Initializes a new instance of the LocationChangedEventArgs class. /// </summary> /// <param name="sessionState"> /// The public session state instance associated with this runspace. /// </param> /// <param name="oldPath"> /// The path we changed locations from. /// </param> /// <param name="newPath"> /// The path we change locations to. /// </param> internal LocationChangedEventArgs(SessionState sessionState, PathInfo oldPath, PathInfo newPath) { SessionState = sessionState; OldPath = oldPath; NewPath = newPath; }
} // SetLocation /// <summary> /// Changes the current working directory to the path specified /// </summary> /// <param name="path"> /// The path of the new current working directory /// </param> /// <param name="context"> /// The context the provider uses when performing the operation. /// </param> /// <returns> /// The PathInfo object representing the path of the location /// that was set. /// </returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="path"/> does not exist, is not a container, or /// resolved to multiple containers. /// </exception> /// <exception cref="ProviderNotFoundException"> /// If <paramref name="path"/> refers to a provider that does not exist. /// </exception> /// <exception cref="DriveNotFoundException"> /// If <paramref name="path"/> refers to a drive that does not exist. /// </exception> /// <exception cref="ProviderInvocationException"> /// If the provider associated with <paramref name="path"/> threw an /// exception. /// </exception> /// <exception cref="ItemNotFoundException"> /// If the <paramref name="path"/> could not be resolved. /// </exception> internal PathInfo SetLocation(string path, CmdletProviderContext context) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } PathInfo current = CurrentLocation; string originalPath = path; string driveName = null; ProviderInfo provider = null; string providerId = null; switch (originalPath) { case string originalPathSwitch when originalPathSwitch.Equals("-", StringComparison.OrdinalIgnoreCase): if (_setLocationHistory.UndoCount <= 0) { throw new InvalidOperationException(SessionStateStrings.LocationUndoStackIsEmpty); } path = _setLocationHistory.Undo(this.CurrentLocation).Path; break; case string originalPathSwitch when originalPathSwitch.Equals("+", StringComparison.OrdinalIgnoreCase): if (_setLocationHistory.RedoCount <= 0) { throw new InvalidOperationException(SessionStateStrings.LocationRedoStackIsEmpty); } path = _setLocationHistory.Redo(this.CurrentLocation).Path; break; default: var pushPathInfo = GetNewPushPathInfo(); _setLocationHistory.Push(pushPathInfo); break; } PSDriveInfo previousWorkingDrive = CurrentDrive; // First check to see if the path is a home path if (LocationGlobber.IsHomePath(path)) { path = Globber.GetHomeRelativePath(path); } if (LocationGlobber.IsProviderDirectPath(path)) { // The path is a provider-direct path so use the current // provider and its hidden drive but don't modify the path // at all. provider = CurrentLocation.Provider; CurrentDrive = provider.HiddenDrive; } else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId)) { provider = GetSingleProvider(providerId); CurrentDrive = provider.HiddenDrive; } else { // See if the path is a relative or absolute // path. if (Globber.IsAbsolutePath(path, out driveName)) { // Since the path is an absolute path // we need to change the current working // drive PSDriveInfo newWorkingDrive = GetDrive(driveName); CurrentDrive = newWorkingDrive; // If the path is simply a colon-terminated drive, // not a slash-terminated path to the root of a drive, // set the path to the current working directory of that drive. string colonTerminatedVolume = CurrentDrive.Name + ':'; if (CurrentDrive.VolumeSeparatedByColon && (path.Length == colonTerminatedVolume.Length)) { path = Path.Combine((colonTerminatedVolume + Path.DirectorySeparatorChar), CurrentDrive.CurrentLocation); } // Now that the current working drive is set, // process the rest of the path as a relative path. } } if (context == null) { context = new CmdletProviderContext(this.ExecutionContext); } if (CurrentDrive != null) { context.Drive = CurrentDrive; } CmdletProvider providerInstance = null; Collection <PathInfo> workingPath = null; try { workingPath = Globber.GetGlobbedMonadPathsFromMonadPath( path, false, context, out providerInstance); } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception) // Catch-all OK, 3rd party callout { // Reset the drive to the previous drive and // then rethrow the error CurrentDrive = previousWorkingDrive; throw; } if (workingPath.Count == 0) { // Set the current working drive back to the previous // one in case it was changed. CurrentDrive = previousWorkingDrive; throw new ItemNotFoundException( path, "PathNotFound", SessionStateStrings.PathNotFound); } // We allow globbing the location as long as it only resolves a single container. bool foundContainer = false; bool pathIsContainer = false; bool pathIsProviderQualifiedPath = false; bool currentPathisProviderQualifiedPath = false; for (int index = 0; index < workingPath.Count; ++index) { CmdletProviderContext normalizePathContext = new CmdletProviderContext(context); PathInfo resolvedPath = workingPath[index]; string currentPath = path; try { string providerName = null; currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName); if (currentPathisProviderQualifiedPath) { // The path should be the provider-qualified path without the provider ID // or :: string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path); try { currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, String.Empty, normalizePathContext); } catch (NotSupportedException) { // Since the provider does not support normalizing the path, just // use the path we currently have. } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception) // Catch-all OK, 3rd party callout { // Reset the drive to the previous drive and // then rethrow the error CurrentDrive = previousWorkingDrive; throw; } } else { try { currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext); } catch (NotSupportedException) { // Since the provider does not support normalizing the path, just // use the path we currently have. } catch (LoopFlowException) { throw; } catch (PipelineStoppedException) { throw; } catch (ActionPreferenceStopException) { throw; } catch (Exception) // Catch-all OK, 3rd party callout { // Reset the drive to the previous drive and // then rethrow the error CurrentDrive = previousWorkingDrive; throw; } } // Now see if there was errors while normalizing the path if (normalizePathContext.HasErrors()) { // Set the current working drive back to the previous // one in case it was changed. CurrentDrive = previousWorkingDrive; normalizePathContext.ThrowFirstErrorOrDoNothing(); } } finally { normalizePathContext.RemoveStopReferral(); } // Check to see if the path is a container bool isContainer = false; CmdletProviderContext itemContainerContext = new CmdletProviderContext(context); itemContainerContext.SuppressWildcardExpansion = true; try { isContainer = IsItemContainer( resolvedPath.Path, itemContainerContext); if (itemContainerContext.HasErrors()) { // Set the current working drive back to the previous // one in case it was changed. CurrentDrive = previousWorkingDrive; itemContainerContext.ThrowFirstErrorOrDoNothing(); } } catch (NotSupportedException) { if (currentPath.Length == 0) { // Treat this as a container because providers that only // support the ContainerCmdletProvider interface are really // containers at their root. isContainer = true; } } finally { itemContainerContext.RemoveStopReferral(); } if (isContainer) { if (foundContainer) { // The path resolved to more than one container // Set the current working drive back to the previous // one in case it was changed. CurrentDrive = previousWorkingDrive; throw PSTraceSource.NewArgumentException( "path", SessionStateStrings.PathResolvedToMultiple, originalPath); } else { // Set the path to use path = currentPath; // Mark it as a container pathIsContainer = true; // Mark whether or not it was provider-qualified pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath; // Mark that we have already found one container. Finding additional // should be an error foundContainer = true; } } } if (pathIsContainer) { // Remove the root slash since it is implied that the // current working directory is relative to the root. if (!LocationGlobber.IsProviderDirectPath(path) && path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.CurrentCulture) && !pathIsProviderQualifiedPath) { path = path.Substring(1); } s_tracer.WriteLine( "New working path = {0}", path); CurrentDrive.CurrentLocation = path; } else { // Set the current working drive back to the previous // one in case it was changed. CurrentDrive = previousWorkingDrive; throw new ItemNotFoundException( originalPath, "PathNotFound", SessionStateStrings.PathNotFound); } // Now make sure the current drive is set in the provider's // current working drive hashtable ProvidersCurrentWorkingDrive[CurrentDrive.Provider] = CurrentDrive; // Set the $PWD variable to the new location this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal); // If an action has been defined for location changes, invoke it now. if (PublicSessionState.InvokeCommand.LocationChangedAction != null) { var eventArgs = new LocationChangedEventArgs(PublicSessionState, current, CurrentLocation); PublicSessionState.InvokeCommand.LocationChangedAction.Invoke(ExecutionContext.CurrentRunspace, eventArgs); s_tracer.WriteLine("Invoked LocationChangedAction"); } return(this.CurrentLocation); } // SetLocation
/// <summary> /// The main execution method for the get-location command. Depending on /// the parameter set that is specified, the command can do many things. /// -locationSet gets the current working directory as a Monad path /// -stackSet gets the directory stack of directories that have been /// pushed by the push-location command /// </summary> protected override void ProcessRecord() { // It is OK to use a switch for string comparison here because we // want a case sensitive comparison in the current culture. switch (ParameterSetName) { case locationSet: PathInfo result = null; if (PSDrive != null && PSDrive.Length > 0) { foreach (string drive in PSDrive) { List<PSDriveInfo> foundDrives = null; try { foundDrives = GetMatchingDrives(drive, PSProvider, null); } catch (DriveNotFoundException e) { ErrorRecord errorRecord = new ErrorRecord( e, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, drive); WriteError(errorRecord); continue; } catch (ProviderNotFoundException e) { ErrorRecord errorRecord = new ErrorRecord( e, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, PSProvider); WriteError(errorRecord); continue; } catch (ArgumentException argException) { ErrorRecord errorRecord = new ErrorRecord( argException, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, drive); WriteError(errorRecord); continue; } // Get the current location for a specific drive and provider foreach (PSDriveInfo workingDrive in foundDrives) { try { string path = LocationGlobber.GetDriveQualifiedPath( workingDrive.CurrentLocation, workingDrive); result = new PathInfo(workingDrive, workingDrive.Provider, path, SessionState); WriteObject(result); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } } } } // If the drive wasn't specified but the provider was else if ((PSDrive == null || PSDrive.Length == 0) && (PSProvider != null && PSProvider.Length > 0)) { foreach (string providerName in PSProvider) { bool providerContainsWildcard = WildcardPattern.ContainsWildcardCharacters(providerName); if (!providerContainsWildcard) { // Since the Provider was specified and doesn't contain // wildcard characters, make sure it exists. try { SessionState.Provider.GetOne(providerName); } catch (ProviderNotFoundException e) { ErrorRecord errorRecord = new ErrorRecord( e, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, providerName); WriteError(errorRecord); continue; } } // Match the providers foreach (ProviderInfo providerInfo in SessionState.Provider.GetAll()) { if (providerInfo.IsMatch(providerName)) { try { WriteObject(SessionState.Path.CurrentProviderLocation(providerInfo.FullName)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (DriveNotFoundException driveNotFound) { if (providerContainsWildcard) { // NTRAID#Windows Out Of Band Releases-923607-2005/11/02-JeffJon // This exception is ignored, because it just means we didn't find // an active drive for the provider. continue; } else { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } } } } } } else { // Get the current working directory using the core command API. WriteObject(SessionState.Path.CurrentLocation); } break; case stackSet: if (_stackNames != null) { foreach (string stackName in _stackNames) { try { // Get the directory stack. This is similar to the "dirs" command WriteObject(SessionState.Path.LocationStack(stackName), false); } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); continue; } } } else { try { WriteObject(SessionState.Path.LocationStack(null), false); } catch (PSArgumentException argException) { WriteError( new ErrorRecord( argException.ErrorRecord, argException)); } } break; default: Dbg.Diagnostics.Assert(false, String.Format(System.Globalization.CultureInfo.InvariantCulture, "One of the predefined parameter sets should have been specified, instead we got: {0}", ParameterSetName)); break; } // case (ParameterSetName) } // ProcessRecord
internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force) { Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null"); Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)"); DirectoryInfo directoryInfo = null; try { string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context); if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.')) { PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem); rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath); } if (string.IsNullOrEmpty(rootedPath)) { string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath(); if (string.IsNullOrEmpty(personalModuleRoot)) { cmdlet.ThrowTerminatingError( new ErrorRecord( new ArgumentException(PathUtilsStrings.ExportPSSession_ErrorModuleNameOrPath), "ExportPSSession_ErrorModuleNameOrPath", ErrorCategory.InvalidArgument, cmdlet)); } rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath); } directoryInfo = new DirectoryInfo(rootedPath); if (directoryInfo.Exists) { if (!force) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, directoryInfo.FullName); ErrorDetails details = new ErrorDetails(errorMessage); ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, directoryInfo); cmdlet.ThrowTerminatingError(errorRecord); } } else { directoryInfo.Create(); } } catch (Exception e) { string errorMessage = string.Format( CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, moduleNameOrPath, e.Message); ErrorDetails details = new ErrorDetails(errorMessage); ErrorRecord errorRecord = new ErrorRecord( new ArgumentException(details.Message, e), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath); cmdlet.ThrowTerminatingError(errorRecord); } return(directoryInfo); }
/// <summary> /// /// </summary> /// <param name="pathInfo"></param> /// <returns></returns> public static PscxPathInfo FromPathInfo(PathInfo pathInfo) { return new ResolvedPscxPathImpl(pathInfo); }
/// <summary> /// Pushes the current location onto the working /// location stack so that it can be retrieved later. /// </summary> /// /// <param name="stackName"> /// The ID of the stack to push the location on. If /// it is null or empty the default stack is used. /// </param> /// internal void PushCurrentLocation(string stackName) { if (String.IsNullOrEmpty(stackName)) { stackName = _defaultStackName; } // Create a new instance of the directory/drive pair ProviderInfo provider = CurrentDrive.Provider; string mshQualifiedPath = LocationGlobber.GetMshQualifiedPath(CurrentDrive.CurrentLocation, CurrentDrive); PathInfo newPushLocation = new PathInfo( CurrentDrive, provider, mshQualifiedPath, new SessionState(this)); s_tracer.WriteLine( "Pushing drive: {0} directory: {1}", CurrentDrive.Name, mshQualifiedPath); // Get the location stack from the hashtable Stack<PathInfo> locationStack = null; if (!_workingLocationStack.TryGetValue(stackName, out locationStack)) { locationStack = new Stack<PathInfo>(); _workingLocationStack[stackName] = locationStack; } // Push the directory/drive pair onto the stack locationStack.Push(newPushLocation); }
internal ContentHolder( PathInfo pathInfo, IContentReader reader, IContentWriter writer) { if (pathInfo == null) { throw PSTraceSource.NewArgumentNullException("pathInfo"); } PathInfo = pathInfo; Reader = reader; Writer = writer; } // constructor
/// <summary> /// Fetch the files, and if requested, all the include files as well. /// </summary> /// <param name="ds"></param> /// <param name="extractionPath"></param> /// <returns></returns> private IEnumerable<FileInfo> GetSvnFiles(SvnTarget ds, PathInfo extractionPath) { // Build the location of this file to write out. var outfile = new FileInfo(Path.Combine(extractionPath.Path, ds.FileName)); WriteVerbose($"Downloading svn file {ds.TargetName}"); MCJobSVNHelpers.ExtractFile(ds, outfile); yield return outfile; // Next, we need to dip into all the levels down to see if we can't // figure out if there are includes. var includeFiles = outfile .ReadLines() .SelectMany(l => ExtractIncludedFiles(l, extractionPath)); foreach (var l in includeFiles) { yield return l; } }
private DirectoryInfoBase DetermineFeatureFolder(IFileSystem fileSystem, PathInfo currentFileSystemLocation, string directory) { DirectoryInfoBase result; if (fileSystem.Path.IsPathRooted(directory)) { result = fileSystem.DirectoryInfo.FromDirectoryName(directory); } else { result = fileSystem.DirectoryInfo.FromDirectoryName( fileSystem.Path.Combine(currentFileSystemLocation.Path, directory)); } return result; }
/// <summary> /// Wraps the content into a PSObject and adds context information as notes /// </summary> /// /// <param name="content"> /// The content being written out. /// </param> /// /// <param name="readCount"> /// The number of blocks that have been read so far. /// </param> /// /// <param name="pathInfo"> /// The context the content was retrieved from. /// </param> /// /// <param name="context"> /// The context the command is being run under. /// </param> /// internal void WriteContentObject(object content, long readCount, PathInfo pathInfo, CmdletProviderContext context) { Dbg.Diagnostics.Assert( content != null, "The caller should verify the content."); Dbg.Diagnostics.Assert( pathInfo != null, "The caller should verify the pathInfo."); Dbg.Diagnostics.Assert( context != null, "The caller should verify the context."); PSObject result = PSObject.AsPSObject(content); Dbg.Diagnostics.Assert( result != null, "A PSObject should always be constructed."); // Use the cached notes if the cache exists and the path is still the same PSNoteProperty note; if (_currentContentItem != null && ((_currentContentItem.PathInfo == pathInfo) || ( String.Compare( pathInfo.Path, _currentContentItem.PathInfo.Path, StringComparison.OrdinalIgnoreCase) == 0) ) ) { result = _currentContentItem.AttachNotes(result); } else { // Generate a new cache item and cache the notes _currentContentItem = new ContentPathsCache(pathInfo); // Construct a provider qualified path as the Path note string psPath = pathInfo.Path; note = new PSNoteProperty("PSPath", psPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSPath", psPath); _currentContentItem.PSPath = psPath; try { // Now get the parent path and child name string parentPath = null; if (pathInfo.Drive != null) { parentPath = SessionState.Path.ParseParent(pathInfo.Path, pathInfo.Drive.Root, context); } else { parentPath = SessionState.Path.ParseParent(pathInfo.Path, String.Empty, context); } note = new PSNoteProperty("PSParentPath", parentPath); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSParentPath", parentPath); _currentContentItem.ParentPath = parentPath; // Get the child name string childName = SessionState.Path.ParseChildName(pathInfo.Path, context); note = new PSNoteProperty("PSChildName", childName); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSChildName", childName); _currentContentItem.ChildName = childName; } catch (NotSupportedException) { // Ignore. The object just won't have ParentPath or ChildName set. } // PSDriveInfo if (pathInfo.Drive != null) { PSDriveInfo drive = pathInfo.Drive; note = new PSNoteProperty("PSDrive", drive); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSDrive", drive); _currentContentItem.Drive = drive; } // ProviderInfo ProviderInfo provider = pathInfo.Provider; note = new PSNoteProperty("PSProvider", provider); result.Properties.Add(note, true); tracer.WriteLine("Attaching {0} = {1}", "PSProvider", provider); _currentContentItem.Provider = provider; } // Add the ReadCount note note = new PSNoteProperty("ReadCount", readCount); result.Properties.Add(note, true); WriteObject(result); } // WriteContentObject
/// <summary> /// Validates the provider of the path, only FileSystem provider is accepted. /// </summary> /// <param name="path">path to validate</param> internal void ValidatePathProvider(PathInfo path) { if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName) { throw new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ProviderIsNotFileSystem, path.Path)); } }
private PathInfo ResolvePath(string pathToResolve, bool allowNonexistingPaths, CmdletProviderContext currentCommandContext) { Collection<PathInfo> targetObject = new Collection<PathInfo>(); try { foreach (PathInfo info in base.SessionState.Path.GetResolvedPSPathFromPSPath(pathToResolve, currentCommandContext)) { targetObject.Add(info); } } catch (PSNotSupportedException exception) { base.WriteError(new ErrorRecord(exception.ErrorRecord, exception)); } catch (System.Management.Automation.DriveNotFoundException exception2) { base.WriteError(new ErrorRecord(exception2.ErrorRecord, exception2)); } catch (ProviderNotFoundException exception3) { base.WriteError(new ErrorRecord(exception3.ErrorRecord, exception3)); } catch (ItemNotFoundException exception4) { if (allowNonexistingPaths) { ProviderInfo provider = null; PSDriveInfo drive = null; string path = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(pathToResolve, currentCommandContext, out provider, out drive); PathInfo item = new PathInfo(drive, provider, path, base.SessionState); targetObject.Add(item); } else { base.WriteError(new ErrorRecord(exception4.ErrorRecord, exception4)); } } if (targetObject.Count == 1) { return targetObject[0]; } if (targetObject.Count > 1) { Exception exception5 = PSTraceSource.NewNotSupportedException(); base.WriteError(new ErrorRecord(exception5, "NotSupported", ErrorCategory.NotImplemented, targetObject)); return null; } return null; }
/// <summary> /// Sets the parent debugger and breakpoints. /// </summary> /// <param name="parent">Parent debugger</param> /// <param name="breakPoints">List of breakpoints</param> /// <param name="startAction">Debugger mode</param> /// <param name="host">host</param> /// <param name="path">Current path</param> public virtual void SetParent( Debugger parent, IEnumerable<Breakpoint> breakPoints, DebuggerResumeAction? startAction, PSHost host, PathInfo path) { throw new PSNotImplementedException(); }
/// <summary> /// Resolves the specified path to PathInfo objects /// </summary> /// /// <param name="pathToResolve"> /// The path to be resolved. Each path may contain glob characters. /// </param> /// /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// /// <param name="currentCommandContext"> /// The context under which the command is running. /// </param> /// /// <returns> /// A string representing the resolved path. /// </returns> /// private PathInfo ResolvePath( string pathToResolve, bool allowNonexistingPaths, CmdletProviderContext currentCommandContext) { Collection<PathInfo> results = new Collection<PathInfo>(); try { // First resolve path Collection<PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( pathToResolve, currentCommandContext); foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFound) { if (allowNonexistingPaths) { ProviderInfo provider = null; System.Management.Automation.PSDriveInfo drive = null; string unresolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath( pathToResolve, currentCommandContext, out provider, out drive); PathInfo pathInfo = new PathInfo( drive, provider, unresolvedPath, SessionState); results.Add(pathInfo); } else { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); } } if (results.Count == 1) { return results[0]; } else if (results.Count > 1) { Exception e = PSTraceSource.NewNotSupportedException(); WriteError( new ErrorRecord(e, "NotSupported", ErrorCategory.NotImplemented, results)); return null; } else { return null; } } // ResolvePath
/// <summary> /// Extract any include files (and recurse) and return the file list. /// </summary> /// <param name="pythonLine"></param> /// <param name="extractionPath"></param> /// <returns></returns> private IEnumerable<FileInfo> ExtractIncludedFiles(string pythonLine, PathInfo extractionPath) { var includeInfo = ExtractIncludeInformation(pythonLine); if (includeInfo != null) { // Get the svn target. var f = FindIncludeFile(includeInfo.includeName); if (f == null) { WriteWarning($"Unable to find and download include file {includeInfo.includeName}."); } else { foreach (var includeFiles in GetSvnFiles(f, extractionPath)) { yield return includeFiles; } } } }
/// <summary> /// Resolves the specified path to PathInfo objects /// </summary> /// /// <param name="pathToResolve"> /// The path to be resolved. Each path may contain glob characters. /// </param> /// /// <param name="isLiteralPath"> /// True if wildcard expansion should be suppressed for pathToResolve. /// </param> /// /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// /// <param name="cmdlet"> /// Calling cmdlet /// </param> /// /// <returns> /// A string representing the resolved path. /// </returns> /// private static PathInfo ResolvePath( string pathToResolve, bool isLiteralPath, bool allowNonexistingPaths, PSCmdlet cmdlet) { // Construct cmdletprovidercontext CmdletProviderContext cmdContext = new CmdletProviderContext(cmdlet); cmdContext.SuppressWildcardExpansion = isLiteralPath; Collection<PathInfo> results = new Collection<PathInfo>(); try { // First resolve path Collection<PathInfo> pathInfos = cmdlet.SessionState.Path.GetResolvedPSPathFromPSPath( pathToResolve, cmdContext); foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { cmdlet.ThrowTerminatingError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (System.Management.Automation.DriveNotFoundException driveNotFound) { cmdlet.ThrowTerminatingError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { cmdlet.ThrowTerminatingError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFound) { if (allowNonexistingPaths) { ProviderInfo provider = null; System.Management.Automation.PSDriveInfo drive = null; string unresolvedPath = cmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath( pathToResolve, cmdContext, out provider, out drive); PathInfo pathInfo = new PathInfo( drive, provider, unresolvedPath, cmdlet.SessionState); results.Add(pathInfo); } else { cmdlet.ThrowTerminatingError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); } } if (results.Count == 1) { return results[0]; } else //if (results.Count > 1) { Exception e = PSTraceSource.NewNotSupportedException(); cmdlet.ThrowTerminatingError( new ErrorRecord(e, "NotSupported", ErrorCategory.NotImplemented, results)); return null; } } // ResolvePath
/// <summary> /// Sets the parent debugger, breakpoints, function source and other /// debugging context information. /// </summary> /// <param name="parent">Parent debugger</param> /// <param name="breakPoints">List of breakpoints</param> /// <param name="startAction">Debugger mode</param> /// <param name="host">PowerShell host</param> /// <param name="path">Current path</param> /// <param name="functionSourceMap">Function to source map</param> public virtual void SetParent( Debugger parent, IEnumerable<Breakpoint> breakPoints, DebuggerResumeAction? startAction, PSHost host, PathInfo path, Dictionary<string, DebugSource> functionSourceMap) { throw new PSNotImplementedException(); }
/// <summary> /// Constructs a content cache item. /// </summary> /// /// <param name="pathInfo"> /// The path information for which the cache will be bound. /// </param> /// public ContentPathsCache(PathInfo pathInfo) { PathInfo = pathInfo; }
internal PathInfo GetNamespaceCurrentLocation(string namespaceID) { if (namespaceID == null) { throw PSTraceSource.NewArgumentNullException("namespaceID"); } PSDriveInfo info = null; if (namespaceID.Length == 0) { this.ProvidersCurrentWorkingDrive.TryGetValue(this.CurrentDrive.Provider, out info); } else { this.ProvidersCurrentWorkingDrive.TryGetValue(this.GetSingleProvider(namespaceID), out info); } if (info == null) { System.Management.Automation.DriveNotFoundException exception = new System.Management.Automation.DriveNotFoundException(namespaceID, "DriveNotFound", SessionStateStrings.DriveNotFound); throw exception; } CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext) { Drive = info }; string path = null; if (info.Hidden) { if (LocationGlobber.IsProviderDirectPath(info.CurrentLocation)) { path = info.CurrentLocation; } else { path = LocationGlobber.GetProviderQualifiedPath(info.CurrentLocation, info.Provider); } } else { path = LocationGlobber.GetDriveQualifiedPath(info.CurrentLocation, info); } PathInfo info2 = new PathInfo(info, info.Provider, path, new SessionState(this)); tracer.WriteLine("result = {0}", new object[] { info2 }); return info2; }
} // GetContentReaders /// <summary> /// Resolves the specified paths to PathInfo objects /// </summary> /// /// <param name="pathsToResolve"> /// The paths to be resolved. Each path may contain glob characters. /// </param> /// /// <param name="allowNonexistingPaths"> /// If true, resolves the path even if it doesn't exist. /// </param> /// /// <param name="allowEmptyResult"> /// If true, allows a wildcard that returns no results. /// </param> /// /// <param name="currentCommandContext"> /// The context under which the command is running. /// </param> /// /// <returns> /// An array of PathInfo objects that are the resolved paths for the /// <paramref name="pathsToResolve"/> parameter. /// </returns> /// internal Collection<PathInfo> ResolvePaths( string[] pathsToResolve, bool allowNonexistingPaths, bool allowEmptyResult, CmdletProviderContext currentCommandContext) { Collection<PathInfo> results = new Collection<PathInfo>(); foreach (string path in pathsToResolve) { bool pathNotFound = false; bool filtersHidPath = false; ErrorRecord pathNotFoundErrorRecord = null; try { // First resolve each of the paths Collection<PathInfo> pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath( path, currentCommandContext); if (pathInfos.Count == 0) { pathNotFound = true; // If the item simply did not exist, // we would have got an ItemNotFoundException. // If we get here, it's because the filters // excluded the file. if (!currentCommandContext.SuppressWildcardExpansion) { filtersHidPath = true; } } foreach (PathInfo pathInfo in pathInfos) { results.Add(pathInfo); } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); } catch (ItemNotFoundException pathNotFoundException) { pathNotFound = true; pathNotFoundErrorRecord = new ErrorRecord(pathNotFoundException.ErrorRecord, pathNotFoundException); } if (pathNotFound) { if (allowNonexistingPaths && (!filtersHidPath) && (currentCommandContext.SuppressWildcardExpansion || (!WildcardPattern.ContainsWildcardCharacters(path)))) { ProviderInfo provider = null; PSDriveInfo drive = null; string unresolvedPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath( path, currentCommandContext, out provider, out drive); PathInfo pathInfo = new PathInfo( drive, provider, unresolvedPath, SessionState); results.Add(pathInfo); } else { if (pathNotFoundErrorRecord == null) { // Detect if the path resolution failed to resolve to a file. String error = StringUtil.Format(NavigationResources.ItemNotFound, Path); Exception e = new Exception(error); pathNotFoundErrorRecord = new ErrorRecord( e, "ItemNotFound", ErrorCategory.ObjectNotFound, Path); } WriteError(pathNotFoundErrorRecord); } } } return results; } // ResolvePaths
internal void PushCurrentLocation(string stackName) { if (string.IsNullOrEmpty(stackName)) { stackName = this.defaultStackName; } ProviderInfo provider = this.CurrentDrive.Provider; string mshQualifiedPath = LocationGlobber.GetMshQualifiedPath(this.CurrentDrive.CurrentLocation, this.CurrentDrive); PathInfo item = new PathInfo(this.CurrentDrive, provider, mshQualifiedPath, new SessionState(this)); tracer.WriteLine("Pushing drive: {0} directory: {1}", new object[] { this.CurrentDrive.Name, mshQualifiedPath }); Stack<PathInfo> stack = null; if (!this.workingLocationStack.TryGetValue(stackName, out stack)) { stack = new Stack<PathInfo>(); this.workingLocationStack[stackName] = stack; } stack.Push(item); }
internal ResolvedPscxPathImpl(PathInfo resolvedPath, string sourcePath) : this(resolvedPath) { _sourcePath = sourcePath; // save original source path, e.g. "*.txt" }
protected override void ProcessRecord() { PathInfo pathInfo; List<PSDriveInfo> matchingDrives; string parameterSetName = base.ParameterSetName; string str = parameterSetName; if (parameterSetName != null) { if (str == "Location") { pathInfo = null; if (this.PSDrive == null || (int)this.PSDrive.Length <= 0) { if ((this.PSDrive == null || (int)this.PSDrive.Length == 0) && this.PSProvider != null && (int)this.PSProvider.Length > 0) { string[] pSProvider = this.PSProvider; for (int i = 0; i < (int)pSProvider.Length; i++) { string str1 = pSProvider[i]; bool flag = WildcardPattern.ContainsWildcardCharacters(str1); if (!flag) { try { base.SessionState.Provider.GetOne(str1); } catch (ProviderNotFoundException providerNotFoundException1) { ProviderNotFoundException providerNotFoundException = providerNotFoundException1; ErrorRecord errorRecord = new ErrorRecord(providerNotFoundException, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, str1); base.WriteError(errorRecord); goto Label0; } } foreach (ProviderInfo all in base.SessionState.Provider.GetAll()) { if (!all.IsMatch(str1)) { continue; } try { base.WriteObject(base.SessionState.Path.CurrentProviderLocation(all.FullName)); } catch (ProviderNotFoundException providerNotFoundException3) { ProviderNotFoundException providerNotFoundException2 = providerNotFoundException3; base.WriteError(new ErrorRecord(providerNotFoundException2.ErrorRecord, providerNotFoundException2)); } catch (DriveNotFoundException driveNotFoundException1) { DriveNotFoundException driveNotFoundException = driveNotFoundException1; if (!flag) { base.WriteError(new ErrorRecord(driveNotFoundException.ErrorRecord, driveNotFoundException)); } } } Label0: continue; } return; } else { base.WriteObject(base.SessionState.Path.CurrentLocation); return; } } else { string[] pSDrive = this.PSDrive; for (int j = 0; j < (int)pSDrive.Length; j++) { string str2 = pSDrive[j]; matchingDrives = null; try { matchingDrives = base.GetMatchingDrives(str2, this.PSProvider, null); goto Label1; } catch (DriveNotFoundException driveNotFoundException3) { DriveNotFoundException driveNotFoundException2 = driveNotFoundException3; ErrorRecord errorRecord1 = new ErrorRecord(driveNotFoundException2, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, str2); base.WriteError(errorRecord1); } catch (ProviderNotFoundException providerNotFoundException5) { ProviderNotFoundException providerNotFoundException4 = providerNotFoundException5; ErrorRecord errorRecord2 = new ErrorRecord(providerNotFoundException4, "GetLocationNoMatchingProvider", ErrorCategory.ObjectNotFound, this.PSProvider); base.WriteError(errorRecord2); } catch (ArgumentException argumentException1) { ArgumentException argumentException = argumentException1; ErrorRecord errorRecord3 = new ErrorRecord(argumentException, "GetLocationNoMatchingDrive", ErrorCategory.ObjectNotFound, str2); base.WriteError(errorRecord3); } } return; } } else { if (str == "Stack") { if (this.stackNames == null) { try { base.WriteObject(base.SessionState.Path.LocationStack(null), false); } catch (PSArgumentException pSArgumentException1) { PSArgumentException pSArgumentException = pSArgumentException1; base.WriteError(new ErrorRecord(pSArgumentException.ErrorRecord, pSArgumentException)); } } else { string[] strArrays = this.stackNames; for (int k = 0; k < (int)strArrays.Length; k++) { string str3 = strArrays[k]; try { base.WriteObject(base.SessionState.Path.LocationStack(str3), false); } catch (PSArgumentException pSArgumentException3) { PSArgumentException pSArgumentException2 = pSArgumentException3; base.WriteError(new ErrorRecord(pSArgumentException2.ErrorRecord, pSArgumentException2)); } } return; } } else { return; } } } return; Label1: List<PSDriveInfo>.Enumerator enumerator = matchingDrives.GetEnumerator(); try { while (enumerator.MoveNext()) { PSDriveInfo current = enumerator.Current; try { string driveQualifiedPath = LocationGlobber.GetDriveQualifiedPath(current.CurrentLocation, current); pathInfo = new PathInfo(current, current.Provider, driveQualifiedPath, base.SessionState); base.WriteObject(pathInfo); } catch (ProviderNotFoundException providerNotFoundException7) { ProviderNotFoundException providerNotFoundException6 = providerNotFoundException7; base.WriteError(new ErrorRecord(providerNotFoundException6.ErrorRecord, providerNotFoundException6)); } } return; } finally { enumerator.Dispose(); } }