public int Execute()
        {
            return(ConsoleTask.Execute(this, console =>
            {
                console.WriteLine("Getting package information...");
                var dirs = SharedOptions.GetDirectories(BasePackage, OurPackage).ToList();

                var script = default(InstallScript);
                console.Write("Calculating diffs... ");
                using (var prog = new ProgressBar())
                {
                    var processor = new MergeProcessor()
                    {
                        SortDependencies = true
                    };
                    if (!string.IsNullOrEmpty(FirstOfGroup))
                    {
                        processor.FirstOfGroup.UnionWith(FirstOfGroup.Split(','));
                    }
                    processor.ProgressChanged += (s, ev) => prog.Report(ev.Progress / 100.0);
                    script = processor.Merge(dirs[0], dirs[1]);
                }
                console.WriteLine("Done.");

                SharedOptions.WritePackage(console, script, Output, MultipleDirectories, CleanOutput);
            }));
        }
Example #2
0
 public async Task <int> Execute(ILogger logger)
 {
     return(ConsoleTask.Execute(this, (console) =>
     {
         console.WriteLine("Getting package information...");
         var script = Package.Create(InputFile).Single().Read();
         SharedOptions.WritePackage(console, script, Output, MultipleDirectories, CleanOutput);
     }));
 }
Example #3
0
 public int Execute()
 {
     return(ConsoleTask.Execute(this, (console) =>
     {
         console.WriteLine("Getting package information...");
         var script = InnovatorPackage.Load(InputFile).Read();
         SharedOptions.WritePackage(console, script, Output, MultipleDirectories, CleanOutput);
     }));
 }
Example #4
0
 public int Execute()
 {
     return(ConsoleTask.Execute(this, console =>
     {
         if (!Directory.Exists(InputFile))
         {
             throw new InvalidOperationException();
         }
     }));
 }
Example #5
0
        public async static Task <int> ExecuteAsync <T>(T options, Func <ConsoleTask, Task> func, Action <ConsoleTask> config = null)
        {
            var task = new ConsoleTask();

            config?.Invoke(task);
            var verb = options.GetType().GetCustomAttributes(typeof(VerbAttribute), true)
                       .OfType <VerbAttribute>()
                       .FirstOrDefault()
                       ?.Name ?? "Task";

            verb = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(verb);
            try
            {
                task.LogWriter?.WriteLine(Parser.Default.FormatCommandLine(options));
                task.LogWriter?.WriteLine();

                await func.Invoke(task);

                task.WriteLine();
                task.WriteLine(verb + " succeeded");
                return(0);
            }
            catch (Exception ex)
            {
                var flat = ex;
                if (ex is AggregateException agg)
                {
                    flat = agg.Flatten();
                }

                task.LogWriter?.WriteLine();
                task.LogWriter?.WriteLine();

                var errorOutput = task.LogWriter;
                if (errorOutput == Console.Out)
                {
                    errorOutput = Console.Error;
                }
                errorOutput?.WriteLine(@"{0:hh\:mm\:ss} {1} failed.", task.Elapsed, verb);
                errorOutput?.WriteLine();
                errorOutput?.WriteLine(flat.ToString());
                return(-1);
            }
            finally
            {
                if (task.LogWriter != null && task.LogWriter != Console.Out)
                {
                    task.LogWriter.Dispose();
                }
            }
        }
Example #6
0
        public Task <int> Execute()
        {
            return(ConsoleTask.ExecuteAsync(this, async(console) =>
            {
                console.WriteLine("Connecting to innovator...");
                var conn = await this.GetConnection().ConfigureAwait(false);
                var processor = new InstallProcessor(conn);

                console.WriteLine("Reading the install package...");
                var script = default(InstallScript);
                if (Path.GetExtension(InputFile) == ".innpkg")
                {
                    using (var pkg = InnovatorPackage.Load(InputFile))
                        script = pkg.Read();
                }
                else
                {
                    var pkg = new ManifestFolder(InputFile);
                    var doc = pkg.Read(out var title);
                    script = await processor.ConvertManifestXml(doc, title).ConfigureAwait(false);
                }

                console.Write("Installing package `{0}`...", script.Title);
                using (var prog = console.Progress())
                {
                    var tcs = new TaskCompletionSource <int>();
                    processor.ProgressChanged += (s, e) => prog.Report(e.Progress / 100.0);
                    processor.ErrorRaised += (s, e) =>
                    {
                        tcs.TrySetException(e.Exception);
                        e.RecoveryOption = RecoveryOption.Abort;
                    };
                    processor.ActionComplete += (s, e) =>
                    {
                        if (e.Exception == null)
                        {
                            tcs.TrySetResult(0);
                        }
                        else
                        {
                            tcs.TrySetException(e.Exception);
                        }
                    };
                    await processor.Initialize(script).ConfigureAwait(false);
                    processor.Install();
                    await tcs.Task.ConfigureAwait(false);
                }
                console.WriteLine("Done.");
            }));
        }
