Exemplo n.º 1
0
        public async void IsIdempotant()
        {
            var dryRun = new DryRun(false, this.dryRunLogger);

            await this.AssertMetadata(BeforeFixSamples, FirmwareVersion);

            var actual = await this.fixer.ProcessFileAsync(this.target.Path, dryRun, false);

            Assert.Equal(FixStatus.Fixed, actual.Status);
            Assert.Contains($"Old total samples was", actual.Message);

            await this.AssertMetadata(AfterFixSamples, FirmwareVersion, PatchedTag);

            var first = await this.fileUtilities.CalculateChecksum(this.target.Path, HashAlgorithmName.SHA256);

            // now again!
            var secondActual = await this.fixer.ProcessFileAsync(this.target.Path, dryRun, false);

            Assert.Equal(FixStatus.NoOperation, secondActual.Status);
            Assert.Contains($"File has already had it's duration repaired", secondActual.Message);
            Assert.Equal(CheckStatus.Repaired, secondActual.CheckResult.Status);
            var second = await this.fileUtilities.CalculateChecksum(this.target.Path, HashAlgorithmName.SHA256);

            Assert.Equal(first, second);

            await this.AssertMetadata(AfterFixSamples, FirmwareVersion, PatchedTag);
        }
Exemplo n.º 2
0
 internal sealed record OptionArgs(
     SourcePath SourcePath,
     DestinationDirectory DestinationDirectory,
     DryRun DryRun,
     KeepGoing KeepGoing,
     SkipDateSubdirectory SkipDateSubdirectory,
     Overwrite Overwrite);
Exemplo n.º 3
0
            public void Apply(IServiceProvider serviceProvider)
            {
                var settings = serviceProvider.GetService <IOptions <Settings> >().Value;

                if (Host.HasValue())
                {
                    settings.Admin.Host = Host.Value();
                }

                if (OutputFolder.HasValue())
                {
                    settings.OutputFolder = OutputFolder.Value();
                }

                if (Port.HasValue())
                {
                    settings.Admin.Port = int.Parse(Port.Value());
                }

                settings.DryRun = DryRun.HasValue();

                if (InputFolder.HasValue())
                {
                    settings.InputFolder = InputFolder.Value();
                }
            }
Exemplo n.º 4
0
        public async void WillBackupIfRequested()
        {
            var backupPath = this.target.Path + ".bak";
            var dryRun     = new DryRun(false, this.dryRunLogger);

            var before = await this.fileUtilities.CalculateChecksum(this.target.Path, HashAlgorithmName.SHA256);

            await this.AssertMetadata(BeforeFixSamples, FirmwareVersion);

            var actual = await this.fixer.ProcessFileAsync(this.target.Path, dryRun, true);

            Assert.Equal(FixStatus.Fixed, actual.Status);
            Assert.Contains($"Old total samples was", actual.Message);

            // modified file
            await this.AssertMetadata(AfterFixSamples, FirmwareVersion, PatchedTag);

            // backup
            using (var stream = (FileStream)this.fileSystem.File.OpenRead(backupPath))
            {
                var actualSamples  = (ulong)Flac.ReadTotalSamples(stream);
                var actualFirmware = (FirmwareRecord) await ReadFirmwareAsync(stream);

                Assert.Equal(BeforeFixSamples, actualSamples);
                Assert.Equal(FirmwareVersion, actualFirmware.Version);

                actualFirmware.Tags.Should().BeEquivalentTo(Array.Empty <string>());
            }

            var after = await this.fileUtilities.CalculateChecksum(backupPath, HashAlgorithmName.SHA256);

            // the backup file has the same hash as the original
            Assert.Equal(before, after);
        }
