Ejemplo n.º 1
0
        /// <summary>
        /// Check if string is prefixed by psdrive, if so, expand it if filesystem path.
        /// </summary>
        /// <param name="path">The potential PSPath to resolve.</param>
        /// <param name="context">The current ExecutionContext.</param>
        /// <returns>Resolved PSPath if applicable otherwise the original path</returns>
        internal static string ResolvePath(string path, ExecutionContext context)
        {
            if (ExperimentalFeature.IsEnabled("PSNativePSPathResolution"))
            {
#if !UNIX
                // on Windows, we need to expand ~ to point to user's home path
                if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal))
                {
                    try
                    {
                        ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName);
                        return(new StringBuilder(fileSystemProvider.Home)
                               .Append(path.Substring(1))
                               .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
                               .ToString());
                    }
                    catch
                    {
                        return(path);
                    }
                }

                // check if the driveName is an actual disk drive on Windows, if so, no expansion
                if (path.Length >= 2 && path[1] == ':')
                {
                    foreach (var drive in DriveInfo.GetDrives())
                    {
                        if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase))
                        {
                            return(path);
                        }
                    }
                }
#endif

                if (path.Contains(':'))
                {
                    LocationGlobber globber = new LocationGlobber(context.SessionState);
                    try
                    {
                        ProviderInfo providerInfo;

                        // replace the argument with resolved path if it's a filesystem path
                        string pspath = globber.GetProviderPath(path, out providerInfo);
                        if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                        {
                            path = pspath;
                        }
                    }
                    catch
                    {
                        // if it's not a provider path, do nothing
                    }
                }
            }

            return(path);
        }
Ejemplo n.º 2
0
        private void ResolveCurrentDirectoryInLookupPaths()
        {
            SortedList           list               = new SortedList();
            int                  num                = 0;
            string               fileSystem         = this._context.ProviderNames.FileSystem;
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            bool                 flag               = ((engineSessionState.CurrentDrive != null) && engineSessionState.CurrentDrive.Provider.NameEquals(fileSystem)) && engineSessionState.IsProviderLoaded(fileSystem);
            string               currentDirectory   = Environment.CurrentDirectory;

            if (string.IsNullOrEmpty(currentDirectory) && OSHelper.IsUnix)
            {
                currentDirectory = "/";
            }

            LocationGlobber locationGlobber = this._context.LocationGlobber;

            foreach (int num2 in this.lookupPaths.IndexOfRelativePath())
            {
                string item         = null;
                string providerPath = null;
                CommandDiscovery.discoveryTracer.WriteLine("Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...", new object[] { this.lookupPaths[num2] });
                if (flag)
                {
                    ProviderInfo provider = null;
                    try
                    {
                        providerPath = locationGlobber.GetProviderPath(this.lookupPaths[num2], out provider);
                    }
                    catch (ProviderInvocationException exception)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'", new object[] { this.lookupPaths[num2], exception.Message });
                    }
                    catch (InvalidOperationException)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not resolve a home directory for the provider", new object[] { this.lookupPaths[num2] });
                    }
                    if (!string.IsNullOrEmpty(providerPath))
                    {
                        CommandDiscovery.discoveryTracer.TraceError("The relative path resolved to: {0}", new object[] { providerPath });
                        item = providerPath;
                    }
                    else
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path was not a file system path. {0}", new object[] { this.lookupPaths[num2] });
                    }
                }
                else
                {
                    CommandDiscovery.discoveryTracer.TraceWarning("The current drive is not set, using the process current directory: {0}", new object[] { currentDirectory });
                    item = currentDirectory;
                }
                if (item != null)
                {
                    int index = this.lookupPaths.IndexOf(item);
                    if (index == -1)
                    {
                        this.lookupPaths[num2] = item;
                    }
                    else if (index > num2)
                    {
                        list.Add(num++, index);
                        this.lookupPaths[num2] = item;
                    }
                    else
                    {
                        list.Add(num++, num2);
                    }
                }
                else
                {
                    list.Add(num++, num2);
                }
            }
            for (int i = list.Count; i > 0; i--)
            {
                int num5 = (int)list[i - 1];
                this.lookupPaths.RemoveAt(num5);
            }
        }
        private void ResolveCurrentDirectoryInLookupPaths()
        {
            var indexesToRemove  = new SortedDictionary <int, int>();
            int removalListCount = 0;

            string fileSystemProviderName = _context.ProviderNames.FileSystem;

            SessionStateInternal sessionState = _context.EngineSessionState;

            // Only use the directory if it gets resolved by the FileSystemProvider
            bool isCurrentDriveValid =
                sessionState.CurrentDrive != null &&
                sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) &&
                sessionState.IsProviderLoaded(fileSystemProviderName);

            string environmentCurrentDirectory = Directory.GetCurrentDirectory();

            LocationGlobber pathResolver = _context.LocationGlobber;

            // Loop through the relative paths and resolve them

            foreach (int index in _lookupPaths.IndexOfRelativePath())
            {
                string?resolvedDirectory = null;
                string?resolvedPath      = null;

                CommandDiscovery.discoveryTracer.WriteLine(
                    "Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...",
                    _lookupPaths[index]);

                if (isCurrentDriveValid)
                {
                    try
                    {
                        ProviderInfo provider;
                        resolvedPath =
                            pathResolver.GetProviderPath(
                                _lookupPaths[index],
                                out provider);
                    }
                    catch (ProviderInvocationException providerInvocationException)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'",
                            _lookupPaths[index],
                            providerInvocationException.Message);
                    }
                    catch (InvalidOperationException)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path '{0}', could not resolve a home directory for the provider",
                            _lookupPaths[index]);
                    }

                    // Note, if the directory resolves to multiple paths, only the first is used.

                    if (!string.IsNullOrEmpty(resolvedPath))
                    {
                        CommandDiscovery.discoveryTracer.TraceError(
                            "The relative path resolved to: {0}",
                            resolvedPath);

                        resolvedDirectory = resolvedPath;
                    }
                    else
                    {
                        CommandDiscovery.discoveryTracer.WriteLine(
                            "The relative path was not a file system path. {0}",
                            _lookupPaths[index]);
                    }
                }
                else
                {
                    CommandDiscovery.discoveryTracer.TraceWarning(
                        "The current drive is not set, using the process current directory: {0}",
                        environmentCurrentDirectory);

                    resolvedDirectory = environmentCurrentDirectory;
                }

                // If we successfully resolved the path, make sure it is unique. Remove
                // any duplicates found after the first occurrence of the path.

                if (resolvedDirectory != null)
                {
                    int existingIndex = _lookupPaths.IndexOf(resolvedDirectory);

                    if (existingIndex != -1)
                    {
                        if (existingIndex > index)
                        {
                            // The relative path index is less than the explicit path,
                            // so remove the explicit path.

                            indexesToRemove.Add(removalListCount++, existingIndex);
                            _lookupPaths[index] = resolvedDirectory;
                        }
                        else
                        {
                            // The explicit path index is less than the relative path
                            // index, so remove the relative path.

                            indexesToRemove.Add(removalListCount++, index);
                        }
                    }
                    else
                    {
                        // Change the relative path to the resolved path.

                        _lookupPaths[index] = resolvedDirectory;
                    }
                }
                else
                {
                    // The directory couldn't be resolved so remove it from the
                    // lookup paths.

                    indexesToRemove.Add(removalListCount++, index);
                }
            }

            // Now remove all the duplicates starting from the back of the collection.
            // As each element is removed, elements that follow are moved up to occupy
            // the emptied index.

            for (int removeIndex = indexesToRemove.Count; removeIndex > 0; --removeIndex)
            {
                int indexToRemove = indexesToRemove[removeIndex - 1];
                _lookupPaths.RemoveAt(indexToRemove);
            }
        }
