Exemple #1
0
        internal static Include Include(string baseDirectory, string culture, string fileName, bool useCulture, IDictionary replace)
        {
            baseDirectory = PSDocumentOption.GetRootedPath(baseDirectory);
            var absolutePath = Path.IsPathRooted(fileName) ? fileName : Path.Combine(baseDirectory, (useCulture ? culture : string.Empty), fileName);
            var result       = new Include
            {
                Path = absolutePath
            };

            if (result.Exists)
            {
                var text = File.ReadAllText(absolutePath);
                if (replace != null && replace.Count > 0)
                {
                    foreach (var key in replace.Keys)
                    {
                        var k = key?.ToString();
                        var v = replace[key]?.ToString();
                        text = text.Replace(k, v);
                    }
                }
                result.Content = text;
            }
            return(result);
        }
Exemple #2
0
 internal PathBuilder(ILogger logger, string basePath, string searchPattern)
 {
     Logger                = logger;
     _Source               = new List <FileInfo>();
     _BasePath             = PSDocumentOption.GetRootedBasePath(basePath);
     _DefaultSearchPattern = searchPattern;
 }
Exemple #3
0
        private Runspace GetRunspace()
        {
            if (_Runspace == null)
            {
                // Get session state
                var state = HostState.CreateSessionState();
                state.LanguageMode = Pipeline.LanguageMode == LanguageMode.FullLanguage ? PSLanguageMode.FullLanguage : PSLanguageMode.ConstrainedLanguage;

                _Runspace = RunspaceFactory.CreateRunspace(state);

                if (Runspace.DefaultRunspace == null)
                {
                    Runspace.DefaultRunspace = _Runspace;
                }

                _Runspace.Open();
                _Runspace.SessionStateProxy.PSVariable.Set(new HostState.PSDocsVariable());
                _Runspace.SessionStateProxy.PSVariable.Set(new HostState.InstanceNameVariable());
                _Runspace.SessionStateProxy.PSVariable.Set(new HostState.TargetObjectVariable());
                _Runspace.SessionStateProxy.PSVariable.Set(new HostState.InputObjectVariable());
                _Runspace.SessionStateProxy.PSVariable.Set(new HostState.DocumentVariable());
                _Runspace.SessionStateProxy.PSVariable.Set("ErrorActionPreference", ActionPreference.Continue);
                _Runspace.SessionStateProxy.PSVariable.Set("WarningPreference", ActionPreference.Continue);
                _Runspace.SessionStateProxy.PSVariable.Set("VerbosePreference", ActionPreference.Continue);
                _Runspace.SessionStateProxy.PSVariable.Set("DebugPreference", ActionPreference.Continue);
                _Runspace.SessionStateProxy.Path.SetLocation(PSDocumentOption.GetWorkingPath());
            }
            return(_Runspace);
        }
 private static TextReader ReadAsReader(PSObject sourceObject, out InputFileInfo sourceInfo)
 {
     sourceInfo = null;
     if (sourceObject.BaseObject is string)
     {
         return(new StringReader(sourceObject.BaseObject.ToString()));
     }
     else if (sourceObject.BaseObject is InputFileInfo inputFileInfo)
     {
         sourceInfo = inputFileInfo;
         return(new StreamReader(inputFileInfo.FullName));
     }
     else if (sourceObject.BaseObject is FileInfo fileInfo)
     {
         sourceInfo = new InputFileInfo(PSDocumentOption.GetRootedBasePath(""), fileInfo.FullName);
         return(new StreamReader(fileInfo.FullName));
     }
     else
     {
         var uri = sourceObject.BaseObject as Uri;
         sourceInfo = new InputFileInfo(null, uri.ToString());
         using (var webClient = new WebClient())
         {
             return(new StringReader(webClient.DownloadString(uri)));
         }
     }
 }
Exemple #5
0
        public MarkdownProcessorContext(PSDocumentOption option, Document document)
        {
            Option   = option;
            Document = document;

            Builder = new StringBuilder();
        }
 internal MarkdownProcessorContext(PSDocumentOption option, Document document)
 {
     Option   = option;
     Document = document;
     Builder  = new StringBuilder();
     _Ending  = LineEnding.None;
 }
Exemple #7
0
        public static IGetPipelineBuilder Get(Source[] source, PSDocumentOption option, PSCmdlet commandRuntime, EngineIntrinsics executionContext)
        {
            var hostContext = new HostContext(commandRuntime, executionContext);
            var builder     = new GetPipelineBuilder(source, hostContext);

            builder.Configure(option);
            return(builder);
        }
