public static ChangeLog ReadChangelog(string changelogFile) { var releaseNotes = ReadReleaseNotes(changelogFile); var unreleased = releaseNotes.Where(x => x.Unreleased).ToArray(); if (unreleased.Length > 0) { ControlFlow.Assert(unreleased.Length == 1, "Changelog should have only one draft section."); return(new ChangeLog(changelogFile, unreleased.First(), releaseNotes)); } ControlFlow.Assert(releaseNotes.Count(x => !x.Unreleased) >= 1, "Changelog should have at lease one released version section."); return(new ChangeLog(changelogFile, releaseNotes)); }
private static (string endpoint, string identifier) ParseUrl(string url) { var match = new[] { @"git@(?<endpoint>[^:/]+?)(:|/)(?<identifier>.+?)/?(\.git)?$", @"^https://([^:]+:[^:@]+@)?(?<endpoint>[^/]+?)/(?<identifier>.+?)/?(\.git)?$" } .Select(x => Regex.Match(url.Trim(), x)) .FirstOrDefault(x => x.Success); ControlFlow.Assert(match != null, $"Url '{url}' could not be parsed."); return(match.Groups["endpoint"].Value, match.Groups["identifier"].Value); }
private object Convert(string value, Type destinationType) { try { var typeConverter = TypeDescriptor.GetConverter(destinationType); return(typeConverter.ConvertFromInvariantString(value)); } catch { ControlFlow.Fail($"Value '{value}' could not be converted to '{GetName(destinationType)}'."); // ReSharper disable once HeuristicUnreachableCode return(null); } }
private static bool IsMemberNull(MemberInfo member, NukeBuild build, ExecutableTarget target = null) { var from = target != null ? $"from target '{target.Name}' " : string.Empty; ControlFlow.Assert(member.HasCustomAttribute <InjectionAttributeBase>(), $"Member '{member.Name}' is required {from}but not marked with an injection attribute."); if (NukeBuild.Host == HostType.Console) { InjectValueInteractive(build, member); } return(member.GetValue(build) == null); }
public void GetNextVersion(bool isMainBranchBuild) { Version = GitVersion.MajorMinorPatch; SemVersion = GitVersion.SemVer; /* GitVersion Is not working correctly. * InformationalVersion = GitVersion.InformationalVersion; * SemVersionNugetCompatible = GitVersion.NuGetVersionV2; * * return; */ if (isMainBranchBuild) { SemVersion = Version; SemVersionNugetCompatible = Version; InformationalVersion = Version + "+" + GitVersion.Sha.Substring(0, 7); return; } string label = GitVersion.PreReleaseLabel; int commitNumber = GetBranchCommitCount(); ControlFlow.Assert(commitNumber > 0, "There are no commits on branch [" + CurrentBranch + "]. Since this is a non-main branch there is nothing to do."); //int commitNumber = Int32.Parse(GitVersion.CommitsSinceVersionSource); //commitNumber++; SemVersion = Version + "-" + label + "." + commitNumber; // Calculate Nuget Version string zeros = ""; if (commitNumber > 99) { zeros = "0"; } else if (commitNumber > 9) { zeros = "00"; } else { zeros = "000"; } SemVersionNugetCompatible = Version + "-" + label + zeros + commitNumber; InformationalVersion = SemVersion + "+" + GitVersion.Sha.Substring(0, 7); }
public virtual IProcess StartProcess( string toolPath, string executionArguments = null, string outputArguments = null, string workingDirectory = null, IReadOnlyDictionary <string, string> environmentVariables = null, int?timeout = null, bool logOutput = true, Func <string, LogLevel> logLevelParser = null, Func <string, string> outputFilter = null) { ControlFlow.Assert(toolPath != null, "ToolPath was not set."); if (!Path.IsPathRooted(toolPath) && !toolPath.Contains(Path.DirectorySeparatorChar)) { toolPath = ToolPathResolver.GetPathExecutable(toolPath); } #if NETCORE string toolPathOverride = null; if (toolPath.EndsWith(".dll")) { toolPathOverride = DotNetTasks.GetToolPath(); } else if (EnvironmentInfo.IsUnix && toolPath.EndsWithOrdinalIgnoreCase(".exe")) { toolPathOverride = ToolPathResolver.GetPathExecutable("mono"); } if (!string.IsNullOrEmpty(toolPathOverride)) { executionArguments = $"{toolPath.DoubleQuoteIfNeeded()} {executionArguments}".TrimEnd(); outputArguments = $"{toolPath.DoubleQuoteIfNeeded()} {outputArguments}".TrimEnd(); toolPath = toolPathOverride; } #endif outputArguments = outputArguments ?? (outputFilter == null ? executionArguments : outputFilter(executionArguments)); ControlFlow.Assert(File.Exists(toolPath), $"ToolPath '{toolPath}' does not exist."); Logger.Info($"> {Path.GetFullPath(toolPath).DoubleQuoteIfNeeded()} {outputArguments}"); return(StartProcessInternal(toolPath, executionArguments, workingDirectory, environmentVariables, timeout, logOutput, logLevelParser, outputFilter ?? (x => x))); }
private void qlrpfl(Elevations pfl, RadioClimate klimx, VariabilityMode mdvarx) { _dist = pfl.EndIndex * pfl.DeltaDistance; hzns(pfl); foreach (var antenna in Antennae) { antenna.xl = Math.Min(15 * antenna.hg, 0.1 * antenna.dl); } Receiver.xl = _dist - Receiver.xl; _dh = d1thx(pfl, Transmitter.xl, Receiver.xl); if (Transmitter.dl + Receiver.dl > 1.5 * _dist) { z1sq1(pfl, Transmitter.xl, Receiver.xl, out var za, out var zb); Transmitter.he = Transmitter.hg + Dim(pfl.FirstPoint, za); Receiver.he = Receiver.hg + Dim(pfl.LastPoint, zb); foreach (var antenna in Antennae) { antenna.dl = Math.Sqrt(2 * antenna.he / _gme) * Math.Exp(-0.07 * Math.Sqrt(_dh / Math.Max(antenna.he, 5))); } var q = Transmitter.dl + Receiver.dl; if (q <= _dist) { q = Math.Pow(_dist / q, 2); foreach (var antenna in Antennae) { antenna.he *= q; antenna.dl = Math.Sqrt(2 * antenna.he / _gme) * Math.Exp(-0.07 * Math.Sqrt(_dh / Math.Max(antenna.he, 5))); } } foreach (var antenna in Antennae) { q = Math.Sqrt(2 * antenna.he / _gme); antenna.the = (0.65 * _dh * (q / antenna.dl - 1) - 2 * antenna.he) / q; } } else { z1sq1(pfl, Transmitter.xl, 0.9 * Transmitter.dl, out var za, out _); z1sq1(pfl, _dist - 0.9 * Receiver.dl, Receiver.xl, out _, out var zb); Transmitter.he = Transmitter.hg + Dim(pfl.FirstPoint, za); Receiver.he = Receiver.hg + Dim(pfl.LastPoint, zb); } _mdp = ControlFlow.PointToPoint; _mdvar = mdvarx; _klim = klimx; _lvar = Changes.All; lrprop(0); }
private static IReadOnlyCollection <ExecutableTarget> GetExecutionPlanInternal( IReadOnlyCollection <ExecutableTarget> executableTargets, ICollection <ExecutableTarget> invokedTargets) { var vertexDictionary = GetVertexDictionary(executableTargets); var graphAsList = vertexDictionary.Values.ToList(); var executingTargets = new List <ExecutableTarget>(); while (graphAsList.Any()) { var independents = graphAsList.Where(x => !graphAsList.Any(y => y.Dependencies.Contains(x))).ToList(); if (EnvironmentInfo.ArgumentSwitch("strict") && independents.Count > 1) { ControlFlow.Fail( new[] { "Incomplete target definition order." } .Concat(independents.Select(x => $" - {x.Value.Name}")) .JoinNewLine()); } var independent = independents.FirstOrDefault(); if (independent == null) { var scc = new StronglyConnectedComponentFinder <ExecutableTarget>(); var cycles = scc.DetectCycle(graphAsList) .Cycles() .Select(x => string.Join(" -> ", x.Select(y => y.Value.Name))); ControlFlow.Fail( new[] { "Circular dependencies between target definitions." } .Concat(independents.Select(x => $" - {cycles}")) .JoinNewLine()); } graphAsList.Remove(independent); var executableTarget = independent.Value; if (!invokedTargets.Contains(executableTarget) && !executingTargets.SelectMany(x => x.ExecutionDependencies).Contains(executableTarget)) { continue; } executingTargets.Add(executableTarget); } executingTargets.Reverse(); return(executingTargets); }
public override object GetValue(MemberInfo member, object instance) { // TODO: https://github.com/GitTools/GitVersion/issues/1097 if (EnvironmentInfo.IsUnix && DisableOnUnix) { Logger.Warn($"{nameof(GitVersion)} is disabled on UNIX environment."); return(null); } return(ControlFlow.SuppressErrors(() => GitVersionTasks.GitVersion(s => s .DisableLogOutput()) .Result, includeStackTrace: true)); }
IEnumerable <Instruction> Main() { try { yield return(ControlFlow.ExecuteWhile( () => !hp.dead, Cycle() )); yield break; } finally { anim.SetTrigger("Die"); } }
public void TestNoEquation() { // test-input\_noFunction if (ControlFlow.Initialize()) { string[] delimiters = ControlFlow.GetDelimiters(); string[] results = ControlFlow.ControlDirect("", "x" + delimiters[1] + "2" + delimiters[1] + "4" + delimiters[0] + "y" + delimiters[1] + "3" + delimiters[1] + "5"); Assert.AreEqual(-3, ControlFlow.GetSuccessCode()); } else { Assert.Fail(); } }
public static async Task SendTeamsMessageAsync(Configure <TeamsMessage> configurator, string webhook) { var message = configurator(new TeamsMessage()); var messageJson = JsonConvert.SerializeObject(message); using var client = new WebClient(); client.Headers["Content-Type"] = "application/json"; var response = await client.UploadDataTaskAsync(webhook, "POST", Encoding.UTF8.GetBytes(messageJson)); var responseText = Encoding.UTF8.GetString(response); ControlFlow.Assert(responseText == "1", $"'{responseText}' == '1'"); }
public void Execute( NukeBuild build, IReadOnlyCollection <ExecutableTarget> executableTargets, IReadOnlyCollection <ExecutableTarget> executionPlan) { if (!ParameterService.Instance.GetParameter <bool>(Constants.VisualStudioDebugParameterName)) { return; } File.WriteAllText(Constants.GetVisualStudioDebugFile(NukeBuild.RootDirectory), Process.GetCurrentProcess().Id.ToString()); ControlFlow.Assert(SpinWait.SpinUntil(() => Debugger.IsAttached, millisecondsTimeout: TimeoutInMilliseconds), $"VisualStudio debugger was not attached within {TimeoutInMilliseconds} milliseconds."); }
public void TestExtractVars() { EquationConversion.ResetEquationConversion(); if (ControlFlow.Initialize()) { // unittest-controlextractvars string[] vars = ControlFlow.ExtractVariables("x+y"); Assert.AreEqual("x", vars[0]); Assert.AreEqual("y", vars[1]); } else { Assert.Fail(); } }
private PropertyInfo GetSingleTargetProperty <T>() { var interfaceTargets = typeof(T).GetProperties(ReflectionUtility.Instance).Where(x => x.PropertyType == typeof(Target)).ToList(); ControlFlow.Assert(interfaceTargets.Count == 1, new[] { $"Target '{Target.DeclaringType}.{Target.Name}' cannot have a shorthand dependency on component '{typeof(T).Name}'.", interfaceTargets.Count > 1 ? "Available targets are:" : "No targets available." }.Concat(interfaceTargets.Select(x => $" - {x.Name}")).JoinNewLine()); return(interfaceTargets.Single()); }
/// <summary> /// Url in the form of <c>https://github.com/{identifier}/tree/{branch}/directory</c> or /// <c>https://github.com/{identifier}/blob/{branch}/file</c> depending on the item type. /// </summary> public static string GetGitHubBrowseUrl( this GitRepository repository, string path = null, string branch = null, GitHubItemType itemType = GitHubItemType.Automatic) { ControlFlow.Assert(repository.IsGitHubRepository(), "repository.IsGitHubRepository()"); branch = branch ?? repository.Branch.NotNull("repository.Branch != null"); var relativePath = GetRepositoryRelativePath(path, repository); var method = GetMethod(relativePath, itemType, repository); ControlFlow.Assert(path == null || method != null, "Could not determine item type."); return $"https://github.com/{repository.Identifier}/{method}/{branch}/{relativePath}"; }
protected virtual GitHubActionsConfiguration GetConfiguration(NukeBuild targets, IReadOnlyCollection <ExecutableTarget> relevantTargets) { var configuration = new GitHubActionsConfiguration { Name = _name, ShortTriggers = On, DetailedTriggers = GetTriggers().ToArray(), Jobs = _images.Select(x => GetJobs(x, relevantTargets)).ToArray() }; ControlFlow.Assert(configuration.ShortTriggers == null || configuration.DetailedTriggers.Length == 0, "configuration.ShortTriggers == null || configuration.DetailedTriggers.Length == 0"); return(configuration); }
private static T CreateBuildInstance <T>(Expression <Func <T, Target> > defaultTargetExpression) where T : NukeBuild { var constructors = typeof(T).GetConstructors(); ControlFlow.Assert(constructors.Length == 1 && constructors.Single().GetParameters().Length == 0, $"Type '{typeof(T).Name}' must declare a single parameterless constructor."); var build = Activator.CreateInstance <T>(); build.TargetDefinitions = build.GetTargetDefinitions(defaultTargetExpression); NukeBuild.Instance = build; return(build); }
public static IEnumerable <(string Text, object Object)> GetParameterValueSet(MemberInfo member, object instance) { var attribute = member.GetCustomAttribute <ParameterAttribute>(); var memberType = member.GetMemberType().GetScalarType(); IEnumerable <(string Text, object Object)> TryGetFromValueProvider() { if (attribute.ValueProviderMember == null) { return(null); } var valueProviderType = attribute.ValueProviderType ?? instance.GetType(); var valueProvider = valueProviderType .GetMember(attribute.ValueProviderMember, All) .SingleOrDefault() .NotNull($"No single provider '{valueProviderType.Name}.{member.Name}' found."); ControlFlow.Assert(valueProvider.GetMemberType() == typeof(IEnumerable <string>), $"Value provider '{valueProvider.Name}' must be of type '{typeof(IEnumerable<string>).GetDisplayShortName()}'."); return(valueProvider.GetValue <IEnumerable <string> >(instance).Select(x => (x, (object)x))); } IEnumerable <(string Text, object Object)> TryGetFromEnumerationClass() => memberType.IsSubclassOf(typeof(Enumeration)) ? memberType.GetFields(Static).Select(x => (x.Name, x.GetValue())) : null; IEnumerable <(string Text, object Object)> TryGetFromEnum() { var enumType = memberType.IsEnum ? memberType : Nullable.GetUnderlyingType(memberType) is { } underlyingType&& underlyingType.IsEnum ? underlyingType : null; return(enumType != null ? enumType.GetEnumNames().Select(x => (x, Enum.Parse(enumType, x))) : null); } return((attribute.GetValueSet(member, instance) ?? TryGetFromValueProvider() ?? TryGetFromEnumerationClass() ?? TryGetFromEnum()) ?.OrderBy(x => x.Item1)); }
internal static void RecreateDatabase(string dbName, string connectionString) { var cs = new ConnectionString(connectionString); var masterConnection = new SqlConnectionManager(cs.GetMasterConnection()); ControlFlow.SetLoggingDatabase(masterConnection); new DropDatabaseTask(dbName) { DisableLogging = true, ConnectionManager = masterConnection }.Execute(); new CreateDatabaseTask(dbName, RecoveryModel.Simple, "Latin1_General_CS_AS") { DisableLogging = true, ConnectionManager = masterConnection }.Execute(); ControlFlow.SetLoggingDatabase(new SqlConnectionManager(cs)); }
public static string GetPackageExecutable(string packageId, string packageExecutable, string version = null, string framework = null) { ControlFlow.Assert(packageId != null && packageExecutable != null, "packageId != null && packageExecutable != null"); var packageDirectory = GetPackageDirectory(packageId.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries), version); var packageExecutables = packageExecutable.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var packageExecutablePaths = packageExecutables .Select(x => Directory.GetFiles(packageDirectory, x, SearchOption.AllDirectories)) .FirstOrDefault(x => x.Length > 0)?.ToList(); ControlFlow.Assert(packageExecutablePaths != null, $"Could not find {packageExecutables.Select(x => x.SingleQuote()).JoinCommaOr()} inside '{packageDirectory}'."); if (packageExecutablePaths.Count == 1 && framework == null) { return(packageExecutablePaths.Single()); }
private string GetSolutionFileFromConfigurationFile() { var nukeFile = Path.Combine(NukeBuild.Instance.RootDirectory, NukeBuild.ConfigurationFile); ControlFlow.Assert(File.Exists(nukeFile), $"File.Exists({NukeBuild.ConfigurationFile})"); var solutionFileRelative = File.ReadAllLines(nukeFile)[0]; ControlFlow.Assert(!solutionFileRelative.Contains(value: '\\'), $"{NukeBuild.ConfigurationFile} must use unix-styled separators"); var solutionFile = Path.GetFullPath(Path.Combine(NukeBuild.Instance.RootDirectory, solutionFileRelative)); ControlFlow.Assert(File.Exists(solutionFile), "File.Exists(solutionFile)"); return((PathConstruction.AbsolutePath)solutionFile); }
private static string GetRepositoryRelativePath([CanBeNull] string path, GitRepository repository) { if (path == null) { return(null); } if (!Path.IsPathRooted(path)) { return(path); } ControlFlow.Assert(PathConstruction.IsDescendantPath(repository.LocalDirectory.NotNull("repository.LocalDirectory != null"), path), $"PathConstruction.IsDescendantPath({repository.LocalDirectory}, {path})"); return(PathConstruction.GetRelativePath(repository.LocalDirectory, path).Replace(oldChar: '\\', newChar: '/')); }
public static void CopyDirectoryRecursively( string source, string target, DirectoryExistsPolicy directoryPolicy = DirectoryExistsPolicy.Fail, FileExistsPolicy filePolicy = FileExistsPolicy.Fail, Func <DirectoryInfo, bool> excludeDirectory = null, Func <FileInfo, bool> excludeFile = null) { ControlFlow.Assert(Directory.Exists(source), $"Directory.Exists({source})"); ControlFlow.Assert(!PathConstruction.IsDescendantPath(source, target), $"Target directory '{target}' must not be in source directory '{source}'."); //ControlFlow.Assert(!Contains(source, target), $"Target '{target}' is not contained in source '{source}'."); Logger.Info($"Recursively copying from '{source}' to '{target}'..."); CopyRecursivelyInternal(source, target, directoryPolicy, filePolicy, excludeDirectory, excludeFile); }
public void Test() { var executions = 0; void OnSecondExecution() { executions++; if (executions != 2) { throw new Exception(executions.ToString()); } } ControlFlow.ExecuteWithRetry(OnSecondExecution); executions.Should().Be(2); }
IEnumerable <Instruction> TestAdapter() { // Control execution of two slaves based on value returned by master yield return(ControlFlow.ExecuteWhile( Utils.Adapt(TestMasterFloat(), floatVal => floatVal > 1.0f), boolVal => boolVal == true, TestSlave(5), TestSlave(10))); // Alternate syntax yield return(ControlFlow.ExecuteWhile( TestMasterFloat().Adapt(floatVal => floatVal > 1.0f), boolVal => boolVal == true, TestSlave(5), TestSlave(10))); }
public static string GetPackageExecutable(string packageId, string packageExecutable, string framework = null) { ControlFlow.Assert(packageId != null && packageExecutable != null, "packageId != null && packageExecutable != null"); string GetEmbeddedPackagesDirectory() { var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var embeddedDirectory = (PathConstruction.AbsolutePath)assemblyDirectory / packageId; return(Directory.Exists(embeddedDirectory) ? embeddedDirectory : null); } string GetNuGetPackagesDirectory() => NuGetPackagesConfigFile != null ? NuGetPackageResolver.GetLocalInstalledPackage( packageId, NuGetPackagesConfigFile, resolveDependencies : false) ?.Directory : null; string GetPaketPackagesDirectory() => PaketPackagesConfigFile != null ? PaketPackageResolver.GetLocalInstalledPackageDirectory( packageId, PaketPackagesConfigFile) : null; var packageDirectory = (GetEmbeddedPackagesDirectory() ?? GetNuGetPackagesDirectory() ?? GetPaketPackagesDirectory()).NotNull("packageDirectory != null"); var executables = Directory.GetFiles(packageDirectory, packageExecutable, SearchOption.AllDirectories); ControlFlow.Assert(executables.Length > 0, $"Could not find '{packageExecutable}' inside '{packageDirectory}'."); if (executables.Length == 1 && framework == null) { return(executables.Single()); } var frameworks = executables.Select(x => new FileInfo(x).Directory.NotNull().Name).ToList(); ControlFlow.Assert(frameworks.Contains(framework, StringComparer.OrdinalIgnoreCase), $"Package executable {packageExecutable} [{packageId}] requires a framework: {frameworks.JoinComma()}"); return(executables.Single(x => new FileInfo(x).Directory.NotNull().Name.EqualsOrdinalIgnoreCase(framework))); }
private static int Handle(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript) { var hasCommand = args.FirstOrDefault()?.StartsWithOrdinalIgnoreCase(CommandPrefix.ToString()) ?? false; if (hasCommand) { var command = args.First().Trim(CommandPrefix).Replace("-", string.Empty); if (string.IsNullOrWhiteSpace(command)) { ControlFlow.Fail($"No command specified. Usage is: nuke {CommandPrefix}<command> [args]"); } var availableCommands = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public); var commandHandler = availableCommands .SingleOrDefault(x => x.Name.EqualsOrdinalIgnoreCase(command)); ControlFlow.Assert(commandHandler != null, new[] { $"Command '{command}' is not supported.", "Available commands are:" } .Concat(availableCommands.Select(x => $" - {x.Name}").OrderBy(x => x)).JoinNewLine()); // TODO: add assertions about return type and parameters var commandArguments = new object[] { args.Skip(count: 1).ToArray(), rootDirectory, buildScript }; return((int)commandHandler.Invoke(obj: null, commandArguments)); } if (rootDirectory == null || buildScript == null) { var missingItem = rootDirectory == null ? $"{Constants.NukeDirectoryName} directory/file" : "build.ps1/sh files"; return(UserConfirms($"Could not find {missingItem}. Do you want to setup a build?") ? Setup(new string[0], rootDirectory, buildScript: null) : 0); } // TODO: docker var arguments = args.Select(x => x.DoubleQuoteIfNeeded()).JoinSpace(); var process = Build(buildScript, arguments); process.WaitForExit(); return(process.ExitCode); }
IEnumerable <Instruction> Cycle(Transform target) { try { bool Detached = false; yield return(ControlFlow.ExecuteWhile( () => !Detached, FocusOn(target, transform), Prepare(target, detached => Detached = detached) )); if (ViceLeft == null) { ViceLeft = Instantiate(shadowPrefab, transform.position, Quaternion.identity).transform; } if (ViceRight == null) { ViceRight = Instantiate(shadowPrefab, transform.position, Quaternion.identity).transform; } bool needReGrid = false; yield return(ControlFlow.ExecuteWhileRunning( GridLie(transform, ViceLeft, false), GridLie(transform, ViceRight, true), FocusOn(target, transform), FocusOn(target, ViceLeft), FocusOn(target, ViceRight) )); needReGrid = false; yield return(ControlFlow.ExecuteWhile( () => !needReGrid, Strike(target, transform, need => needReGrid = need), Strike(target, ViceLeft, need => needReGrid = need), Strike(target, ViceRight, need => needReGrid = need) )); } finally { if (ViceLeft.GetComponent <Animator>() != null) { ViceLeft.GetComponent <Animator>().SetTrigger("Die"); } if (ViceRight.GetComponent <Animator>() != null) { ViceRight.GetComponent <Animator>().SetTrigger("Die"); } } }
private static void CopyRecursivelyInternal( string source, string target, DirectoryExistsPolicy directoryPolicy, FileExistsPolicy filePolicy, [CanBeNull] Func <DirectoryInfo, bool> excludeDirectory, [CanBeNull] Func <FileInfo, bool> excludeFile) { if (excludeDirectory != null && excludeDirectory(new DirectoryInfo(source))) { return; } ControlFlow.Assert(!Directory.Exists(target) || directoryPolicy != DirectoryExistsPolicy.Fail, $"!Directory.Exists({target}) || directoryPolicy != DirectoryExistsPolicy.Fail"); string GetDestinationPath(string path) => Path.Combine(target, PathConstruction.GetRelativePath(source, path)); Directory.CreateDirectory(target); foreach (var sourceFile in Directory.GetFiles(source)) { if (excludeFile != null && excludeFile(new FileInfo(sourceFile))) { continue; } var targetFile = GetDestinationPath(sourceFile); if (!ShouldCopyFile(sourceFile, targetFile, filePolicy)) { continue; } //EnsureFileAttributes(sourceFile); File.Copy(sourceFile, targetFile, overwrite: true); } Directory.GetDirectories(source) .ForEach(x => CopyRecursivelyInternal( x, GetDestinationPath(x), directoryPolicy, filePolicy, excludeDirectory, excludeFile)); }
private Element PEKNamedSubBlock(Block Parent, Group RegExGroup) { Block bl; var cf = new ControlFlow(); cf.Parent = Parent; //On continue and break bool isForCF = false; switch (RegExGroup.Value.ToLower()) { case "succeed": cf.Type = ControlFlow.eType.Succeed; break; case "fail": cf.Type = ControlFlow.eType.Fail; break; case "goto": cf.Type = ControlFlow.eType.GoTo; break; case "continue": cf.Type = ControlFlow.eType.Continue; PendingContinueControlFlows.Add(cf); isForCF = true; break; case "break": cf.Type = ControlFlow.eType.Succeed; PendingContinueControlFlows.Add(cf); isForCF = true; break; } cf.Annotation.SourcePosition = RegExGroup; if (_caret.WS().Match(@":")) { cf.Name = ""; bool bNIP; TextPortion tp; if (PEIdentifier("#", "_sb", out cf.Name, out bNIP, out tp)) { //Emanate errors if (cf.Name.Length == 0) ThrowParseError("Missing block name", tp); cf.Annotation.SourcePosition.End = tp.End; bl = Parent; if (cf.Type == ControlFlow.eType.GoTo) { //Find block or wait for it to be defined if (cf.Name != "") { var labels = Parent.Function.NamedBlocks; if (labels.Defined.ContainsKey(cf.Name)) { cf.Target = labels.Defined[cf.Name]; if (cf.Target.GOTOArea != Parent.GOTOArea) ThrowParseError("Cannot jump there from here", cf.Annotation.SourcePosition); else { //Obviously parent blocks up to the common ancestor can't be called bl = Parent.FindCommonAncestor(cf.Target); if (bl != null) { Block b2 = Parent; while ((b2 != null) && (b2 != bl)) { b2.CanBeCalled = false; b2 = b2.Parent; } } } } else { //It's not defined, so remember to check later if (!labels.Undefined.ContainsKey(cf.Name)) labels.Undefined.Add(cf.Name, new Function.NamedBlocksClass.UndefinedBlockCall()); labels.Undefined[cf.Name].Items.Add(cf); } } } else { //Find parent block while ((bl != null) && (StringComparer.OrdinalIgnoreCase.Compare(bl.Name, cf.Name) != 0)) bl = bl.Parent; if (bl == null) ThrowParseError("Block '" + cf.Name + "' not a parent block", cf.Annotation.SourcePosition); else { cf.Target = bl; //Obviously parent blocks until cf.Target can't be called bl = Parent; while ((bl != null) && (StringComparer.OrdinalIgnoreCase.Compare(bl.Name, cf.Name) != 0)) { bl.CanBeCalled = false; bl = bl.Parent; } } } } else if (_caret.Match(@"(?<_kw>Function)(?!\w)")) { if (isForCF) ThrowParseError("Must target a For loop", cf.Annotation.SourcePosition); else { bl = Parent; while ((bl != null) && (bl.Parent != null)) bl = bl.Parent; if (bl == null) ThrowParseError("Expected block name", cf.Annotation.SourcePosition); else { cf.Name = bl.Name; cf.Target = bl; cf.Annotation.SourcePosition.End = new TextPortion(_caret.LastMatch).End; } } } else ThrowParseError("Expected block name", cf.Annotation.SourcePosition); } else { switch (cf.Type) { case ControlFlow.eType.GoTo: ThrowParseError("Expected block definition", cf.Annotation.SourcePosition); break; case ControlFlow.eType.Fail: case ControlFlow.eType.Succeed: if (!isForCF) cf.Target = Parent; break; } } if (cf.Type == ControlFlow.eType.Succeed) if (cf.Target != null) Parent.SucceedsUpToDepth = cf.Target.Depth; return cf; }
/// <summary> /// Parse a named block or a control flow /// </summary> private Element PENamedBlock(Block Parent) { string sName; bool bNameIsProper; TextPortion tp; if (PEIdentifier("#", "_sb", out sName, out bNameIsProper, out tp)) { //Emanate errors if (sName.Length == 0) ThrowParseError("Missing block name", tp); else if (!bNameIsProper) ThrowParseError("Block name must begin with a letter", tp); //If it is a definition if (_caret.WS().Match(@"\:")) { Block bl = new Block(); bl.Annotation.IDE = IDE; bl.Name = sName; bl.Parent = Parent; bl.Annotation.SourcePosition = tp; if (bl.Name.Length != 0) { var labels = Parent.Function.NamedBlocks; //Must be unique if ((labels.Defined.ContainsKey(bl.Name)) || (Parent.Function.Aliases.Contains(bl.Name))) ThrowParseError("Block name already exists", bl.Annotation.SourcePosition); //Update calls to it else if (bNameIsProper) { labels.Defined.Add(bl.Name, bl); if (labels.Undefined.ContainsKey(bl.Name)) labels.Undefined[bl.Name].Target = bl; } } //Must have a block following if (!_caret.WS().Match(@"\{")) ThrowParseError("Expected block declaration", bl.Annotation.SourcePosition); else { bl.Annotation.SourcePosition.Begin = _caret.LastMatch.Index; //If it fails fail ParseBlock(bl); bl.Annotation.SourcePosition.End = bl.Annotation.SourcePosition.End; } return bl; } //It is a call else { var cf = new ControlFlow(); cf.Type = ControlFlow.eType.Call; cf.Name = sName; cf.Annotation.SourcePosition = tp; if (cf.Name != "") { var labels = Parent.Function.NamedBlocks; //If not defined yet add to watchlist if (labels.Defined.ContainsKey(cf.Name)) { cf.Target = labels.Defined[cf.Name]; if (!cf.Target.CanBeCalled) ThrowParseError("This block cannot be called from here; it uses a goto/succeed/fail of a parent block", cf.Annotation.SourcePosition); } else { //Add to watchlist if (!labels.Undefined.ContainsKey(cf.Name)) labels.Undefined.Add(cf.Name, new Function.NamedBlocksClass.UndefinedBlockCall()); labels.Undefined[cf.Name].Items.Add(cf); } } return cf; } } else return null; }