- 
                Notifications
    
You must be signed in to change notification settings  - Fork 32
 
          Add docs-builder mv command
          #376
        
          New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Changes from 4 commits
      Commits
    
    
            Show all changes
          
          
            10 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      8d59ed2
              
                Add mv command
              
              
                reakaleek 85d9dac
              
                Add license header
              
              
                reakaleek bc8657e
              
                Also change links in source file
              
              
                reakaleek 2f30eef
              
                ok
              
              
                reakaleek c14e0d9
              
                Add tests
              
              
                reakaleek 2ce89d6
              
                ok
              
              
                reakaleek 882148c
              
                Fix help text
              
              
                reakaleek 6611623
              
                fix
              
              
                reakaleek ff39347
              
                fix
              
              
                reakaleek 65d9f93
              
                Fix
              
              
                reakaleek File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,228 @@ | ||
| // Licensed to Elasticsearch B.V under one or more agreements. | ||
| // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
| // See the LICENSE file in the project root for more information | ||
| 
     | 
||
| using System.IO.Abstractions; | ||
| using System.Text.RegularExpressions; | ||
| using Elastic.Markdown.IO; | ||
| using Microsoft.Extensions.Logging; | ||
| 
     | 
||
| namespace Documentation.Builder.Cli; | ||
| 
     | 