Example #7
0
        public Task <int> Execute()
        {
            return(ConsoleTask.ExecuteAsync(this, async(console) =>
            {
                foreach (var file in GetMatchingFiles(InputFile))
                {
                    console.Write("Generating doc for ");
                    console.WriteLine(file);

                    var metadata = PackageMetadataProvider.FromFile(file);
                    var outputPath = Output.Replace("*", CleanFileName(metadata.Title));
                    var writer = new DocumentationWriter();
                    var extension = Path.GetExtension(outputPath).ToUpperInvariant().TrimStart('.');
                    switch (extension)
                    {
                    case "PUML":
                    case "TXT":
                        writer.Format = DiagramFormat.PlantUml;
                        writer.Output = DocumentOutput.Diagram;
                        break;

                    case "SVG":
                    case "PNG":
                        writer.Format = (DiagramFormat)Enum.Parse(typeof(DiagramFormat), extension, true);
                        writer.Output = DocumentOutput.Diagram;
                        break;

                    case "MD":
                        writer.Format = DiagramFormat.PlantUml;
                        writer.Output = DocumentOutput.Markdown;
                        break;
                    }

                    try
                    {
                        using (var stream = File.OpenWrite(outputPath))
                            await writer.WriteAsync(metadata, stream);
                    }
                    catch (Exception ex)
                    {
                        console.WriteLine("Error documenting " + file);
                        console.WriteLine(ex.ToString());
                    }
                }
            }));
        }
        public int Execute()
        {
            return(ConsoleTask.Execute(this, console =>
            {
                if (string.IsNullOrWhiteSpace(InputFile))
                {
                    throw new ArgumentNullException(nameof(InputFile));
                }
                if (string.IsNullOrWhiteSpace(Transform))
                {
                    throw new ArgumentNullException(nameof(Transform));
                }
                if (string.IsNullOrWhiteSpace(Output))
                {
                    throw new ArgumentNullException(nameof(Output));
                }

                if (!File.Exists(InputFile))
                {
                    throw new FileNotFoundException("Input file was not found.", InputFile);
                }
                if (!File.Exists(Transform))
                {
                    throw new FileNotFoundException("Transform file was not found.", Transform);
                }

                var logger = new Logger(console);
                using (var document = new XmlTransformableDocument())
                    using (var transformation = new XmlTransformation(Transform, logger))
                    {
                        document.PreserveWhitespace = true;
                        document.Load(InputFile);

                        var success = transformation.Apply(document);

                        if (success)
                        {
                            document.Save(Output);
                        }
                        else
                        {
                            throw new AggregateException(logger.Exceptions);
                        }
                    }
            }));
        }
Example #9
0
        public Task <int> Execute(ILogger logger)
        {
            return(ConsoleTask.ExecuteAsync(this, async(console) =>
            {
                console.WriteLine("Connecting to innovator...");
                var conn = await GetConnection().ConfigureAwait(false);

                console.WriteLine("Reading input...");
                var stream = string.IsNullOrEmpty(InputFile) ? console.ReadInput() : new FileStream(InputFile, FileMode.Open, FileAccess.Read);
                var cmd = default(Command);
                if (string.IsNullOrEmpty(SoapAction))
                {
                    var input = conn.AmlContext.FromXml(stream);
                    cmd = new Command(input);
                    if (input.Items().Count() > 1)
                    {
                        cmd.WithAction(CommandAction.ApplyAML);
                    }
                }
                else
                {
                    cmd = new Command(stream.AsString());
                }

                console.WriteLine("Calling action...");
                var result = (await conn.ApplyAsync(cmd, true, false).ConfigureAwait(false)).AssertNoError();

                console.WriteLine("Writing output...");
                using (var output = string.IsNullOrEmpty(Output) ? Console.Out : new StreamWriter(Output))
                    using (var xml = XmlWriter.Create(output))
                    {
                        result.ToAml(xml);
                    }
            }, console =>
            {
                if (string.IsNullOrEmpty(Output))
                {
                    console.LogWriter = string.IsNullOrEmpty(LogFile) ? null : new StreamWriter(LogFile);
                }
            }));
        }