Exemplo n.º 5
0
        private async Task <int> Execute()
        {
            if (!TryValidateProjectPath(Project, out var projectPath))
            {
                return(1);
            }

            if (Plugins.Values.Count == 0)
            {
                ShowHelp();
                return(1);
            }

            var analysisContext = Analysis.CreateContext();
            var compilation     = await GetCompilationAsync(projectPath);

            analysisContext.SetData <CSharpCompilation>(compilation);

            var operations = new List <Operation>();

            for (var i = 0; i < Plugins.Values.Count; i++)
            {
                var name = Plugins.Values[i];

                Out.WriteLine($"Processing '{name}'...");

                if (!KnownPlugins.Plugins.TryGetValue(name, out var plugin))
                {
                    Out.WriteLine($"Unknown plugin '{name}'");
                    return(1);
                }

                operations.AddRange(await plugin.GetOperationsAsync(analysisContext));
            }

            Out.WriteLine("Resolved operations:");
            for (var i = 0; i < operations.Count; i++)
            {
                Out.WriteLine($"\t{operations[i]}");
            }
            Out.WriteLine();

            if (!DryRun.HasValue())
            {
                var editorContext = new EditorContext();
                editorContext.SetData <CSharpCompilation>(await analysisContext.GetDataAsync <CSharpCompilation>().ConfigureAwait(false));
                var editor = Editor.Create();

                Out.WriteLine("Performing operations:");
                for (var i = 0; i < operations.Count; i++)
                {
                    Out.WriteLine($"\t{operations[i]}");
                    await editor.ApplyAsync(editorContext, operations[i]);
                }
            }
            Out.WriteLine();

            return(0);
        }
Exemplo n.º 6
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ DryRun.GetHashCode();
         hashCode = (hashCode * 397) ^ (Manifests != null ? Manifests.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ Prune.GetHashCode();
         return(hashCode);
     }
 }
Exemplo n.º 7
0
        public override async Task <int> InvokeAsync(InvocationContext context)
        {
            // validate options

            // resolve targets
            this.logger.LogDebug("Input targets: {targets}", this.Targets);

            var files = this.fileMatcher.ExpandMatches(this.fileSystem.Directory.GetCurrentDirectory(), this.Targets);

            this.WriteHeader <RenameResult>();
            this.Write("Looking for targets...");

            using var dryRun = new DryRun(this.DryRun, this.dryRunLogger);

            var(renames, failed) = await this.ProcessFiles(files, dryRun);

            int success = 0, unchanged = 0, fail = 0;

            if (renames.Any())
            {
                if (failed)
                {
                    fail = renames.Length;
                }
                else
                {
                    foreach (var result in renames)
                    {
                        if (result.Reason is not null)
                        {
                            fail++;
                        }
                        else if (result.OldName == result.NewName)
                        {
                            unchanged++;
                        }
                        else
                        {
                            success++;
                        }
                    }
                }
            }
            else
            {
                this.WriteFooter($"No files matched targets: {this.Targets.FormatInlineList()}");
            }

            this.WriteFooter($"{renames.Length} files, {success} renamed, {unchanged} unchanged, {fail} failed");

            return(ExitCodes.Get(!failed));
        }
Exemplo n.º 8
0
        public async void CanRepairFaultyDurations()
        {
            var dryRun = new DryRun(false, this.dryRunLogger);

            await this.AssertMetadata(BeforeFixSamples, FirmwareVersion);

            var actual = await this.fixer.ProcessFileAsync(this.target.Path, dryRun, false);

            Assert.Equal(FixStatus.Fixed, actual.Status);
            Assert.Contains($"Old total samples was", actual.Message);

            await this.AssertMetadata(AfterFixSamples, FirmwareVersion, PatchedTag);
        }
Exemplo n.º 9
0
        public async void WillDoNothingInADryRun()
        {
            var dryRun = new DryRun(true, this.dryRunLogger);

            var before = await this.fileUtilities.CalculateChecksum(this.target.Path, HashAlgorithmName.SHA256);

            await this.AssertMetadata(BeforeFixSamples, FirmwareVersion);

            var actual = await this.fixer.ProcessFileAsync(this.target.Path, dryRun, false);

            Assert.Equal(FixStatus.Fixed, actual.Status);
            Assert.Contains($"Old total samples was", actual.Message);

            await this.AssertMetadata(BeforeFixSamples, FirmwareVersion);

            var after = await this.fileUtilities.CalculateChecksum(this.target.Path, HashAlgorithmName.SHA256);

            Assert.Equal(before, after);
        }
Exemplo n.º 10
0
 public static async Task ClassCleanup()
 {
     await DryRun.DisableSafeMode();
 }
