Best Testcontainers-dotnet code snippet using DotNet.Testcontainers.Images.IgnoreFile.Regex
IgnoreFile.cs
Source:IgnoreFile.cs
...5 using System.Linq;6 using System.Text.RegularExpressions;7 using Microsoft.Extensions.Logging;8 /// <summary>9 /// Creates a Regex cache for all ignore patterns.10 /// </summary>11 public class IgnoreFile12 {13 private static readonly ISearchAndReplace<string>[] PrepareRegex = { default(EscapeRegex), default(PrepareRecursiveWildcards), default(PrepareNonRecursiveWildcards), default(PrepareZeroOrOneQuantifier) };14 private readonly IEnumerable<KeyValuePair<Regex, bool>> ignorePatterns;15 /// <summary>16 /// Initializes a new instance of the <see cref="IgnoreFile" /> class.17 /// <see cref="Accepts" /> and <see cref="Denies" /> files.18 /// </summary>19 /// <param name="patterns">A list of strings with ignore patterns.</param>20 /// <param name="logger">The logger.</param>21 public IgnoreFile(IEnumerable<string> patterns, ILogger logger)22 {23 this.ignorePatterns = patterns24 .AsParallel()25 // Keep the order.26 .AsOrdered()27 // Trim each line.28 .Select(line => line.Trim())29 // Remove empty line.30 .Where(line => !string.IsNullOrEmpty(line))31 // Remove comment.32 .Where(line => !line.StartsWith("#", StringComparison.Ordinal))33 // Exclude files and directories.34 .Select(line => line.TrimEnd('/'))35 // Exclude files and directories.36 .Select(line =>37 {38 const string filesAndDirectories = "/*";39 return line.EndsWith(filesAndDirectories, StringComparison.InvariantCulture) ? line.Substring(0, line.Length - filesAndDirectories.Length) : line;40 })41 // Exclude all files and directories (https://github.com/testcontainers/testcontainers-dotnet/issues/618).42 .Select(line => "*".Equals(line, StringComparison.OrdinalIgnoreCase) ? "**" : line)43 // Check if the pattern contains an optional prefix ("!"), which negates the pattern.44 .Aggregate(new List<KeyValuePair<string, bool>>(), (lines, line) =>45 {46 switch (line.First())47 {48 case '!':49 lines.Add(new KeyValuePair<string, bool>(line.Substring(1), true));50 break;51 case '/':52 lines.Add(new KeyValuePair<string, bool>(line.Substring(1), false));53 break;54 default:55 lines.Add(new KeyValuePair<string, bool>(line, false));56 break;57 }58 return lines;59 })60 // Prepare exact and partial patterns.61 .Aggregate(new List<KeyValuePair<string, bool>>(), (lines, line) =>62 {63 var key = line.Key;64 var value = line.Value;65 lines.AddRange(key66 .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)67 .Skip(1)68 .Prepend(key)69 .Select(ignorePattern => new KeyValuePair<string, bool>(ignorePattern, value)));70 return lines;71 })72 // Prepare regular expressions to accept and deny files.73 .Select((ignorePattern, index) =>74 {75 var key = ignorePattern.Key;76 var value = ignorePattern.Value;77 key = PrepareRegex.Aggregate(key, (current, prepareRegex) => prepareRegex.Replace(current));78 key = 0.Equals(index) ? key : $"([\\\\\\/]?({key}\\b|$))";79 key = $"^{key}";80 return new KeyValuePair<string, bool>(key, value);81 })82 // Compile and cache regular expression to increase the performance.83 .Select(ignorePattern =>84 {85 var key = ignorePattern.Key;86 var value = ignorePattern.Value;87 return new KeyValuePair<Regex, bool>(new Regex(key, RegexOptions.Compiled), value);88 })89 .ToArray();90 foreach (var ignorePattern in this.ignorePatterns)91 {92 logger.IgnorePatternAdded(ignorePattern.Key);93 }94 }95 /// <summary>96 /// Replaces all occurrences of a defined pattern.97 /// </summary>98 /// <typeparam name="TToReplace">Type of element that is searched and replaced.</typeparam>99 private interface ISearchAndReplace<TToReplace>100 {101 /// <summary>102 /// Replaces all occurrences of a defined pattern.103 /// </summary>104 /// <param name="input">Is searched and replaced.</param>105 /// <returns>Returns the input with all replaced occurrences of a defined pattern.</returns>106 TToReplace Replace(TToReplace input);107 }108 /// <summary>109 /// Returns true if the file path does not match any ignore pattern.110 /// </summary>111 /// <param name="file">Path to check.</param>112 /// <returns>True if the file path does not match any ignore pattern, otherwise false.</returns>113 public bool Accepts(string file)114 {115 var matches = this.ignorePatterns.AsParallel().Where(ignorePattern => ignorePattern.Key.IsMatch(file)).ToArray();116 return !matches.Any() || matches.Last().Value;117 }118 /// <summary>119 /// Returns true if the file path matches any ignore pattern.120 /// </summary>121 /// <param name="file">Path to check.</param>122 /// <returns>True if the file path matches any ignore pattern, otherwise false.</returns>123 public bool Denies(string file)124 {125 return !this.Accepts(file);126 }127 /// <summary>128 /// Escapes a set of of metacharacters (-, [, ], /, {, }, (, ), +, ?, ., \, ^, $, |) with their \ codes.129 /// </summary>130 private readonly struct EscapeRegex : ISearchAndReplace<string>131 {132 private static readonly Regex Pattern = new Regex("[\\-\\[\\]\\/\\{\\}\\(\\)\\+\\?\\.\\\\\\^\\$\\|]", RegexOptions.Compiled);133 /// <inheritdoc />134 public string Replace(string input)135 {136 return Pattern.Replace(input, "\\$&");137 }138 }139 /// <summary>140 /// Searches and replaces a string with recursive wildcards **.141 /// </summary>142 private readonly struct PrepareRecursiveWildcards : ISearchAndReplace<string>143 {144 /// <inheritdoc />145 public string Replace(string input)146 {...
Regex
Using AI Code Generation
1using System;2using System.Text.RegularExpressions;3using DotNet.Testcontainers.Images;4{5 {6 static void Main(string[] args)7 {8 var ignoreFile = new IgnoreFile();9 var regex = new Regex(@"^#.*$");10 ignoreFile.Add(regex);11 Console.WriteLine($"IgnoreFile contains {ignoreFile.Count} Regex objects");12 }13 }14}15using System;16using System.IO;17using DotNet.Testcontainers.Images;18{19 {20 static void Main(string[] args)21 {22 var ignoreFile = new IgnoreFile();23 var ignoreList = File.ReadAllLines(@"ignore.txt");24 ignoreFile.AddRange(ignoreList);25 Console.WriteLine($"IgnoreFile contains {ignoreFile.Count} Regex objects");26 }27 }28}29using System;30using System.IO;31using DotNet.Testcontainers.Images;32{33 {34 static void Main(string[] args)35 {36 var ignoreFile = new IgnoreFile();37 var ignoreList = File.ReadAllLines(@"ignore.txt");38 ignoreFile.AddRange(ignoreList);39 Console.WriteLine($"IgnoreFile contains {ignoreFile.Count} Regex objects");40 var ignoreFile2 = new IgnoreFile();41 ignoreFile2.AddRange(ignoreFile);42 Console.WriteLine($"IgnoreFile2 contains {ignoreFile2.Count} Regex objects");43 }44 }45}46using System;47using System.IO;48using DotNet.Testcontainers.Images;49{50 {51 static void Main(string[] args)52 {53 var ignoreFile = new IgnoreFile();54 var ignoreList = File.ReadAllLines(@"ignore.txt");55 ignoreFile.AddRange(ignoreList);56 Console.WriteLine($"IgnoreFile contains {ignoreFile.Count} Regex objects");57 var ignoreFile2 = new IgnoreFile();58 ignoreFile2.AddRange(ignoreFile);59 Console.WriteLine($"IgnoreFile2 contains {ignoreFile2.Count} Regex objects");
Regex
Using AI Code Generation
1using System;2using System.Text.RegularExpressions;3using DotNet.Testcontainers.Images;4using DotNet.Testcontainers.Images.Configurations;5{6 {7 public IgnoreFileRegex(IImageConfiguration imageConfiguration) : base(imageConfiguration)8 {9 }10 public override bool IsIgnored(string path)11 {12 var regex = new Regex("^(?!.*\\.(cs|csproj)).*$");13 return regex.IsMatch(path);14 }15 }16}17using System;18using System.Threading.Tasks;19using DotNet.Testcontainers.Containers.Builders;20using DotNet.Testcontainers.Containers.Configurations;21using DotNet.Testcontainers.Containers.Modules;22using DotNet.Testcontainers.Images;23using DotNet.Testcontainers.Tests.Unit.Images;24using Xunit;25{26 {27 public static async Task BuildImageWithDockerfile()28 {29 var dockerfile = new DockerfileBuilder()30 .From("mcr.microsoft.com/dotnet/core/sdk:3.1")31 .Add(".", "/src")32 .Workdir("/src")33 .Run("dotnet build -c Release -o /app")34 .Expose(80)35 .EntryPoint("dotnet", "testcontainers.dll")36 .Build();37 {38 IgnoreFile = new IgnoreFileRegex()39 };40 using (var testcontainer = new TestcontainersBuilder<Testcontainer>()41 .WithDockerfile(dockerfileConfiguration)42 .Build())43 {44 await testcontainer.StartAsync();45 Assert.True(await testcontainer.IsRunningAsync());46 }47 }48 }49}
Regex
Using AI Code Generation
1var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();2var result = ignoreFile.Regex("*.cs");3Console.WriteLine(result);4var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();5var result = ignoreFile.Regex("*.cs");6Console.WriteLine(result);7var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();8var result = ignoreFile.Regex("*.cs");9Console.WriteLine(result);10var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();11var result = ignoreFile.Regex("*.cs");12Console.WriteLine(result);13var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();14var result = ignoreFile.Regex("*.cs");15Console.WriteLine(result);16var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();17var result = ignoreFile.Regex("*.cs");18Console.WriteLine(result);19var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();20var result = ignoreFile.Regex("*.cs");21Console.WriteLine(result);22var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();23var result = ignoreFile.Regex("*.cs");24Console.WriteLine(result);25var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();26var result = ignoreFile.Regex("*.cs");27Console.WriteLine(result);28var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();29var result = ignoreFile.Regex("*.cs");30Console.WriteLine(result);
Regex
Using AI Code Generation
1using DotNet.Testcontainers.Images;2using System.Text.RegularExpressions;3{4 {5 static void Main(string[] args)6 {7 var ignoreFile = new IgnoreFile(@"C:\Users\user\Desktop\ignore.txt");8 var regex = new Regex(@"^/var/lib/rpm/Packages$");9 ignoreFile.Add(regex);10 }11 }12}13using DotNet.Testcontainers.Images;14using System.Text.RegularExpressions;15{16 {17 static void Main(string[] args)18 {19 var ignoreFile = new IgnoreFile(@"C:\Users\user\Desktop\ignore.txt");20 ignoreFile.Add("/var/lib/rpm/Packages");21 }22 }23}24using DotNet.Testcontainers.Images;25using System.Text.RegularExpressions;26{27 {28 static void Main(string[] args)29 {30 var ignoreFile = new IgnoreFile(@"C:\Users\user\Desktop\ignore.txt");31 ignoreFile.Add("/var/lib/rpm/Packages", "sample comment");32 }33 }34}35using DotNet.Testcontainers.Images;36using System.Text.RegularExpressions;37{38 {39 static void Main(string[] args)40 {41 var ignoreFile = new IgnoreFile(@"C:\Users\user\Desktop\ignore.txt");42 ignoreFile.Add("/var/lib/rpm/Packages", "sample comment", true);43 }44 }45}46using DotNet.Testcontainers.Images;47using System.Text.RegularExpressions;48{49 {50 static void Main(string[] args)51 {52 var ignoreFile = new IgnoreFile(@"C:\Users\user\Desktop\ignore.txt");53 ignoreFile.Add("/var/lib/rpm/Packages", "sample comment", true, true);54 }55 }56}57using DotNet.Testcontainers.Images;
Regex
Using AI Code Generation
1using System;2using System.Text.RegularExpressions;3{4 {5 public static string Regex(string pattern)6 {7 return Regex.Escape(pattern)8 .Replace("\\*", ".*")9 .Replace("\\?", ".")10 .Replace("\\[", "[")11 .Replace("\\]", "]");12 }13 }14}15using System;16using System.Text.RegularExpressions;17{18 {19 public static string Regex(string pattern)20 {21 return Regex.Escape(pattern)22 .Replace("\\*", ".*")23 .Replace("\\?", ".")24 .Replace("\\[", "[")25 .Replace("\\]", "]");26 }27 }28}29using System;30using System.Text.RegularExpressions;31{32 {33 public static string Regex(string pattern)34 {35 return Regex.Escape(pattern)36 .Replace("\\*", ".*")37 .Replace("\\?", ".")38 .Replace("\\[", "[")39 .Replace("\\]", "]");40 }41 }42}43using System;44using System.Text.RegularExpressions;45{46 {47 public static string Regex(string pattern)48 {49 return Regex.Escape(pattern)50 .Replace("\\*", ".*")51 .Replace("\\?", ".")52 .Replace("\\[", "[")53 .Replace("\\]", "]");54 }55 }56}57using System;58using System.Text.RegularExpressions;59{60 {61 public static string Regex(string pattern)62 {63 return Regex.Escape(pattern)64 .Replace("\\*", ".*")65 .Replace("\\?", ".")66 .Replace("\\[", "[")67 .Replace("\\]", "]");68 }69 }70}71using System;72using System.Text.RegularExpressions;
Regex
Using AI Code Generation
1using DotNet.Testcontainers.Images;2using System;3using System.Text.RegularExpressions;4{5 {6 static void Main(string[] args)7 {8 Regex regex = new Regex(".*\\.sql");9 IgnoreFile ignoreFile = new IgnoreFile(regex);10 Console.WriteLine("Hello World!");11 }12 }13}
Regex
Using AI Code Generation
1using DotNet.Testcontainers.Images;2using System;3using System.Text.RegularExpressions;4{5 static void Main()6 {7 string pattern = @"^\s*#.*$|^\s*$";8 string input = " #this is a comment ";9 bool match = Regex.Match(input, pattern).Success;10 Console.WriteLine(match);11 }12}
Regex
Using AI Code Generation
1using System.Text.RegularExpressions;2using DotNet.Testcontainers.Images;3using Xunit;4{5 {6 public void IgnoreFileRegexTest()7 {8 var ignoreFile = new IgnoreFile();9 var regex = new Regex(ignoreFile.IgnoreFileRegex);10 Assert.True(regex.IsMatch("Dockerfile"));11 Assert.True(regex.IsMatch(".dockerignore"));12 Assert.True(regex.IsMatch("dockerfile"));13 Assert.True(regex.IsMatch(".dockerignore"));14 Assert.True(regex.IsMatch("Dockerfile.txt"));15 Assert.True(regex.IsMatch(".dockerignore.txt"));16 Assert.True(regex.IsMatch("dockerfile.txt"));17 Assert.True(regex.IsMatch(".dockerignore.txt"));18 Assert.True(regex.IsMatch("Dockerfile.md"));19 Assert.True(regex.IsMatch(".dockerignore.md"));20 Assert.True(regex.IsMatch("dockerfile.md"));21 Assert.True(regex.IsMatch(".dockerignore.md"));22 Assert.True(regex.IsMatch("Dockerfile.html"));23 Assert.True(regex.IsMatch(".dockerignore.html"));24 Assert.True(regex.IsMatch("dockerfile.html"));25 Assert.True(regex.IsMatch(".dockerignore.html"));26 Assert.True(regex.IsMatch("Dockerfile.htm"));27 Assert.True(regex.IsMatch(".dockerignore.htm"));28 Assert.True(regex.IsMatch("dockerfile.htm"));29 Assert.True(regex.IsMatch(".dockerignore.htm"));30 Assert.True(regex.IsMatch("Dockerfile.xml"));31 Assert.True(regex.IsMatch(".dockerignore.xml"));32 Assert.True(regex.IsMatch("dockerfile.xml"));33 Assert.True(regex.IsMatch(".dockerignore.xml"));34 Assert.False(regex.IsMatch("Dockerfile.cs"));35 Assert.False(regex.IsMatch(".dockerignore.cs"));36 Assert.False(regex.IsMatch("dockerfile.cs"));37 Assert.False(regex.IsMatch(".dockerignore.cs"));38 Assert.False(regex.IsMatch("Dockerfile.csproj"));39 Assert.False(regex.IsMatch(".dockerignore.csproj"));40 Assert.False(regex.IsMatch("dockerfile.csproj"));41 Assert.False(regex.IsMatch(".dockerignore.csproj"));42 Assert.False(regex.IsMatch("Dockerfile.sln"));43 Assert.False(regex.IsMatch(".dockerignore.sln"));44 Assert.False(regex.IsMatch("dockerfile.sln"));45 Assert.False(regex.IsMatch(".dockerignore.sln"));46 Assert.False(regex.IsMatch("Dockerfile.json"));47 Assert.False(regex.IsMatch(".dockerignore.json"));48 Assert.False(regex.IsMatch("dockerfile.json"));49 Assert.False(regex.IsMatch(".dockerignore.json"));50 Assert.False(regex.IsMatch("Dockerfile.vb"));
Regex
Using AI Code Generation
1var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();2var ignoreFileContent = ignoreFile.ToString();3var regex = new Regex(@"\.git");4ignoreFileContent = regex.Replace(ignoreFileContent, string.Empty);5File.WriteAllText(ignoreFile.Path, ignoreFileContent);6var image = new DotNet.Testcontainers.Images.BuildImageFromDockerfile(imageName)7 .WithFileFromPath(Directory.GetCurrentDirectory())8 .Build();9var ignoreFile = new DotNet.Testcontainers.Images.IgnoreFile();10var ignoreFileContent = ignoreFile.ToString();11var regex = new Regex(@"\.git");12ignoreFileContent = regex.Replace(ignoreFileContent, string.Empty);13File.WriteAllText(ignoreFile.Path, ignoreFileContent);14var image = new DotNet.Testcontainers.Images.BuildImageFromDockerfile(imageName)15 .WithFileFromPath(Directory.GetCurrentDirectory())16 .Build();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!