Example #10
0
        public int Execute()
        {
            return(ConsoleTask.Execute(this, console =>
            {
                console.WriteLine("Getting package information...");
                var elem = XElement.Load(InputFile);

                if (RemoveMetadata)
                {
                    elem.Attribute("created")?.Remove();
                    elem.Attribute("creator")?.Remove();
                    elem.Attribute("modified")?.Remove();
                }

                var baseDir = Path.GetDirectoryName(InputFile);
                foreach (var path in elem.Elements("Path").ToList())
                {
                    var fullPath = Path.Combine(baseDir, path.Attribute("path")?.Value);
                    if (!File.Exists(fullPath))
                    {
                        Console.WriteLine("Removing reference to `{0}`", path.Attribute("path")?.Value);
                        path.Remove();
                    }
                }

                console.WriteLine("Writing file...");
                using (var writer = XmlWriter.Create(InputFile, new XmlWriterSettings()
                {
                    OmitXmlDeclaration = true,
                    Indent = true
                }))
                {
                    elem.Save(writer);
                }
            }));
        }
        public Task <int> Execute()
        {
            return(ConsoleTask.ExecuteAsync(this, async(console) =>
            {
                console.WriteLine("Connecting to innovator...");
                var conn = await this.GetConnection().ConfigureAwait(false);
                var processor = new ExportProcessor(conn);

                var refsToExport = default(List <ItemReference>);
                var checkDependencies = true;

                console.Write("Identifying items to export... ");
                if (this.InputFile?.EndsWith(".innpkg", StringComparison.OrdinalIgnoreCase) == true ||
                    this.InputFile?.EndsWith(".mf", StringComparison.OrdinalIgnoreCase) == true)
                {
                    var exportScript = InnovatorPackage.Load(this.InputFile).Read();
                    refsToExport = exportScript.Lines
                                   .Where(l => l.Type == InstallType.Create)
                                   .Select(l => l.Reference)
                                   .Distinct()
                                   .ToList();
                }
                else
                {
                    var exportQuery = XElement.Parse("<AML><Item type='*' /></AML>");
                    if (!string.IsNullOrEmpty(this.InputFile))
                    {
                        exportQuery = XElement.Load(this.InputFile);
                    }

                    var firstItem = exportQuery.XPathSelectElement("//Item[1]");
                    if (firstItem == null)
                    {
                        throw new Exception("No item nodes could be found");
                    }

                    var items = default(IEnumerable <XElement>);
                    if (firstItem.Parent == null)
                    {
                        items = new[] { firstItem }
                    }
                    ;
                    else
                    {
                        items = firstItem.Parent.Elements("Item");
                    }

                    var version = await conn.FetchVersion(true).ConfigureAwait(false);
                    var types = ExportAllType.Types.Where(t => t.Applies(version)).ToList();
                    var queries = GetQueryies(items, types).ToList();
                    checkDependencies = items.All(e => e.Attribute("type")?.Value != "*");

                    using (var prog = console.Progress())
                    {
                        var toExport = await SharedUtils.TaskPool(30, (l, m) => prog.Report(l / 100.0), queries
                                                                  .Select(q =>
                        {
                            var aml = new XElement(q);
                            var levels = aml.Attribute("levels");
                            if (levels != null)
                            {
                                levels.Remove();
                            }
                            return (Func <Task <QueryAndResult> >)(() => conn.ApplyAsync(aml, true, false)
                                                                   .ToTask()
                                                                   .ContinueWith(t => new QueryAndResult()
                            {
                                Query = q,
                                Result = t.Result
                            }));
                        })
                                                                  .ToArray());
                        refsToExport = toExport.SelectMany(r =>
                        {
                            var refs = r.Result.Items()
                                       .Select(i => ItemReference.FromFullItem(i, true))
                                       .ToList();
                            var levels = (int?)r.Query.Attribute("levels");
                            if (levels.HasValue)
                            {
                                foreach (var iRef in refs)
                                {
                                    iRef.Levels = levels.Value;
                                }
                            }
                            return refs;
                        })
                                       .ToList();
                    }
                }
                console.WriteLine("Done.");

                var script = new InstallScript
                {
                    ExportUri = new Uri(Url),
                    ExportDb = Database,
                    Lines = Enumerable.Empty <InstallItem>(),
                    Title = Title ?? System.IO.Path.GetFileNameWithoutExtension(Output),
                    Creator = Author ?? Username,
                    Website = string.IsNullOrEmpty(Website) ? null : new Uri(Website),
                    Description = Description,
                    Created = DateTime.Now,
                    Modified = DateTime.Now
                };

                console.Write("Exporting metadata... ");
                using (var prog = console.Progress())
                {
                    processor.ProgressChanged += (s, e) => prog.Report(e.Progress / 100.0);
                    processor.ActionComplete += (s, e) =>
                    {
                        if (e.Exception != null)
                        {
                            throw new AggregateException(e.Exception);
                        }
                    };
                    await processor.Export(script, refsToExport, checkDependencies);
                }
                console.WriteLine("Done.");

                WritePackage(console, script, Output, MultipleDirectories, CleanOutput);
            }));
        }
