Exemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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);
        }