Ejemplo n.º 1
0
        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);
        }
Ejemplo n.º 2
0
        public static Path CalculateFullPath(Path currentLocation, Path changeCommand)
        {
            changeCommand = (changeCommand ?? string.Empty).NormalizeSlashes();
            currentLocation = currentLocation.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();
        }
Ejemplo n.º 3
0
        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));
            }
        }
Ejemplo n.º 4
0
 private void WritePath(Path path)
 {
     WriteObject(path.ToString());
 }
Ejemplo n.º 5
0
        private void LoadManifestModule(PSModuleInfo moduleInfo, Path path)
        {
            // Load the manifest (hashtable). We use a isolated SessionState to not affect the existing one
            var isolatedSessionState = new SessionState(_executionContext.SessionStateGlobal);
            var res = ExecuteScriptInSessionState(path.ToString(), isolatedSessionState);
            if (res.Count != 1 || !(res[0].BaseObject is Hashtable))
            {
                var msg = "The module manifest is invalid as it doesn't simply define a hashtable. ";
                throw new PSArgumentException(msg, "Modules_InvalidManifest", ErrorCategory.InvalidOperation);
            }
            var manifest = (Hashtable)res[0].BaseObject;

            // Load the metadata into the PSModuleInfo (simply overwrite if existing due to nesting)
            try
            {
                moduleInfo.SetMetadata(manifest);
            } 
            catch (PSInvalidCastException e)
            {                
                var msg = "The module manifest contains invalid data." + Environment.NewLine + e.Message;
                throw new PSInvalidOperationException(msg, "Modules_InvalidManifestData", ErrorCategory.InvalidData, e,
                                                      false);
            }

            // TODO: check and load required assemblies and modules

            // Load RootModule / ModuleToProcess
            LoadManifestRootModule(moduleInfo, manifest);

            // restrict the module exports
            RestrictModuleExportsByManifest(moduleInfo, manifest);
        }
Ejemplo n.º 6
0
 private void LoadScriptModule(PSModuleInfo moduleInfo, Path path)
 {
     // execute the script in the module scope
     // TODO: simply discard the module output?
     ExecuteScriptInSessionState(path.ToString(), moduleInfo.SessionState);
 }
Ejemplo n.º 7
0
 internal string NormalizePath(string path)
 {
     var p = new Path(path).NormalizeSlashes();
     return p.ToString();
 }
Ejemplo n.º 8
0
        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;
        }