Exemple #8
0
        public static SourcePipelineBuilder Source(PSDocumentOption option, PSCmdlet commandRuntime, EngineIntrinsics executionContext)
        {
            var hostContext = new HostContext(commandRuntime, executionContext);
            var builder     = new SourcePipelineBuilder(hostContext);

            //builder.Configure(option);
            return(builder);
        }
Exemple #9
0
 internal PipelineBuilderBase(Source[] source, HostContext hostContext)
 {
     Option        = new PSDocumentOption();
     Source        = source;
     Writer        = new HostPipelineWriter(hostContext);
     ShouldProcess = hostContext == null ? EmptyShouldProcess : hostContext.ShouldProcess;
     OutputVisitor = (o, enumerate) => WriteToString(o, enumerate, Writer);
 }
Exemple #10
0
 protected PathBuilder(IPipelineWriter logger, string basePath, string searchPattern, PathFilter filter)
 {
     _Logger               = logger;
     _Files                = new List <InputFileInfo>();
     _Paths                = new HashSet <string>();
     _BasePath             = NormalizePath(PSDocumentOption.GetRootedBasePath(basePath));
     _DefaultSearchPattern = searchPattern;
     _GlobalFilter         = filter;
 }
Exemple #11
0
 private void ConfigureCulture()
 {
     if (Option.Output.Culture == null || Option.Output.Culture.Length == 0)
     {
         // Fallback to current culture
         var current = PSDocumentOption.GetCurrentCulture();
         Option.Output.Culture = new string[] { current.Name };
     }
 }
Exemple #12
0
 public PipelineContext(PSDocumentOption option, IPipelineWriter writer, Action <IDocumentResult, bool> _Output, InstanceNameBinder instanceNameBinder)
 {
     Option             = option;
     LanguageMode       = option.Execution.LanguageMode.GetValueOrDefault(ExecutionOption.Default.LanguageMode.Value);
     Filter             = DocumentFilter.Create(Option.Document.Include, Option.Document.Tag);
     Writer             = writer;
     InstanceNameBinder = instanceNameBinder;
     _OutputVisitor     = _Output;
 }
Exemple #13
0
        public override void Process(RunspaceContext context, IEnumerable input)
        {
            var culture    = context.Builder.Document.Culture;
            var rootedPath = PSDocumentOption.GetRootedPath(context.Pipeline.Option.Output.Path);
            var outputPath = !string.IsNullOrEmpty(culture) && context.Pipeline.Option.Output?.Culture?.Length > 1 ?
                             Path.Combine(rootedPath, culture) : rootedPath;

            context.DocumentContext.InstanceName = context.Builder.Document.Name;
            context.DocumentContext.OutputPath   = outputPath;
        }
Exemple #14
0
        private static PSDocumentOption GetOption(string[] name = null)
        {
            var option = new PSDocumentOption();

            if (name != null && name.Length > 0)
            {
                option.Document.Include = name;
            }
            return(option);
        }
Exemple #15
0
 internal DocumentResult(DocumentContext documentContext, string markdown)
 {
     _Markdown    = markdown;
     InstanceName = documentContext.InstanceName;
     Culture      = documentContext.Culture;
     OutputPath   = PSDocumentOption.GetRootedPath(documentContext.OutputPath);
     FullName     = GetFullName();
     Metadata     = documentContext.Metadata;
     Data         = documentContext.Data;
 }
        public virtual IPipelineBuilder Configure(PSDocumentOption option)
        {
            if (option == null)
            {
                return(this);
            }

            Option.Output = new OutputOption(option.Output);
            return(this);
        }
Exemple #17
0
        private static PSDocumentOption GetOption(string[] name = null)
        {
            var option = new PSDocumentOption();

            if (name != null && name.Length > 0)
            {
                option.Document.Include = name;
            }
            option.Output.Culture = new string[] { "en-US" };
            return(option);
        }
Exemple #18
0
        public IDocumentResult Process(PSDocumentOption option, Document document)
        {
            if (document == null)
            {
                return(null);
            }

            var name    = document.Name;
            var culture = document.Culture;
            var context = new MarkdownProcessorContext(option, document);

            Document(context);
            return(new DocumentResult(name, culture, markdown: context.GetString()));
        }
Exemple #19
0
        private void ConfigureCulture()
        {
            if (Option.Output.Culture == null || Option.Output.Culture.Length == 0)
            {
                // Fallback to current culture
                var current = PSDocumentOption.GetCurrentCulture();
                if (current == null || string.IsNullOrEmpty(current.Name))
                {
                    return;
                }

                Option.Output.Culture = new string[] { current.Name };
            }
        }