Exemplo n.º 11
0
 public async Task DapperQueriesWork(QueryContext ctx)
 {
     await DryRun.ExecuteQuery(ctx);
 }
Exemplo n.º 12
0
 public static async Task ClassInit(TestContext context)
 {
     await DryRun.EnableSafeMode(ConnectionString);
 }
Exemplo n.º 13
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string();
            tokens["AlterDatabaseFolderName"]  = AlterDatabaseFolderName.to_string();
            tokens["Baseline"] = Baseline.to_string();
            tokens["BeforeMigrationFolderName"]  = BeforeMigrationFolderName.to_string();
            tokens["CommandTimeout"]             = CommandTimeout.to_string();
            tokens["CommandTimeoutAdmin"]        = CommandTimeoutAdmin.to_string();
            tokens["ConfigurationFile"]          = ConfigurationFile.to_string();
            tokens["ConnectionString"]           = ConnectionString.to_string();
            tokens["ConnectionStringAdmin"]      = ConnectionStringAdmin.to_string();
            tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string();
            tokens["DatabaseName"]             = DatabaseName.to_string();
            tokens["DatabaseType"]             = DatabaseType.to_string();
            tokens["Debug"]                    = Debug.to_string();
            tokens["DisableOutput"]            = DisableOutput.to_string();
            tokens["DisableTokenReplacement"]  = DisableTokenReplacement.to_string();
            tokens["DoNotAlterDatabase"]       = DoNotAlterDatabase.to_string();
            tokens["DoNotCreateDatabase"]      = DoNotCreateDatabase.to_string();
            tokens["DoNotStoreScriptsRunText"] = DoNotStoreScriptsRunText.to_string();
            tokens["DownFolderName"]           = DownFolderName.to_string();
            tokens["Drop"]                                     = Drop.to_string();
            tokens["DryRun"]                                   = DryRun.to_string();
            tokens["EnvironmentName"]                          = string.Join(",", EnvironmentNames);
            tokens["EnvironmentNames"]                         = string.Join(",", EnvironmentNames);
            tokens["FunctionsFolderName"]                      = FunctionsFolderName.to_string();
            tokens["IndexesFolderName"]                        = IndexesFolderName.to_string();
            tokens["Initialize"]                               = Initialize.to_string();
            tokens["OutputPath"]                               = OutputPath.to_string();
            tokens["PermissionsFolderName"]                    = PermissionsFolderName.to_string();
            tokens["RecoveryMode"]                             = RecoveryMode.to_string();
            tokens["RepositoryPath"]                           = RepositoryPath.to_string();
            tokens["Restore"]                                  = Restore.to_string();
            tokens["RestoreCustomOptions"]                     = RestoreCustomOptions.to_string();
            tokens["RestoreFromPath"]                          = RestoreFromPath.to_string();
            tokens["RestoreTimeout"]                           = RestoreTimeout.to_string();
            tokens["RunAfterCreateDatabaseFolderName"]         = RunAfterCreateDatabaseFolderName.to_string();
            tokens["RunAfterOtherAnyTimeScriptsFolderName"]    = RunAfterOtherAnyTimeScriptsFolderName.to_string();
            tokens["RunAllAnyTimeScripts"]                     = RunAllAnyTimeScripts.to_string();
            tokens["RunBeforeUpFolderName"]                    = RunBeforeUpFolderName.to_string();
            tokens["RunFirstAfterUpFolderName"]                = RunFirstAfterUpFolderName.to_string();
            tokens["SchemaName"]                               = SchemaName.to_string();
            tokens["ScriptsRunErrorsTableName"]                = ScriptsRunErrorsTableName.to_string();
            tokens["ScriptsRunTableName"]                      = ScriptsRunTableName.to_string();
            tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string();
            tokens["ServerName"]                               = ServerName.to_string();
            tokens["Silent"]                                   = Silent.to_string();
            tokens["SprocsFolderName"]                         = SprocsFolderName.to_string();
            tokens["SqlFilesDirectory"]                        = SqlFilesDirectory.to_string();
            tokens["TriggersFolderName"]                       = TriggersFolderName.to_string();
            tokens["UpFolderName"]                             = UpFolderName.to_string();
            tokens["Version"]                                  = Version.to_string();
            tokens["VersionFile"]                              = VersionFile.to_string();
            tokens["VersionTableName"]                         = VersionTableName.to_string();
            tokens["VersionXPath"]                             = VersionXPath.to_string();
            tokens["ViewsFolderName"]                          = ViewsFolderName.to_string();
            tokens["WarnAndIgnoreOnOneTimeScriptChanges"]      = WarnAndIgnoreOnOneTimeScriptChanges.to_string();
            tokens["WarnOnOneTimeScriptChanges"]               = WarnOnOneTimeScriptChanges.to_string();
            tokens["WithTransaction"]                          = WithTransaction.to_string();

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
Exemplo n.º 14
0
#pragma warning restore CS0612 // Type or member is obsolete

        public async Task <int> ExecuteAsync(CancellationToken cancellationToken)
        {
            var sw = System.Diagnostics.Stopwatch.StartNew();

            _logger.SetDebugEnable(Verbose.HasValue());

            try
            {
                var(baseRegistry, destRegistry) = CreateRegistries();
                var(manifest, image)            = await LoadBaseImage(baseRegistry);

                UpdateImageConfig(image);
                UpdateConfigInManifest(manifest, image);

                var layersAdded = new List <BuilderLayer>();
                if (Add.HasValue())
                {
                    var layer = CreateLayer(Add.Values, AddFolder.Values, $"layer{layersAdded.Count():00}");
                    layersAdded.Add(layer);
                    AddLayerToConfigAndManifest(layer, manifest, image);
                }

                var pusher = new Pusher(GetFromImage(), GetToImage(), destRegistry, layersAdded, CreateLogger("PUSHR"))
                {
                    FakePullAndRetryMount = true,
                };

                bool configExists = await pusher.CheckConfigExists(manifest);

                var missingLayers = await pusher.FindMissingLayers(manifest, !DryRun.HasValue() && destRegistry == baseRegistry);

                if (!DryRun.HasValue())
                {
                    if (!configExists)
                    {
                        await pusher.PushConfig(manifest.config, () => GetJsonStream(image));
                    }

                    await pusher.CopyLayers(baseRegistry, ImageHelper.GetImageName(GetFromImage()), missingLayers);

                    await pusher.PushLayers(f => File.OpenRead(Path.Combine(_tempFolderPath, f)));

                    await pusher.PushManifest(() => GetJsonStream(manifest));
                }

                string manifestDigest;
                using (var manifestStream = GetJsonStream(manifest))
                {
                    manifestDigest = FileHelper.Digest(manifestStream);
                }

                _logger.LogDebug($"Image digest: {manifestDigest}");

                if (DigestFile.HasValue())
                {
                    string digestFilepath;
                    if (!string.IsNullOrEmpty(DigestFile.Value()))
                    {
                        digestFilepath = DigestFile.Value();
                    }
                    else
                    {
                        EnsureTempFolder();
                        digestFilepath = Path.Combine(_tempFolderPath, ManifestDigestFileName);
                    }

                    File.WriteAllText(digestFilepath, manifestDigest);
                }

                _logger.LogDebug($"completed in {sw.ElapsedMilliseconds} ms");
                Console.WriteLine(manifestDigest);

                return(0);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine($"Error: {ex.Message}");
                _logger.LogDebug(ex, "exception");
                _logger.LogDebug($"completed in {sw.ElapsedMilliseconds} ms");

                return(1);
            }
        }