Example #12
0
        public static void WritePackage(ConsoleTask console, InstallScript script, string output, bool multipleDirectories, bool cleanOutput)
        {
            multipleDirectories = multipleDirectories || string.Equals(Path.GetExtension(output), ".mf", StringComparison.OrdinalIgnoreCase);

            if (cleanOutput)
            {
                console.Write("Cleaning output... ");
                if (multipleDirectories)
                {
                    var dir = new DirectoryInfo(Path.GetDirectoryName(output));
                    if (dir.Exists)
                    {
                        Parallel.ForEach(dir.EnumerateFileSystemInfos(), fs =>
                        {
                            if (fs is DirectoryInfo di)
                            {
                                di.Delete(true);
                            }
                            else
                            {
                                fs.Delete();
                            }
                        });
                    }
                    else
                    {
                        dir.Create();
                    }
                }
                else
                {
                    File.Delete(output);
                }
                console.WriteLine("Done.");
            }

            console.Write("Writing package... ");
            var outputDir = Path.GetDirectoryName(output);

            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }

            switch (Path.GetExtension(output).ToLowerInvariant())
            {
            case ".mf":
                var manifest = new ManifestFolder(output);
                manifest.Write(script);
                break;

            case ".innpkg":
                if (multipleDirectories)
                {
                    using (var pkgFolder = new InnovatorPackageFolder(output))
                        pkgFolder.Write(script);
                }
                else
                {
                    if (File.Exists(output))
                    {
                        File.Delete(output);
                    }
                    using (var pkgFile = new InnovatorPackageFile(output))
                        pkgFile.Write(script);
                }
                break;

            default:
                throw new NotSupportedException("Output file type is not supported");
            }
            console.WriteLine("Done.");
        }
 public Logger(ConsoleTask console)
 {
     _console = console;
 }
        public Task <int> Execute()
        {
            return(ConsoleTask.ExecuteAsync(this, async(console) =>
            {
                console.WriteLine("Connecting to innovator...");
                var conn = await this.GetConnection().ConfigureAwait(false);
                var processor = new ExportProcessor(conn);

                var refsToExport = default(List <ItemReference>);
                var checkDependencies = true;

                if (string.IsNullOrEmpty(this.InputFile))
                {
                    var version = await conn.FetchVersion(true).ConfigureAwait(false);
                    var types = ExportAllType.Types.Where(t => t.Applies(version)).ToList();

                    console.Write("Identifying all metadata items... ");
                    using (var prog = console.Progress())
                    {
                        var toExport = await SharedUtils.TaskPool(30, (l, m) => prog.Report(l / 100.0), types
                                                                  .Select(t => (Func <Task <IReadOnlyResult> >)(() => conn.ApplyAsync(t.ToString(), true, false).ToTask()))
                                                                  .ToArray());
                        refsToExport = toExport.SelectMany(r => r.Items())
                                       .Select(i => ItemReference.FromFullItem(i, true))
                                       .ToList();
                    }
                    console.WriteLine("Done.");

                    checkDependencies = false;
                }
                else
                {
                    throw new NotSupportedException("Input package is not supported");
                }

                var script = new InstallScript
                {
                    ExportUri = new Uri(Url),
                    ExportDb = Database,
                    Lines = Enumerable.Empty <InstallItem>(),
                    Title = Title ?? System.IO.Path.GetFileNameWithoutExtension(Output),
                    Creator = Author ?? Username,
                    Website = string.IsNullOrEmpty(Website) ? null : new Uri(Website),
                    Description = Description,
                    Created = DateTime.Now,
                    Modified = DateTime.Now
                };

                console.Write("Exporting metadata... ");
                using (var prog = console.Progress())
                {
                    processor.ProgressChanged += (s, e) => prog.Report(e.Progress / 100.0);
                    processor.ActionComplete += (s, e) =>
                    {
                        if (e.Exception != null)
                        {
                            throw new AggregateException(e.Exception);
                        }
                    };
                    await processor.Export(script, refsToExport, checkDependencies);
                }
                console.WriteLine("Done.");

                WritePackage(console, script, Output, MultipleDirectories, CleanOutput);
            }));
        }