Exemple #20
0
        private void ProcessTemplateFile(string templateFile)
        {
            try
            {
                var rootedTemplateFile = PSDocumentOption.GetRootedPath(templateFile);

                // Check if metadata property exists
                if (!TryTemplateFile(rootedTemplateFile, out string version, out JObject metadata))
                {
                    return;
                }

                var templateLink = new TemplateLink(rootedTemplateFile, version);

                // Populate remaining properties
                if (TryStringProperty(metadata, PROPERTYNAME_NAME, out string name))
                {
                    templateLink.Name = name;
                }

                if (TryStringProperty(metadata, PROPERTYNAME_DESCRIPTION, out string description))
                {
                    templateLink.Description = description;
                }

                if (TryMetadata(metadata, out Hashtable meta))
                {
                    templateLink.Metadata = meta;
                }

                // var pso = PSObject.AsPSObject(templateLink);
                // var instanceNameProp = new PSNoteProperty("InstanceName", string.Concat(templateLink.Name, "_v", templateLink.Version.Major));
                // pso.Members.Add(new PSMemberSet("PSDocs", new PSMemberInfo[] { instanceNameProp }));

                Writer.WriteObject(templateLink, false);
            }
            catch (InvalidOperationException ex)
            {
                Writer.WriteError(ex, nameof(InvalidOperationException), ErrorCategory.InvalidOperation, templateFile);
            }
            catch (FileNotFoundException ex)
            {
                Writer.WriteError(ex, nameof(FileNotFoundException), ErrorCategory.ObjectNotFound, templateFile);
            }
            catch (PipelineException ex)
            {
                Writer.WriteError(ex, nameof(PipelineException), ErrorCategory.WriteError, templateFile);
            }
        }
Exemple #21
0
        public virtual IPipelineBuilder Configure(PSDocumentOption option)
        {
            Option.Document  = DocumentOption.Combine(option.Document, DocumentOption.Default);
            Option.Execution = ExecutionOption.Combine(option.Execution, ExecutionOption.Default);
            Option.Markdown  = MarkdownOption.Combine(option.Markdown, MarkdownOption.Default);
            Option.Output    = OutputOption.Combine(option.Output, OutputOption.Default);

            if (!string.IsNullOrEmpty(Option.Output.Path))
            {
                OutputVisitor = (o, enumerate) => WriteToFile(o, Option, Writer, ShouldProcess);
            }

            ConfigureCulture();
            return(this);
        }
Exemple #22
0
        public static PSDocsContext Create(PSDocumentOption option, string[] name, string[] tag, string outputPath)
        {
            var actualPath = outputPath;

            if (!Path.IsPathRooted(actualPath))
            {
                actualPath = Path.Combine(PSDocumentOption.GetWorkingPath(), outputPath);
            }

            return(new PSDocsContext
            {
                Option = option,
                Filter = DocumentFilter.Create(name, tag),
                OutputPath = actualPath
            });
        }
Exemple #23
0
        public void InputPath(string[] path)
        {
            if (path == null || path.Length == 0)
            {
                return;
            }

            var basePath = PSDocumentOption.GetWorkingPath();
            var filter   = PathFilterBuilder.Create(basePath, Option.Input.PathIgnore);

            filter.UseGitIgnore();

            var builder = new InputPathBuilder(Writer, basePath, "*", filter.Build());

            builder.Add(path);
            _InputPath = builder.Build();
        }
Exemple #24
0
 internal InputFileInfo(string basePath, string path)
 {
     if (path.IsUri())
     {
         FullName = path;
         IsUrl    = true;
         return;
     }
     path          = PSDocumentOption.GetRootedPath(path);
     FullName      = path;
     BasePath      = basePath;
     Name          = System.IO.Path.GetFileName(path);
     Extension     = System.IO.Path.GetExtension(path);
     DirectoryName = System.IO.Path.GetDirectoryName(path);
     Path          = ExpressionHelpers.NormalizePath(basePath, FullName);
     _TargetType   = string.IsNullOrEmpty(Extension) ? System.IO.Path.GetFileNameWithoutExtension(path) : Extension;
 }
Exemple #25
0
        public static Include Include(string baseDirectory, string culture, string fileName, bool useCulture)
        {
            baseDirectory = PSDocumentOption.GetRootedPath(baseDirectory);
            var absolutePath = Path.IsPathRooted(fileName) ? fileName : Path.Combine(baseDirectory, (useCulture ? culture : string.Empty), fileName);

            if (!File.Exists(absolutePath))
            {
                throw new FileNotFoundException(PSDocsResources.IncludeNotFound, absolutePath);
            }

            var text = File.ReadAllText(absolutePath);

            return(new Include
            {
                Path = absolutePath,
                Content = text,
            });
        }