Ejemplo n.º 4
0
        private void ResolveCurrentDirectoryInLookupPaths()
        {
            SortedList           sortedList         = new SortedList();
            int                  num1               = 0;
            string               fileSystem         = this._context.ProviderNames.FileSystem;
            SessionStateInternal engineSessionState = this._context.EngineSessionState;
            bool                 flag               = engineSessionState.CurrentDrive != (PSDriveInfo)null && engineSessionState.CurrentDrive.Provider.NameEquals(fileSystem) && engineSessionState.IsProviderLoaded(fileSystem);
            string               currentDirectory   = Environment.CurrentDirectory;
            LocationGlobber      locationGlobber    = this._context.LocationGlobber;

            foreach (int index in this.lookupPaths.IndexOfRelativePath())
            {
                string str1 = (string)null;
                string str2 = (string)null;
                CommandDiscovery.discoveryTracer.WriteLine("Lookup directory \"{0}\" appears to be a relative path. Attempting resolution...", (object)this.lookupPaths[index]);
                if (flag)
                {
                    ProviderInfo provider = (ProviderInfo)null;
                    try
                    {
                        str2 = locationGlobber.GetProviderPath(this.lookupPaths[index], out provider);
                    }
                    catch (ProviderInvocationException ex)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not be resolved because the provider threw an exception: '{1}'", (object)this.lookupPaths[index], (object)ex.Message);
                    }
                    catch (InvalidOperationException ex)
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path '{0}', could not resolve a home directory for the provider", (object)this.lookupPaths[index]);
                    }
                    if (!string.IsNullOrEmpty(str2))
                    {
                        CommandDiscovery.discoveryTracer.TraceError("The relative path resolved to: {0}", (object)str2);
                        str1 = str2;
                    }
                    else
                    {
                        CommandDiscovery.discoveryTracer.WriteLine("The relative path was not a file system path. {0}", (object)this.lookupPaths[index]);
                    }
                }
                else
                {
                    CommandDiscovery.discoveryTracer.TraceWarning("The current drive is not set, using the process current directory: {0}", (object)currentDirectory);
                    str1 = currentDirectory;
                }
                if (str1 != null)
                {
                    int num2 = this.lookupPaths.IndexOf(str1);
                    if (num2 != -1)
                    {
                        if (num2 > index)
                        {
                            sortedList.Add((object)num1++, (object)num2);
                            this.lookupPaths[index] = str1;
                        }
                        else
                        {
                            sortedList.Add((object)num1++, (object)index);
                        }
                    }
                    else
                    {
                        this.lookupPaths[index] = str1;
                    }
                }
                else
                {
                    sortedList.Add((object)num1++, (object)index);
                }
            }
            for (int count = sortedList.Count; count > 0; --count)
            {
                this.lookupPaths.RemoveAt((int)sortedList[(object)(count - 1)]);
            }
        }