|
| 1 | +// Licensed to Elasticsearch B.V under one or more agreements. |
| 2 | +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. |
| 3 | +// See the LICENSE file in the project root for more information |
| 4 | + |
| 5 | +using System.Collections.ObjectModel; |
| 6 | +using System.IO.Abstractions; |
| 7 | +using System.Text.RegularExpressions; |
| 8 | +using Elastic.Markdown.IO; |
| 9 | +using Elastic.Markdown.Slices; |
| 10 | +using Microsoft.Extensions.Logging; |
| 11 | + |
| 12 | +namespace Documentation.Mover; |
| 13 | + |
| 14 | +public class Move(IFileSystem readFileSystem, IFileSystem writeFileSystem, DocumentationSet documentationSet, ILoggerFactory loggerFactory) |
| 15 | +{ |
| 16 | + private readonly ILogger _logger = loggerFactory.CreateLogger<Move>(); |
| 17 | + private readonly List<(string filePath, string originalContent, string newContent)> _changes = []; |
| 18 | + private readonly List<LinkModification> _linkModifications = []; |
| 19 | + private const string ChangeFormatString = "Change \e[31m{0}\e[0m to \e[32m{1}\e[0m at \e[34m{2}:{3}:{4}\e[0m"; |
| 20 | + |
| 21 | + public record LinkModification(string OldLink, string NewLink, string SourceFile, int LineNumber, int ColumnNumber); |
| 22 | + |
| 23 | + |
| 24 | + public ReadOnlyCollection<LinkModification> LinkModifications => _linkModifications.AsReadOnly(); |
| 25 | + |
| 26 | + public async Task<int> Execute(string? source, string? target, bool isDryRun, Cancel ctx = default) |
| 27 | + { |
| 28 | + if (isDryRun) |
| 29 | + _logger.LogInformation("Running in dry-run mode"); |
| 30 | + |
| 31 | + if (!ValidateInputs(source, target)) |
| 32 | + { |
| 33 | + return 1; |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + var sourcePath = Path.GetFullPath(source!); |
| 38 | + var targetPath = Path.GetFullPath(target!); |
| 39 | + |
| 40 | + var sourceContent = await readFileSystem.File.ReadAllTextAsync(sourcePath, ctx); |
| 41 | + |
| 42 | + var markdownLinkRegex = new Regex(@"\[([^\]]*)\]\(((?:\.{0,2}\/)?[^:)]+\.md(?:#[^)]*)?)\)", RegexOptions.Compiled); |
| 43 | + |
| 44 | + var change = Regex.Replace(sourceContent, markdownLinkRegex.ToString(), match => |
| 45 | + { |
| 46 | + var originalPath = match.Value.Substring(match.Value.IndexOf('(') + 1, match.Value.LastIndexOf(')') - match.Value.IndexOf('(') - 1); |
| 47 | + |
| 48 | + var newPath = originalPath; |
| 49 | + var isAbsoluteStylePath = originalPath.StartsWith('/'); |
| 50 | + if (!isAbsoluteStylePath) |
| 51 | + { |
| 52 | + var targetDirectory = Path.GetDirectoryName(targetPath)!; |
| 53 | + var sourceDirectory = Path.GetDirectoryName(sourcePath)!; |
| 54 | + var fullPath = Path.GetFullPath(Path.Combine(sourceDirectory, originalPath)); |
| 55 | + var relativePath = Path.GetRelativePath(targetDirectory, fullPath); |
| 56 | + |
| 57 | + if (originalPath.StartsWith("./") && !relativePath.StartsWith("./")) |
| 58 | + newPath = "./" + relativePath; |
| 59 | + else |
| 60 | + newPath = relativePath; |
| 61 | + } |
| 62 | + var newLink = $"[{match.Groups[1].Value}]({newPath})"; |
| 63 | + var lineNumber = sourceContent.Substring(0, match.Index).Count(c => c == '\n') + 1; |
| 64 | + var columnNumber = match.Index - sourceContent.LastIndexOf('\n', match.Index); |
| 65 | + _linkModifications.Add(new LinkModification( |
| 66 | + match.Value, |
| 67 | + newLink, |
| 68 | + sourcePath, |
| 69 | + lineNumber, |
| 70 | + columnNumber |
| 71 | + )); |
| 72 | + return newLink; |
| 73 | + }); |
| 74 | + |
| 75 | + _changes.Add((sourcePath, sourceContent, change)); |
| 76 | + |
| 77 | + foreach (var (_, markdownFile) in documentationSet.MarkdownFiles) |
| 78 | + { |
| 79 | + await ProcessMarkdownFile( |
| 80 | + sourcePath, |
| 81 | + targetPath, |
| 82 | + markdownFile, |
| 83 | + ctx |
| 84 | + ); |
| 85 | + } |
| 86 | + |
| 87 | + foreach (var (oldLink, newLink, sourceFile, lineNumber, columnNumber) in LinkModifications) |
| 88 | + { |
| 89 | + _logger.LogInformation(string.Format( |
| 90 | + ChangeFormatString, |
| 91 | + oldLink, |
| 92 | + newLink, |
| 93 | + sourceFile == sourcePath && !isDryRun ? targetPath : sourceFile, |
| 94 | + lineNumber, |
| 95 | + columnNumber |
| 96 | + )); |
| 97 | + } |
| 98 | + |
| 99 | + if (isDryRun) |
| 100 | + return 0; |
| 101 | + |
| 102 | + |
| 103 | + try |
| 104 | + { |
| 105 | + foreach (var (filePath, _, newContent) in _changes) |
| 106 | + await writeFileSystem.File.WriteAllTextAsync(filePath, newContent, ctx); |
| 107 | + var targetDirectory = Path.GetDirectoryName(targetPath); |
| 108 | + readFileSystem.Directory.CreateDirectory(targetDirectory!); |
| 109 | + readFileSystem.File.Move(sourcePath, targetPath); |
| 110 | + } |
| 111 | + catch (Exception) |
| 112 | + { |
| 113 | + foreach (var (filePath, originalContent, _) in _changes) |
| 114 | + await writeFileSystem.File.WriteAllTextAsync(filePath, originalContent, ctx); |
| 115 | + writeFileSystem.File.Move(targetPath, sourcePath); |
| 116 | + _logger.LogError("An error occurred while moving files. Reverting changes"); |
| 117 | + throw; |
| 118 | + } |
| 119 | + return 0; |
| 120 | + } |
| 121 | + |
| 122 | + private bool ValidateInputs(string? source, string? target) |
| 123 | + { |
| 124 | + |
| 125 | + if (string.IsNullOrEmpty(source)) |
| 126 | + { |
| 127 | + _logger.LogError("Source path is required"); |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + if (string.IsNullOrEmpty(target)) |
| 132 | + { |
| 133 | + _logger.LogError("Target path is required"); |
| 134 | + return false; |
| 135 | + } |
| 136 | + |
| 137 | + if (!Path.GetExtension(source).Equals(".md", StringComparison.OrdinalIgnoreCase)) |
| 138 | + { |
| 139 | + _logger.LogError("Source path must be a markdown file. Directory paths are not supported yet"); |
| 140 | + return false; |
| 141 | + } |
| 142 | + |
| 143 | + if (!Path.GetExtension(target).Equals(".md", StringComparison.OrdinalIgnoreCase)) |
| 144 | + { |
| 145 | + _logger.LogError("Target path must be a markdown file. Directory paths are not supported yet"); |
| 146 | + return false; |
| 147 | + } |
| 148 | + |
| 149 | + if (!readFileSystem.File.Exists(source)) |
| 150 | + { |
| 151 | + _logger.LogError($"Source file {source} does not exist"); |
| 152 | + return false; |
| 153 | + } |
| 154 | + |
| 155 | + if (readFileSystem.File.Exists(target)) |
| 156 | + { |
| 157 | + _logger.LogError($"Target file {target} already exists"); |
| 158 | + return false; |
| 159 | + } |
| 160 | + |
| 161 | + return true; |
| 162 | + } |
| 163 | + |
| 164 | + private async Task ProcessMarkdownFile( |
| 165 | + string source, |
| 166 | + string target, |
| 167 | + MarkdownFile value, |
| 168 | + Cancel ctx) |
| 169 | + { |
| 170 | + var content = await readFileSystem.File.ReadAllTextAsync(value.FilePath, ctx); |
| 171 | + var currentDir = Path.GetDirectoryName(value.FilePath)!; |
| 172 | + var pathInfo = GetPathInfo(currentDir, source, target); |
| 173 | + var linkPattern = BuildLinkPattern(pathInfo); |
| 174 | + |
| 175 | + if (Regex.IsMatch(content, linkPattern)) |
| 176 | + { |
| 177 | + var newContent = ReplaceLinks(content, linkPattern, pathInfo.absoluteStyleTarget, target, value); |
| 178 | + _changes.Add((value.FilePath, content, newContent)); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private (string relativeSource, string relativeSourceWithDotSlash, string absolutStyleSource, string absoluteStyleTarget) GetPathInfo( |
| 183 | + string currentDir, |
| 184 | + string sourcePath, |
| 185 | + string targetPath |
| 186 | + ) |
| 187 | + { |
| 188 | + var relativeSource = Path.GetRelativePath(currentDir, sourcePath); |
| 189 | + var relativeSourceWithDotSlash = Path.Combine(".", relativeSource); |
| 190 | + var relativeToDocsFolder = Path.GetRelativePath(documentationSet.SourcePath.FullName, sourcePath); |
| 191 | + var absolutStyleSource = $"/{relativeToDocsFolder}"; |
| 192 | + var relativeToDocsFolderTarget = Path.GetRelativePath(documentationSet.SourcePath.FullName, targetPath); |
| 193 | + var absoluteStyleTarget = $"/{relativeToDocsFolderTarget}"; |
| 194 | + return ( |
| 195 | + relativeSource, |
| 196 | + relativeSourceWithDotSlash, |
| 197 | + absolutStyleSource, |
| 198 | + absoluteStyleTarget |
| 199 | + ); |
| 200 | + } |
| 201 | + |
| 202 | + private static string BuildLinkPattern( |
| 203 | + (string relativeSource, string relativeSourceWithDotSlash, string absolutStyleSource, string _) pathInfo) => |
| 204 | + $@"\[([^\]]*)\]\((?:{pathInfo.relativeSource}|{pathInfo.relativeSourceWithDotSlash}|{pathInfo.absolutStyleSource})(?:#[^\)]*?)?\)"; |
| 205 | + |
| 206 | + private string ReplaceLinks( |
| 207 | + string content, |
| 208 | + string linkPattern, |
| 209 | + string absoluteStyleTarget, |
| 210 | + string target, |
| 211 | + MarkdownFile value |
| 212 | + ) => |
| 213 | + Regex.Replace( |
| 214 | + content, |
| 215 | + linkPattern, |
| 216 | + match => |
| 217 | + { |
| 218 | + var originalPath = match.Value.Substring(match.Value.IndexOf('(') + 1, match.Value.LastIndexOf(')') - match.Value.IndexOf('(') - 1); |
| 219 | + var anchor = originalPath.Contains('#') |
| 220 | + ? originalPath[originalPath.IndexOf('#')..] |
| 221 | + : ""; |
| 222 | + |
| 223 | + string newLink; |
| 224 | + if (originalPath.StartsWith('/')) |
| 225 | + { |
| 226 | + newLink = $"[{match.Groups[1].Value}]({absoluteStyleTarget}{anchor})"; |
| 227 | + } |
| 228 | + else |
| 229 | + { |
| 230 | + var relativeTarget = Path.GetRelativePath(Path.GetDirectoryName(value.FilePath)!, target); |
| 231 | + newLink = originalPath.StartsWith("./") && !relativeTarget.StartsWith("./") |
| 232 | + ? $"[{match.Groups[1].Value}](./{relativeTarget}{anchor})" |
| 233 | + : $"[{match.Groups[1].Value}]({relativeTarget}{anchor})"; |
| 234 | + } |
| 235 | + |
| 236 | + var lineNumber = content.Substring(0, match.Index).Count(c => c == '\n') + 1; |
| 237 | + var columnNumber = match.Index - content.LastIndexOf('\n', match.Index); |
| 238 | + _linkModifications.Add(new LinkModification( |
| 239 | + match.Value, |
| 240 | + newLink, |
| 241 | + value.SourceFile.FullName, |
| 242 | + lineNumber, |
| 243 | + columnNumber |
| 244 | + )); |
| 245 | + return newLink; |
| 246 | + }); |
| 247 | +} |
0 commit comments