Exemple #26
0
        public static Include Include(string baseDirectory, string culture, string fileName, bool useCulture)
        {
            var absolutePath = Path.IsPathRooted(fileName) ? fileName : Path.Combine(baseDirectory, (useCulture ? culture : string.Empty), fileName);

            if (!Path.IsPathRooted(absolutePath))
            {
                absolutePath = Path.Combine(PSDocumentOption.GetWorkingPath(), absolutePath);
            }

            if (!File.Exists(absolutePath))
            {
                throw new FileNotFoundException("The included file was not found.", absolutePath);
            }

            return(new Include
            {
                Path = absolutePath
            });
        }
Exemple #27
0
        private SourceFile[] GetFiles(string path, string helpPath, string moduleName = null)
        {
            var result     = new List <SourceFile>();
            var rootedPath = PSDocumentOption.GetRootedPath(path);
            var extension  = Path.GetExtension(rootedPath);

            if (extension == ".ps1" || extension == ".yaml" || extension == ".yml")
            {
                if (!File.Exists(rootedPath))
                {
                    throw new FileNotFoundException(PSDocsResources.SourceNotFound, rootedPath);
                }

                if (helpPath == null)
                {
                    helpPath = Path.GetDirectoryName(rootedPath);
                }

                result.Add(new SourceFile(rootedPath, null, GetSourceType(rootedPath), helpPath));
            }
            else if (System.IO.Directory.Exists(rootedPath))
            {
                var files = System.IO.Directory.EnumerateFiles(rootedPath, "*.Doc.*", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    if (Include(file))
                    {
                        if (helpPath == null)
                        {
                            helpPath = Path.GetDirectoryName(file);
                        }

                        result.Add(new SourceFile(file, moduleName, GetSourceType(file), helpPath));
                    }
                }
            }
            else
            {
                return(null);
            }
            return(result.ToArray());
        }
Exemple #28
0
        private static void WriteToFile(IDocumentResult result, PSDocumentOption option, IPipelineWriter writer, ShouldProcess shouldProcess)
        {
            var rootedPath = PSDocumentOption.GetRootedPath(option.Output.Path);
            var filePath   = !string.IsNullOrEmpty(result.Culture) && option.Output?.Culture?.Length > 1 ?
                             Path.Combine(rootedPath, result.Culture, result.Name) : Path.Combine(rootedPath, result.Name);
            var parentPath = Directory.GetParent(filePath);

            if (!parentPath.Exists && shouldProcess(target: parentPath.FullName, action: PSDocsResources.ShouldCreatePath))
            {
                Directory.CreateDirectory(path: parentPath.FullName);
            }
            if (shouldProcess(target: rootedPath, action: PSDocsResources.ShouldWriteFile))
            {
                var encoding = GetEncoding(option.Markdown.Encoding.Value);
                File.WriteAllText(filePath, result.ToString(), encoding);

                // Write file info instead
                var fileInfo = new FileInfo(filePath);
                writer.WriteObject(fileInfo, false);
            }
        }
Exemple #29
0
        public string Process(PSDocumentOption option, Document document)
        {
            if (document == null)
            {
                return(string.Empty);
            }

            var context = new MarkdownProcessorContext(option, document);

            Document(context);

            context.Builder.Remove(context.Builder.Length - 2, 2);
            var result = context.Builder.ToString();

            if (string.IsNullOrEmpty(result))
            {
                result = null;
            }

            return(result);
        }
Exemple #30
0
        private static void WriteToFile(IDocumentResult result, PSDocumentOption option, IPipelineWriter writer, ShouldProcess shouldProcess)
        {
            // Calculate paths
            var fileName   = string.Concat(result.InstanceName, result.Extension);
            var outputPath = PSDocumentOption.GetRootedPath(result.OutputPath);
            var filePath   = Path.Combine(outputPath, fileName);
            var parentPath = Directory.GetParent(filePath);

            if (!parentPath.Exists && shouldProcess(target: parentPath.FullName, action: PSDocsResources.ShouldCreatePath))
            {
                Directory.CreateDirectory(path: parentPath.FullName);
            }

            if (shouldProcess(target: outputPath, action: PSDocsResources.ShouldWriteFile))
            {
                var encoding = GetEncoding(option.Markdown.Encoding.Value);
                File.WriteAllText(filePath, result.ToString(), encoding);

                // Write file info instead
                var fileInfo = new FileInfo(filePath);
                writer.WriteObject(fileInfo, false);
            }
        }