||
| internal class Move(IFileSystem fileSystem, DocumentationSet documentationSet, ILoggerFactory loggerFactory) | ||
| { | ||
| private readonly ILogger _logger = loggerFactory.CreateLogger<Move>(); | ||
| private readonly List<(string filePath, string originalContent, string newContent)> _changes = []; | ||
| private const string ChangeFormatString = "Change \e[31m{0}\e[0m to \e[32m{1}\e[0m at \e[34m{2}:{3}:{4}\e[0m"; | ||
| 
     | 
||
| public async Task<int> Execute(string? source, string? target, bool isDryRun, Cancel ctx = default) | ||
| { | ||
| if (isDryRun) | ||
| _logger.LogInformation("Running in dry-run mode"); | ||
| 
     | 
||
| if (!ValidateInputs(source, target)) | ||
| { | ||
| return 1; | ||
| } | ||
| 
     | 
||
| var sourcePath = Path.GetFullPath(source!); | ||
| var targetPath = Path.GetFullPath(target!); | ||
| 
     | 
||
| var (_, sourceMarkdownFile) = documentationSet.MarkdownFiles.Single(i => i.Value.FilePath == sourcePath); | ||
| 
     | 
||
| var sourceContent = await fileSystem.File.ReadAllTextAsync(sourceMarkdownFile.FilePath, ctx); | ||
| 
     | 
||
| var markdownLinkRegex = new Regex(@"\[([^\]]*)\]\(((?:\.{0,2}\/)?[^:)]+\.md(?:#[^)]*)?)\)", RegexOptions.Compiled); | ||
| 
     | 
||
| var change = Regex.Replace(sourceContent, markdownLinkRegex.ToString(), match => | ||
| { | ||
| var originalPath = match.Value.Substring(match.Value.IndexOf('(') + 1, match.Value.LastIndexOf(')') - match.Value.IndexOf('(') - 1); | ||
| 
     | 
||
| var newPath = originalPath; | ||
| var isAbsoluteStylePath = originalPath.StartsWith('/'); | ||
| if (!isAbsoluteStylePath) | ||
| { | ||
| var targetDirectory = Path.GetDirectoryName(targetPath)!; | ||
| var sourceDirectory = Path.GetDirectoryName(sourceMarkdownFile.FilePath)!; | ||
| var fullPath = Path.GetFullPath(Path.Combine(sourceDirectory, originalPath)); | ||
| var relativePath = Path.GetRelativePath(targetDirectory, fullPath); | ||
| newPath = relativePath; | ||
| } | ||
| var newLink = $"[{match.Groups[1].Value}]({newPath})"; | ||
| var lineNumber = sourceContent.Substring(0, match.Index).Count(c => c == '\n') + 1; | ||
| var columnNumber = match.Index - sourceContent.LastIndexOf('\n', match.Index); | ||
| _logger.LogInformation( | ||
| string.Format( | ||
| ChangeFormatString, | ||
| match.Value, | ||
| newLink, | ||
| sourceMarkdownFile.SourceFile.FullName, | ||
| lineNumber, | ||
| columnNumber | ||
| ) | ||
| ); | ||
| return newLink; | ||
| }); | ||
| 
     | 
||
| _changes.Add((sourceMarkdownFile.FilePath, sourceContent, change)); | ||
| 
     | 
||
| foreach (var (_, markdownFile) in documentationSet.MarkdownFiles) | ||
| { | ||
| await ProcessMarkdownFile( | ||
| sourcePath, | ||
| targetPath, | ||
| markdownFile, | ||
| ctx | ||
| ); | ||
| } | ||
| 
     | 
||
| if (isDryRun) | ||
| return 0; | ||
| 
     | 
||
| var targetDirectory = Path.GetDirectoryName(targetPath); | ||
| fileSystem.Directory.CreateDirectory(targetDirectory!); | ||
| fileSystem.File.Move(sourcePath, targetPath); | ||
| try | ||
| { | ||
| foreach (var (filePath, _, newContent) in _changes) | ||
| await fileSystem.File.WriteAllTextAsync(filePath, newContent, ctx); | ||
| } | ||
| catch (Exception) | ||
| { | ||
| foreach (var (filePath, originalContent, _) in _changes) | ||
| await fileSystem.File.WriteAllTextAsync(filePath, originalContent, ctx); | ||
| fileSystem.File.Move(targetPath, sourcePath); | ||
| throw; | ||
| } | ||
| return 0; | ||
| } | ||
| 
     | 
||
| private bool ValidateInputs(string? source, string? target) | ||
| { | ||
| 
     | 
||
| if (string.IsNullOrEmpty(source)) | ||
| { | ||
| _logger.LogError("Source path is required"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (string.IsNullOrEmpty(target)) | ||
| { | ||
| _logger.LogError("Target path is required"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (!Path.GetExtension(source).Equals(".md", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| _logger.LogError("Source path must be a markdown file. Directory paths are not supported yet"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (!Path.GetExtension(target).Equals(".md", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| _logger.LogError("Target path must be a markdown file. Directory paths are not supported yet"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (!fileSystem.File.Exists(source)) | ||
| { | ||
| _logger.LogError($"Source file {source} does not exist"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| if (fileSystem.File.Exists(target)) | ||
| { | ||
| _logger.LogError($"Target file {target} already exists"); | ||
| return false; | ||
| } | ||
| 
     | 
||
| return true; | ||
| } | ||
| 
     | 
||
| private async Task ProcessMarkdownFile( | ||
| string source, | ||
| string target, | ||
| MarkdownFile value, | ||
| Cancel ctx) | ||
| { | ||
| var content = await fileSystem.File.ReadAllTextAsync(value.FilePath, ctx); | ||
| var currentDir = Path.GetDirectoryName(value.FilePath)!; | ||
| var pathInfo = GetPathInfo(currentDir, source, target); | ||
| var linkPattern = BuildLinkPattern(pathInfo); | ||
| 
     | 
||
| if (Regex.IsMatch(content, linkPattern)) | ||
| { | ||
| var newContent = ReplaceLinks(content, linkPattern, pathInfo.absoluteStyleTarget, target, value); | ||
| _changes.Add((value.FilePath, content, newContent)); | ||
| } | ||
| } | ||
| 
     | 
||
| private (string relativeSource, string relativeSourceWithDotSlash, string absolutStyleSource, string absoluteStyleTarget) GetPathInfo( | ||
| string currentDir, | ||
| string sourcePath, | ||
| string targetPath | ||
| ) | ||
| { | ||
| var relativeSource = Path.GetRelativePath(currentDir, sourcePath); | ||
| var relativeSourceWithDotSlash = Path.Combine(".", relativeSource); | ||
| var relativeToDocsFolder = Path.GetRelativePath(documentationSet.SourcePath.FullName, sourcePath); | ||
| var absolutStyleSource = $"/{relativeToDocsFolder}"; | ||
| var relativeToDocsFolderTarget = Path.GetRelativePath(documentationSet.SourcePath.FullName, targetPath); | ||
| var absoluteStyleTarget = $"/{relativeToDocsFolderTarget}"; | ||
| return ( | ||
| relativeSource, | ||
| relativeSourceWithDotSlash, | ||
| absolutStyleSource, | ||
| absoluteStyleTarget | ||
| ); | ||
| } | ||
| 
     | 
||
| private static string BuildLinkPattern( | ||
| (string relativeSource, string relativeSourceWithDotSlash, string absolutStyleSource, string _) pathInfo) => | ||
| $@"\[([^\]]*)\]\((?:{pathInfo.relativeSource}|{pathInfo.relativeSourceWithDotSlash}|{pathInfo.absolutStyleSource})(?:#[^\)]*?)?\)"; | ||
| 
     | 
||
| private string ReplaceLinks( | ||
| string content, | ||
| string linkPattern, | ||
| string absoluteStyleTarget, | ||
| string target, | ||
| MarkdownFile value | ||
| ) => | ||
| Regex.Replace( | ||
| content, | ||
| linkPattern, | ||
| match => | ||
| { | ||
| var originalPath = match.Value.Substring(match.Value.IndexOf('(') + 1, match.Value.LastIndexOf(')') - match.Value.IndexOf('(') - 1); | ||
| var anchor = originalPath.Contains('#') | ||
| ? originalPath[originalPath.IndexOf('#')..] | ||
| : ""; | ||
| 
     | 
||
| string newLink; | ||
| if (originalPath.StartsWith("/")) | ||
| { | ||
| // Absolute style link | ||
| newLink = $"[{match.Groups[1].Value}]({absoluteStyleTarget}{anchor})"; | ||
| } | ||
| else | ||
| { | ||
| // Relative link | ||
| var relativeTarget = Path.GetRelativePath(Path.GetDirectoryName(value.FilePath)!, target); | ||
| newLink = $"[{match.Groups[1].Value}]({relativeTarget}{anchor})"; | ||
| } | ||
| 
     | 
||
| var lineNumber = content.Substring(0, match.Index).Count(c => c == '\n') + 1; | ||
| var columnNumber = match.Index - content.LastIndexOf('\n', match.Index); | ||
| _logger.LogInformation( | ||
| string.Format( | ||
| ChangeFormatString, | ||
| match.Value, | ||
| newLink, | ||
| value.SourceFile.FullName, | ||
| lineNumber, | ||
| columnNumber | ||
| ) | ||
| ); | ||
| return newLink; | ||
| }); | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was hoping that we could leverage markdig here.
E.g we parse the document AST and include a linkrewriter parser (or make it part of our existing
DiagnosticLinksParser. To mutate the links.Then we can write the AST back out again as markdown.
markdig supports roundtipping like this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Makes totally sense.
Given the time and the need for it already today/tomorrow, do you think we can leave it this way for now and refactor it in a follow-up using Markdig?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
100%! progress over perfection.