Exemplo n.º 15
0
        public async Task <int> ExecuteCore(bool generateOnly)
        {
            if (!OutputDirectory.HasValue())
            {
                OutputDirectory.TryParse($"_output");
            }

            var logsPath = Path.Combine(OutputDirectory.Required(), "logs");

            if (Directory.Exists(logsPath))
            {
                foreach (var file in Directory.EnumerateFiles(logsPath))
                {
                    File.Delete(file);
                }
            }

            var generatedPath = Path.Combine(OutputDirectory.Required(), "generated");

            if (Directory.Exists(generatedPath))
            {
                foreach (var file in Directory.EnumerateFiles(generatedPath, "*.*", new EnumerationOptions {
                    RecurseSubdirectories = true
                }))
                {
                    File.Delete(file);
                }

                foreach (var folder in Directory.EnumerateDirectories(generatedPath))
                {
                    Directory.Delete(folder, recursive: true);
                }
            }

            var blueprint = await _blueprintManager.GetBlueprintPackage(Blueprint.Required());

            if (blueprint == null)
            {
                throw new ApplicationException($"Unable to locate blueprint {Blueprint.Required()}");
            }

            var eachValues         = new List <object>();
            var defaultValuesFiles =
                File.Exists("values.yaml") ? new[] { "values.yaml" } :
            new string[0];

            foreach (var valuesFile in Values.OptionalMany(defaultValuesFiles))
            {
                using (var reader = File.OpenText(valuesFile))
                {
                    eachValues.Add(_serializers.YamlDeserializer.Deserialize(reader));
                }
            }

            if (Set.HasValue())
            {
                var setValues = new Dictionary <object, object>();

                foreach (var set in Set.Values)
                {
                    var parts = set.Split('=', 2);
                    if (parts.Length == 1)
                    {
                        throw new ApplicationException("Equal sign required when using the option --set name=value");
                    }

                    var name     = parts[0];
                    var value    = parts[1];
                    var segments = name.Split('.');
                    if (segments.Any(segment => string.IsNullOrEmpty(segment)))
                    {
                        throw new ApplicationException("Name must not have empty segments when using the option --set name=value");
                    }

                    var cursor = (IDictionary <object, object>)setValues;
                    foreach (var segment in segments.Reverse().Skip(1).Reverse())
                    {
                        if (cursor.TryGetValue(segment, out var child) && child is IDictionary <object, object> )
                        {
                            cursor = (IDictionary <object, object>)child;
                        }
                        else
                        {
                            child           = new Dictionary <object, object>();
                            cursor[segment] = child;
                            cursor          = (IDictionary <object, object>)child;
                        }
                    }

                    cursor[segments.Last()] = value;
                }

                eachValues.Add(setValues);
            }

            IDictionary <object, object> values = new Dictionary <object, object>();

            foreach (var addValues in eachValues)
            {
                values = (IDictionary <object, object>)MergeUtils.Merge(addValues, values) ?? values;
            }

            var(templateEngine, workflow, effectiveValues) = _workflowLoader.Load(blueprint, values, GenerateOutput);

            if (generateOnly == false)
            {
                var patternMatcher = _patternMatcherFactory.Create(Target.Values.Any() ? Target.Values : new List <string>()
                {
                    "/**"
                });

                var context = new ExecutionContext.Builder()
                              .UseBlueprintPackage(blueprint)
                              .UseTemplateEngine(templateEngine)
                              .UsePatternMatcher(patternMatcher)
                              .SetOutputDirectory(OutputDirectory.Required())
                              .SetNonInteractive(NonInteractive?.HasValue() ?? false)
                              .SetDryRun(DryRun?.HasValue() ?? false)
                              .SetValues(effectiveValues)
                              .Build();

                context.AddValuesIn(_valuesEngine.ProcessValues(workflow.values, context.Values) ?? context.Values);

                var resultOut = await _workflowEngine.ExecuteOperations(context, workflow.operations);

                if (workflow.output != null)
                {
                    context.AddValuesOut(_valuesEngine.ProcessValues(workflow.output, MergeUtils.Merge(resultOut, context.Values) ?? context.Values));
                }
                else
                {
                    context.AddValuesOut(resultOut);
                }

                if (context.ValuesOut != null)
                {
                    GenerateOutput("output.yaml", writer => _serializers.YamlSerializer.Serialize(writer, context.ValuesOut));

                    using (var writer = _secretTracker.FilterTextWriter(_console.Out))
                    {
                        _serializers.YamlSerializer.Serialize(writer, context.ValuesOut);
                    }
                }
            }

            return(0);
        }
Exemplo n.º 16
0
        public dynamic Submit(DryRun dryRun = DryRun.Off)
        {
            var context = new StoreContext();
            var type = Type.GetType(boundRecord.entityClass);
            var entitySet = context.Set(type);
            var entity = entitySet.Find(boundRecord.primaryKey);
            context.Entry(entity);
            type.GetProperty(fieldToUpdate).SetValue(entity, newValue);

            if (dryRun == DryRun.Off)
            {
                var saveResult = context.SaveChanges();
                if (saveResult > 0)
                {
                    return boundRecord.primaryKey;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return this;
            }
        }
Exemplo n.º 17
0
 public bool Submit(DryRun dryRun = DryRun.Off)
 {
     var context = new StoreContext();
     var type = Type.GetType(boundRecord.entityClass);
     var entitySet = context.Set(type);
     var entity = entitySet.Find(boundRecord.primaryKey);
     entitySet.Remove(entity);
     var result = context.SaveChanges();
     if (result > 0)
     {
         return true;
     }
     return false;
 }
Exemplo n.º 18
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
            {
                { nameof(AccessToken), AccessToken.to_string() },
                { nameof(AfterMigrationFolderName), AfterMigrationFolderName.to_string() },
                { nameof(AlterDatabaseFolderName), AlterDatabaseFolderName.to_string() },
                { nameof(Baseline), Baseline.to_string() },
                { nameof(BeforeMigrationFolderName), BeforeMigrationFolderName.to_string() },
                { nameof(CommandTimeout), CommandTimeout.to_string() },
                { nameof(CommandTimeoutAdmin), CommandTimeoutAdmin.to_string() },
                { nameof(ConfigurationFile), ConfigurationFile.to_string() },
                { nameof(ConnectionString), ConnectionString.to_string() },
                { nameof(ConnectionStringAdmin), ConnectionStringAdmin.to_string() },
                { nameof(CreateDatabaseCustomScript), CreateDatabaseCustomScript.to_string() },
                { nameof(DatabaseName), DatabaseName.to_string() },
                { nameof(DatabaseType), DatabaseType.to_string() },
                { nameof(Debug), Debug.to_string() },
                { nameof(DisableOutput), DisableOutput.to_string() },
                { nameof(DisableTokenReplacement), DisableTokenReplacement.to_string() },
                { nameof(DoNotAlterDatabase), DoNotAlterDatabase.to_string() },
                { nameof(DoNotCreateDatabase), DoNotCreateDatabase.to_string() },
                { nameof(DoNotStoreScriptsRunText), DoNotStoreScriptsRunText.to_string() },
                { nameof(DownFolderName), DownFolderName.to_string() },
                { nameof(Drop), Drop.to_string() },
                { nameof(DryRun), DryRun.to_string() },
#pragma warning disable 618
                { nameof(EnvironmentName), string.Join(",", EnvironmentNames) },
#pragma warning restore 618
                { nameof(EnvironmentNames), string.Join(",", EnvironmentNames) },
                { nameof(FunctionsFolderName), FunctionsFolderName.to_string() },
                { nameof(IndexesFolderName), IndexesFolderName.to_string() },
                { nameof(Initialize), Initialize.to_string() },
                { nameof(OutputPath), OutputPath.to_string() },
                { nameof(PermissionsFolderName), PermissionsFolderName.to_string() },
                { nameof(RecoveryMode), RecoveryMode.to_string() },
                { nameof(RepositoryPath), RepositoryPath.to_string() },
                { nameof(Restore), Restore.to_string() },
                { nameof(RestoreCustomOptions), RestoreCustomOptions.to_string() },
                { nameof(RestoreFromPath), RestoreFromPath.to_string() },
                { nameof(RestoreTimeout), RestoreTimeout.to_string() },
                { nameof(RunAfterCreateDatabaseFolderName), RunAfterCreateDatabaseFolderName.to_string() },
                { nameof(RunAfterOtherAnyTimeScriptsFolderName), RunAfterOtherAnyTimeScriptsFolderName.to_string() },
                { nameof(RunAllAnyTimeScripts), RunAllAnyTimeScripts.to_string() },
                { nameof(RunBeforeUpFolderName), RunBeforeUpFolderName.to_string() },
                { nameof(RunFirstAfterUpFolderName), RunFirstAfterUpFolderName.to_string() },
                { nameof(SchemaName), SchemaName.to_string() },
                { nameof(ScriptsRunErrorsTableName), ScriptsRunErrorsTableName.to_string() },
                { nameof(ScriptsRunTableName), ScriptsRunTableName.to_string() },
                { nameof(SearchAllSubdirectoriesInsteadOfTraverse), SearchAllSubdirectoriesInsteadOfTraverse.to_string() },
                { nameof(ServerName), ServerName.to_string() },
                { nameof(Silent), Silent.to_string() },
                { nameof(SprocsFolderName), SprocsFolderName.to_string() },
                { nameof(SqlFilesDirectory), SqlFilesDirectory.to_string() },
                { nameof(TriggersFolderName), TriggersFolderName.to_string() },
                { nameof(UpFolderName), UpFolderName.to_string() },
                { nameof(Version), Version.to_string() },
                { nameof(VersionFile), VersionFile.to_string() },
                { nameof(VersionTableName), VersionTableName.to_string() },
                { nameof(VersionXPath), VersionXPath.to_string() },
                { nameof(ViewsFolderName), ViewsFolderName.to_string() },
                { nameof(WarnAndIgnoreOnOneTimeScriptChanges), WarnAndIgnoreOnOneTimeScriptChanges.to_string() },
                { nameof(WarnOnOneTimeScriptChanges), WarnOnOneTimeScriptChanges.to_string() },
                { nameof(WithTransaction), WithTransaction.to_string() },
            };

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
Exemplo n.º 19
0
        public ConversionOptions GetConfiguration()
        {
            var options = new ConversionOptions();

            if (Path.HasValue())
            {
                options.Paths = Path.Values;
            }

            if (File.HasValue())
            {
                options.Files = File.Values;
            }

            if (List.HasValue())
            {
                options.ListFile = List.Value();
            }

            if (options.Paths.Count == 0 &&
                options.Files.Count == 0 &&
                String.IsNullOrEmpty(options.ListFile))
            {
                throw new ConfigurationException("Nothing to process, must specify one of --path, --file or --list");
            }

            if (IndentStyle.HasValue())
            {
                var style = IndentStyle.Value().ToLower();
                if (style == "tabs")
                {
                    options.Indentation = IndentationStyle.Tabs;
                }
                else if (style == "spaces")
                {
                    options.Indentation = IndentationStyle.Spaces;
                }
                else if (style == "leave")
                {
                    options.Indentation = IndentationStyle.Leave;
                }
                else
                {
                    throw new ConfigurationException($"'{style}' is an invalid indentation style");
                }
            }

            if (LineEndings.HasValue())
            {
                var lineEndingStyle = LineEndings.Value().ToLower();
                if (lineEndingStyle == "crlf")
                {
                    options.LineEndingStyle = LineEnding.CRLF;
                }
                else if (lineEndingStyle == "lf")
                {
                    options.LineEndingStyle = LineEnding.LF;
                }
                else
                {
                    throw new ConfigurationException("Line Endings must be crlf or lf");
                }
            }

            options.StripTrailingSpaces = StripTrailingSpaces.HasValue();

            // no point going any further if one of the change options isn't actually specified
            if (options.StripTrailingSpaces == false &&
                options.Indentation == IndentationStyle.Leave &&
                options.LineEndingStyle == LineEnding.Leave)
            {
                throw new ConfigurationException("Nothing to do, you must specify one of --strip-trailing-spaces, --line-endings or --indent");
            }

            if (TabWidth.HasValue())
            {
                if (!Int32.TryParse(TabWidth.Value(), out int tabWidth))
                {
                    throw new ConfigurationException("tabwidth must be a valid number");
                }
                options.TabWidth = tabWidth;
            }

            if (IncludeExtensions.HasValue())
            {
                options.IncludeExtensions = ParseFileExtensionsOption(IncludeExtensions.Values);
            }

            if (ExcludeExtensions.HasValue())
            {
                options.ExcludeExtensions = ParseFileExtensionsOption(ExcludeExtensions.Values);
            }

            if (ExcludeFolders.HasValue())
            {
                options.ExcludeFolders = ExcludeFolders.Values;
            }

            // the presence of recurse|dryrun means it's on, there is no value
            options.Recurse = Recurse.HasValue();
            options.DryRun  = DryRun.HasValue();
            options.Verbose = Verbose.HasValue();

            return(options);
        }