Exemple #1
0
        public override void Run(IEnumerable <string> args)
        {
            PackOptions op = new PackOptions();

            ArgumentSyntaxParser.Parse(args.Skip(1).ToArray(), op);
            Pack(args.First(), op);
        }
Exemple #2
0
 private void TransformProperties(PackOptions packOptions, ProjectPropertyGroupElement propertyGroup)
 {
     foreach (var propertyTransfrom in _propertyTransforms)
     {
         _transformApplicator.Execute(propertyTransfrom.Transform(packOptions), propertyGroup, true);
     }
 }
Exemple #3
0
 public Package(PackOptions options)
 {
     _options     = options;
     _outputPath  = new DirectoryInfo(_options.TargetPath);
     _inputPath   = new DirectoryInfo(_options.SourcePath);
     _signingTool = new SigningTool(_options.Ed25519PrivateKeyPath);
 }
Exemple #4
0
        public string[] CreateArguments(string projectPath, PackOptions options)
        {
            var arguments = new List <string> {
                projectPath
            };
            var properties = _propertiesCache.Value;

            foreach (var property in properties)
            {
                var propertyType  = property.Property.PropertyType;
                var propertyValue = property.Property.GetValue(options);

                if (propertyValue == null)
                {
                    _logger.LogInformation("Skipping {Property} with alias {Alias} because it's value is null",
                                           property.Property.Name, property.Option.Alias);

                    continue;
                }

                if (propertyType == typeof(bool))
                {
                    if ((bool)propertyValue)
                    {
                        arguments.Add(property.Option.Alias);

                        _logger.LogInformation("Added flag {Property} with alias {Alias}",
                                               property.Property.Name, property.Option.Alias);
                    }
                    else
                    {
                        _logger.LogInformation("Skipping {Property} with alias {Alias} because it's value is false",
                                               property.Property.Name, property.Option.Alias);
                    }
                }
                else
                {
                    var converter = TypeDescriptor.GetConverter(propertyType);
                    var strValue  = converter.ConvertToInvariantString(propertyValue);

                    arguments.Add(property.Option.Alias);
                    arguments.Add(strValue);

                    _logger.LogInformation("Added property {Property} with alias {Alias} and value {Value}",
                                           property.Property.Name, property.Option.Alias, strValue);
                }
            }

            if (options.Parameters != null)
            {
                foreach (var parameter in options.Parameters)
                {
                    arguments.Add(parameter);
                    _logger.LogInformation("Added {Parameter}", parameter);
                }
            }

            return(arguments.ToArray());
        }
Exemple #5
0
 internal static void Generate(Atlas Atlas, ChartOptions ChartOptions, PackOptions PackOptions)
 {
     XAtlasPINVOKE.Generate__SWIG_0(Atlas.getCPtr(Atlas), ChartOptions.getCPtr(ChartOptions), PackOptions.getCPtr(PackOptions));
     if (XAtlasPINVOKE.SWIGPendingException.Pending)
     {
         throw XAtlasPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemple #6
0
        /// <summary>
        /// Invoke
        /// </summary>
        public async Task InvokeAsync(PackOptions options)
        {
            var recipe = await RecipeManager.LoadFromFileAsync(@"./");

            Log.Info($"Packaging Project: {recipe.Name}@{recipe.Version}");

            await PackageManager.PackAsync(recipe, Directory.GetCurrentDirectory());
        }
Exemple #7
0
 internal static void PackCharts(Atlas Atlas, PackOptions PackOptions)
 {
     XAtlasPINVOKE.PackCharts__SWIG_0(Atlas.getCPtr(Atlas), PackOptions.getCPtr(PackOptions));
     if (XAtlasPINVOKE.SWIGPendingException.Pending)
     {
         throw XAtlasPINVOKE.SWIGPendingException.Retrieve();
     }
 }
Exemple #8
0
        private PackOptions CreatePackOptions()
        {
            var originalPackOptions = new PackOptions();

            originalPackOptions.PackageType = new List <PackageType>()
            {
                new PackageType("PackageA", new System.Version("1.0.0"))
            };
            originalPackOptions.IncludeExcludeFiles = CreateIncludeExcludeFiles();
            return(originalPackOptions);
        }
Exemple #9
0
        private void TransformPackFiles(PackOptions packOptions, ProjectItemGroupElement itemGroup)
        {
            var transformResult = PackFilesTransform.Transform(packOptions.PackInclude);

            if (transformResult != null && transformResult.Any())
            {
                _transformApplicator.Execute(
                    transformResult,
                    itemGroup,
                    mergeExisting: true);
            }
        }
Exemple #10
0
        private void TransformPackFiles(PackOptions packOptions, ProjectItemGroupElement itemGroup)
        {
            ExecuteTransformation(PackFilesTransform, packOptions.PackInclude, itemGroup);

            if (packOptions.PackInclude != null)
            {
                ExecuteTransformation(
                    DoNotPackFilesTransform,
                    new ExcludeContext(
                        packOptions.PackInclude.SourceBasePath,
                        packOptions.PackInclude.Option,
                        packOptions.PackInclude.RawObject,
                        packOptions.PackInclude.BuiltInsInclude?.ToArray(),
                        packOptions.PackInclude.BuiltInsExclude?.ToArray()),
                    itemGroup);
            }
        }
Exemple #11
0
        /// <summary>
        /// Produce an update package using a ED25519 private key to create signatures.
        /// </summary>
        /// <param name="options"></param>
        private static void RunPackaging(PackOptions options)
        {
            #region validate args

            if (!Directory.Exists(options.SourcePath))
            {
                _log.Fatal("Source directory doesn't exist");
                Environment.Exit(Codes.ERROR_SRC_DIR_MISSING);
            }

            if (Directory.Exists(options.TargetPath) && Directory.GetFiles(options.TargetPath).Any())
            {
                _log.Error("Out directory is not empty");
                Environment.Exit(Codes.ERROR_OUT_DIR_NOT_EMPTY);
            }

            if (string.IsNullOrEmpty(options.Ed25519PrivateKeyPath))
            {
                options.Ed25519PrivateKeyPath = "private_key.json";
            }

            if (!File.Exists(options.Ed25519PrivateKeyPath))
            {
                _log.Fatal("Provided Ed25519 Private Key file doesn't exist");
                Environment.Exit(Codes.ERROR_PRIV_KEY_MISSING);
            }

            if (string.IsNullOrEmpty(options.PackageInfoSavePath))
            {
                options.PackageInfoSavePath = $"{options.TargetPath}";
                _log.Warning($"Output path for packageInfo was not provided. Using default path {options.PackageInfoSavePath}");
            }

            #endregion

            _log.Information($"Package creation started: AppId: {options.ApplicationId} Version: {options.Version}");
            _log.Information($"Source path: {options.SourcePath}");
            _log.Information($"Output path: {options.TargetPath}");

            var package     = new Package(options);
            var packageInfo = package.Build();

            packageInfo.SaveToFile(options.PackageInfoSavePath);
        }
Exemple #12
0
        public CommandLineParserTests(ITestOutputHelper output)
        {
            _output = output;

            _parser = CommandLineParser.Create(
                new ServiceCollection(),
                startServer: (options, invocationContext) =>
            {
                _startOptions = options;
            },
                demo: (options, console, context, startOptions) =>
            {
                _demoOptions = options;
                return(Task.CompletedTask);
            },
                tryGithub: (options, c) =>
            {
                _tryGitHubOptions = options;
                return(Task.CompletedTask);
            },
                pack: (options, console) =>
            {
                _packOptions = options;
                return(Task.CompletedTask);
            },
                install: (options, console) =>
            {
                _installOptions       = options;
                _installPackageSource = options.AddSource;
                return(Task.CompletedTask);
            },
                verify: (options, console, startupOptions) =>
            {
                _verifyOptions = options;
                return(Task.FromResult(0));
            },
                telemetry: new FakeTelemetry(),
                publish: (options, console, startupOptions) =>
            {
                _publishOptions = options;
                return(Task.FromResult(0));
            },
                firstTimeUseNoticeSentinel: new NopFirstTimeUseNoticeSentinel());
        }
Exemple #13
0
        public CommandLineParserTests(ITestOutputHelper output)
        {
            _output = output;

            _parser = CommandLineParser.Create(
                startServer: (options, invocationContext) =>
            {
                _start_options = options;
            },
                demo: (options, console, context, startOptions) =>
            {
                _demoOptions = options;
                return(Task.CompletedTask);
            },
                tryGithub: (options, c) =>
            {
                _tryGitHubOptions = options;
                return(Task.CompletedTask);
            },
                pack: (options, console) =>
            {
                _packOptions = options;
                return(Task.CompletedTask);
            },
                install: (options, console) =>
            {
                _installOptions        = options;
                _install_packageSource = options.AddSource;
                return(Task.CompletedTask);
            },
                verify: (options, console, startupOptions) =>
            {
                _verifyOptions = options;
                return(Task.FromResult(1));
            },
                jupyter: (options, console, startServer, context) =>
            {
                _jupyter_Options = options;
                return(Task.FromResult(1));
            });
        }
Exemple #14
0
        public static void Pack(string projectRoot, PackOptions options)
        {
            string src = Path.Combine(Path.GetFullPath(projectRoot), "project.json");

            ProjectCleanSubSystem.Clean(Path.GetDirectoryName(src));
            Logger.LogMessage(LoggerSystems.ModuleSystem, "Packing '{0}'", src);

            string outDir = Path.Combine(Path.GetDirectoryName(src), "build");

            ProjectConfig t = ProjectConfig.Load(src);

            Version v = Version.Parse(t.ProjectVersion);

            t.ProjectVersion = ChangeVersion(v, options.VersionString).ToString();
            ProjectConfig.Save(src, t);

            string temp = Path.Combine(
                Path.GetDirectoryName(Directory.GetCurrentDirectory()),
                "temp_" + t.ProjectName
                );

            Directory.CreateDirectory(temp);

            CopyTo(Path.GetDirectoryName(src), temp);

            foreach (ProjectDependency moduleDependency in t.Dependencies)
            {
                string p = Path.Combine(temp, moduleDependency.ProjectName);

                if (Directory.Exists(p))
                {
                    Directory.Delete(p, true);
                }
            }

            Directory.CreateDirectory(outDir);
            ZipFile.CreateFromDirectory(temp, Path.Combine(outDir, "module.zip"));
            Directory.Delete(temp, true);
            ProjectConfig.Save(Path.Combine(outDir, "module.json"), t);
        }
Exemple #15
0
        private static object RunPackAndReturnExitCode(PackOptions options)
        {
            if (!Enum.TryParse(options.GameType, out GameVolumeType game) || game is GameVolumeType.Unknown)
            {
                Console.WriteLine("Error: Invalid game type provided.");
                return(1);
            }

            uint tocOffset;

            if (game == GameVolumeType.CUSTOM)
            {
                if (options.TocOffset <= -1)
                {
                    Console.WriteLine("Error: No custom toc offset provided.");
                    return(1);
                }

                tocOffset = (uint)options.TocOffset;
            }
            else
            {
                tocOffset = RoFSBuilder.GetRealToCOffsetForGame(game);
            }

            var fsBuilder = new RoFSBuilder();

            /*
             * if (options.BlockSize != 0)
             *  fsBuilder.SetBlockSize(options.BlockSize);
             */

            fsBuilder.SetCompressed(!options.NoCompress);
            fsBuilder.SetEncrypted(!options.Decrypted);
            fsBuilder.RegisterFilesToPack(options.Input);
            fsBuilder.Build(options.Output, tocOffset);

            return(0);
        }
Exemple #16
0
        private static int RunPack(PackOptions options)
        {
            ContentDefinition def = null;

            if (options.ContentDefinition != null)
            {
                using (var defFs = new FileStream(options.ContentDefinition, FileMode.Open, FileAccess.Read))
                    def = AuthoringUtil.JsonDeserialize <ContentDefinition>(defFs);
            }

            var bList = new List <FileInfo>();

            if (options.Resources != null)
            {
                foreach (var res in options.Resources)
                {
                    bList.Add(new FileInfo(res));
                }
            }
            var metaList = new List <MutableKeyValuePair <string, int> >();

            foreach (var ent in bList)
            {
                metaList.Add(new MutableKeyValuePair <string, int>(ent.Name, (int)ent.Length));
            }
            using (var ofs = new FileStream(options.TargetFile, FileMode.Create, FileAccess.Write)) {
                CzBox.WriteHead(ofs, def, metaList);
                foreach (var ent in bList)
                {
                    using (var eStream = ent.OpenRead())
                        eStream.CopyTo(ofs);
                }
            }

            return(0);
        }
Exemple #17
0
        public void CreatePackage(PackOptions options)
        {
            var package = new Package
            {
                Path     = options.Folder,
                Manifest =
                    this.manifestBuilder.Build(Path.GetFileNameWithoutExtension(options.PackagePath), options.Folder,
                                               options.TokensPairs.Select(x => x.Value).ToList())
            };

            var clonedPackage    = this.clonePackageBuilder.Build(package);
            var tokenizedPackage = this.packageTokeniser.Tokenise(clonedPackage, options.TokensPairs);

            var resultFile = string.IsNullOrEmpty(Path.GetExtension(options.PackagePath))
                ? options.PackagePath + ".pkg"
                : options.PackagePath;

            this.ioHelper.RemoveFile(resultFile);

            ZipFile.CreateFromDirectory(tokenizedPackage.Path, resultFile, CompressionLevel.Optimal, false);

            this.ioHelper.DeleteDirectory(clonedPackage.Path);
            this.ioHelper.DeleteDirectory(tokenizedPackage.Path);
        }
Exemple #18
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(PackOptions obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Exemple #19
0
        public void PackOptionsCloneTest()
        {
            //Set up
            var originalPackOptions = new PackOptions();
            var originalPackageName = "PackageA";
            var packageTypes        = new List <NuGet.Packaging.Core.PackageType>()
            {
                new Packaging.Core.PackageType(originalPackageName, new System.Version("1.0.0"))
            };

            var exclude = new List <string>()
            {
                "Exlclude0"
            };
            var include = new List <string>()
            {
                "Include0"
            };
            var includeFiles = new List <string>()
            {
                "IncludeFiles0"
            };
            var excludeFiles = new List <string>()
            {
                "ExlcludeFiles0"
            };

            var files = new IncludeExcludeFiles();

            files.Exclude      = exclude;
            files.Include      = include;
            files.IncludeFiles = includeFiles;
            files.ExcludeFiles = excludeFiles;

            originalPackOptions.PackageType         = packageTypes;
            originalPackOptions.IncludeExcludeFiles = files;

            // Act
            var clone = originalPackOptions.Clone();

            // Assert
            Assert.Equal(originalPackOptions, clone);

            // Act again
            packageTypes.Clear();

            // Assert
            Assert.NotEqual(originalPackOptions, clone);
            Assert.Equal(originalPackageName, clone.PackageType[0].Name);

            // Set Up again
            originalPackOptions.Mappings.Add("randomString", files);

            // Act again
            var cloneWithMappings = originalPackOptions.Clone();

            // Assert
            Assert.Equal(originalPackOptions, cloneWithMappings);

            // Act again
            originalPackOptions.Mappings.Clear();

            // Assert
            Assert.NotEqual(originalPackOptions, cloneWithMappings);
            Assert.Equal(1, cloneWithMappings.Mappings.Count);
        }
        /// <summary>
        /// Turn a list of images into a packed sprite image and matching css file
        /// </summary>
        /// <param name="pOptions"></param>
        /// <param name="oResults">result messages</param>
        /// <returns>true/false for success</returns>
        public static bool CombineImages(PackOptions pOptions, out List<string> oResults)
        {
            oResults = new List<string>();

            long inputFileTotalSize = 0;
            long outputFileSize = 0;
            long areaTotalImages = 0;
            long areaTotalFrames = 0;
            long areaImage = 0;
            long areaFrame = 0;
            int widestImage = 0;
            int tallestImage = 0;

            var cssBuffer = new StringBuilder();
            var testPage = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(pOptions.CssHeaderText))
                cssBuffer.AppendLine(pOptions.CssHeaderText);

            pOptions.ImageFilePaths.Sort(); //doing this as a debugging test

            var frameArray = new List<ImageFrame>();
            foreach (string imageFilePath in pOptions.ImageFilePaths)
            {
                if (File.Exists(imageFilePath))
                {
                    inputFileTotalSize += new FileInfo(imageFilePath).Length;

                    using (var image = Image.FromFile(imageFilePath))
                    {
                        var frame = new ImageFrame(imageFilePath, image.Width, image.Height);
                        frameArray.Add(frame);
                        #region Debugging and Error Checking
                        if (image.Width > widestImage)
                            widestImage = image.Width;
                        if (image.Height > tallestImage)
                            tallestImage = image.Height;

                        areaImage = (image.Width * image.Height);
                        areaFrame = (frame.Width * frame.Height);

                        areaTotalImages += areaImage;
                        areaTotalFrames += areaFrame;

                        if (image.Width != frame.Width
                            || image.Height != frame.Height
                            || areaImage != frame.Area)
                        {
                            oResults.Add(string.Format("Error: Image>Frame conversion size is incorrect: {0} ", imageFilePath));
                            oResults.Add(string.Format("H/W/A: Image:{0}/{1}/{2}, Frame:{3}/{4}/{5}"
                                , image.Height, image.Width, areaImage
                                , frame.Height, frame.Width, frame.Area
                                ));
                        }
                        #endregion
                    }
                }
                else
                {
                    oResults.Add(string.Format("Could not find file: {0} ", imageFilePath));
                    if (pOptions.TreatInputFileNotFoundAsError)
                        return false;
                }
            }

            long minArea = tallestImage * widestImage;
            if (areaTotalFrames > minArea)
                minArea = areaTotalFrames;
            var pref = ImageLayoutHelper.PackPreference.ByWidth;
            if (widestImage > tallestImage)
                pref = ImageLayoutHelper.PackPreference.ByHeight;

            int optimalTotalWidth = (int)Math.Ceiling(Math.Sqrt(minArea));
            if (optimalTotalWidth < widestImage)
                optimalTotalWidth = widestImage;
            optimalTotalWidth = GetNextPowerOf2(optimalTotalWidth, false);

            oResults.Add(string.Format("Tallest Image: {0:0,0} ", tallestImage));
            oResults.Add(string.Format("Widest Image: {0:0,0} ", widestImage));
            oResults.Add(string.Format("Total Image Area: {0:0,0} ", areaTotalFrames));
            oResults.Add(string.Format("Smallest Possible Area: {0:0,0} ", minArea));
            oResults.Add(string.Format("Optimal Width: {0:0,0} ", optimalTotalWidth));
            oResults.Add(string.Format("PackPreference: {0} ", pref));

            ImageFrame layoutFrame = ImageLayoutHelper.LayImageFrames(frameArray, optimalTotalWidth);
            List<ImageFrame> framesList = layoutFrame.GetFlatList();

            using (var bitmap = new Bitmap(layoutFrame.Width, layoutFrame.Height))
            {
                using (var g = Graphics.FromImage(bitmap))
                {
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic; //http://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.interpolationmode.aspx
                    g.SmoothingMode = SmoothingMode.None;                       //http://msdn.microsoft.com/en-us/library/z714w2y9.aspx
                    g.PixelOffsetMode = PixelOffsetMode.None;                   //http://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.pixeloffsetmode.aspx
                    g.CompositingQuality = CompositingQuality.HighQuality;      //http://msdn.microsoft.com/en-us/library/system.drawing.drawing2d.compositingquality.aspx

                    if (pOptions.GenerateTestHtmlPage)
                        testPage.AppendFormat("<h1>{0} Images</h1>", framesList.Count);
                    var testPageAltClass = "a";

                    foreach (var f in framesList)
                    {
                        using (var image = Image.FromFile(f.Id))
                        {
                            g.DrawImage(image, f.OffsetX, f.OffsetY, f.Width, f.Height);
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_CSS_CLASS_NAME_BASE] = GetOutputCssClassNameFromFilename(
                                    Path.GetFileName(f.Id).Substring(0, Path.GetFileName(f.Id).LastIndexOf("."))
                                    , pOptions.CssClassNameInvalidCharReplacement
                                    , pOptions.ValidSpriteClassNameCharacters);
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_WIDTH] = f.Width.ToString();
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_HEIGHT] = f.Height.ToString();
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_IMAGE_FILE_NAME] = Path.GetFileName(pOptions.ImageOutputFilePath);
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_OFFSET_X] = (-f.OffsetX).ToString();
                            pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_OFFSET_Y] = (-f.OffsetY).ToString();

                            var currentStyle = new StringBuilder(pOptions.CssFormatStringForSpriteDefinition);
                            foreach (KeyValuePair<string, string> entry in pOptions.CssPlaceholderValues)
                                currentStyle.Replace(entry.Key, entry.Value);

                            cssBuffer.AppendLine(currentStyle.ToString());
                            if (pOptions.GenerateTestHtmlPage)
                            {
                                testPageAltClass = testPageAltClass == "a" ? "" : "a";
                                testPage.AppendFormat("<tr class='{4}'><td>{0}{1}</td><td>{2}</td><td>{3}</td><td><img src='{5}' class='{0}{1}' title='{0}{1}' /></td></tr>"
                                    , pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_CSS_CLASS_NAME_PREFIX] + pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_CSS_CLASS_NAME_BASE]
                                    , pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_CSS_CLASS_NAME_SUFFIX]
                                    , f.Height
                                    , f.Width
                                    , testPageAltClass
                                    , pOptions.TestHtmlClearGifUrl
                                );
                            }
                        }
                    }
                }

                string imageOutputFilePath = pOptions.ImageOutputFilePath;

                File.WriteAllText(pOptions.CssOutputFilePath, cssBuffer.ToString());
                if (pOptions.GenerateTestHtmlPage)
                {
                    var css = cssBuffer.ToString();
                    if (!string.IsNullOrWhiteSpace(pOptions.TestHtmlImageDeployUrlBase))
                        css = css.Replace(pOptions.CssPlaceholderValues[pOptions.CSS_PLACEHOLDER_IMAGE_DEPLOY_URL_BASE], pOptions.TestHtmlImageDeployUrlBase);

                    var htmlForRows = testPage.ToString();
                    var html = string.Format("<html><head><title>CSS Sprite Preview for: {0}</title>{3}<style>body {1}background-color:#eeeeff;{2} img {1}margin:1px;border:solid 1px red;{2} TH {1}background-color:#bbbbbb;{2} TD {1}background-color:#cccccc;{2} TR.a TD {1}background-color:#DDDDDD;{2}  .clickable {1}cursor:pointer;cursor:hand;{2} {4}</style></head><body><table class='sortable' cellspacing=0 cellpadding=5><tr><td class=clickable>Css Class</td><td class=clickable>Height</td><td class=clickable>Width</td><td>Preview</td></tr>",
                        Path.GetFileName(pOptions.CssOutputFilePath), "{", "}", pOptions.TestHtmlHeadIncludes, css)
                        + htmlForRows
                        + "</table></body></html>";

                    var testFilePath = pOptions.CssOutputFilePath + pOptions.TestHtmlFilenameSuffix;
                    if (!string.IsNullOrWhiteSpace(pOptions.TestHtmlPath))
                        testFilePath = Path.Combine(pOptions.TestHtmlPath, Path.GetFileName(pOptions.CssOutputFilePath) + pOptions.TestHtmlFilenameSuffix);

                    File.WriteAllText(testFilePath, html);
                    oResults.Add("Successfully generated the CSS test html file to: " + testFilePath);
                }

                oResults.Add("Successfully generated the corresponding CSS file to: " + pOptions.CssOutputFilePath);

                //option for reducing the output bit depth using OctreeQuantizer
                if (pOptions.LimitOutputImageTo8Bits)
                {
                    var octreeQuantizer = new OctreeQuantizer(OctreeQuantizer.BitDepth.Bits8);
                    using (var quantizedBitmap = octreeQuantizer.Quantize(bitmap))
                    {
                        quantizedBitmap.Save(imageOutputFilePath, pOptions.OutputImageFormat);
                        oResults.Add(string.Format("Limited {0} to {1} bits using OctreeQuantizer", imageOutputFilePath, 8));
                    }
                }
                else
                {
                    bitmap.Save(imageOutputFilePath, pOptions.OutputImageFormat);
                }

                //if (pOptions.MakeTransparentUsingColorKey)
                //{
                //    Color c = bitmap.GetPixel(0, 0); or use passed in coordinate or color
                //    bitmap.MakeTransparent(c);
                //    var bitmapT = Transparency.MakeTransparent(bitmap, Color.Transparent);
                //}

                oResults.Add(string.Format("New sprite: {0} ", imageOutputFilePath));
                outputFileSize = new FileInfo(imageOutputFilePath).Length;
                oResults.Add(string.Format("Successfully converted {0} files of cumulative size {1} bytes into one file of size {2} bytes."
                    , pOptions.ImageFilePaths.Count, inputFileTotalSize, outputFileSize));

            }
            return true;
        }
Exemple #21
0
        public int Main(string[] args)
        {
            var app = new CommandLineApplication();

            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);

            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand/option was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(2);
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot   = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                                         CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                                                 "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                                        CommandOptionType.SingleValue);
                var optNoCache       = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet         = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                                                CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                                                      "Ignore failed remote sources if there are local packages meeting version requirements",
                                                      CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var command     = new RestoreCommand(_environment);
                    command.Reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    command.RestoreDirectory    = argRoot.Value;
                    command.Sources             = optSource.Values;
                    command.FallbackSources     = optFallbackSource.Values;
                    command.NoCache             = optNoCache.HasValue();
                    command.PackageFolder       = optPackageFolder.Value();
                    command.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var success = await command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject          = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut           = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment", CommandOptionType.SingleValue);
                var optionOverwrite     = c.Option("--overwrite", "Remove existing files in target folders",
                                                   CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Don't include sources of project dependencies",
                                              CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <KRE>", "Names or paths to KRE files to include",
                                             CommandOptionType.MultipleValue);
                var optionNative = c.Option("--native", "Build and include native images. User must provide targeted CoreCLR runtime versions along with this option.",
                                            CommandOptionType.NoValue);
                var optionWwwRoot = c.Option("--wwwroot <NAME>", "Name of public folder in the project directory",
                                             CommandOptionType.SingleValue);
                var optionWwwRootOut = c.Option("--wwwroot-out <NAME>",
                                                "Name of public folder in the packed image, can be used only when the '--wwwroot' option or 'webroot' in project.json is specified",
                                                CommandOptionType.SingleValue);
                var optionQuiet = c.Option("--quiet", "Do not show output such as source/destination of packed files",
                                           CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var options = new PackOptions
                    {
                        OutputDir              = optionOut.Value(),
                        ProjectDir             = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        Configuration          = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.RuntimeFramework,
                        WwwRoot    = optionWwwRoot.Value(),
                        WwwRootOut = optionWwwRootOut.Value() ?? optionWwwRoot.Value(),
                        Overwrite  = optionOverwrite.HasValue(),
                        NoSource   = optionNoSource.HasValue(),
                        Runtimes   = optionRuntime.HasValue() ?
                                     string.Join(";", optionRuntime.Values).
                                     Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                                     new string[0],
                        Native  = optionNative.HasValue(),
                        Reports = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue())
                    };

                    var manager = new PackManager(_hostServices, options);
                    if (!manager.Package())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionDependencies  = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var optionQuiet         = c.Option("--quiet", "Do not show output such as source/destination of nupkgs",
                                                   CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions              = new BuildOptions();
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;
                    buildOptions.Reports          = CreateReports(optionVerbose.HasValue(), optionQuiet.HasValue());

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), quiet: false);

                    var command        = new AddCommand();
                    command.Reports    = reports;
                    command.Name       = argName.Value;
                    command.Version    = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            app.Command("install", c =>
            {
                c.Description = "Install the given dependency";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add, default is the latest version.");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optSource  = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                                          CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                                                 "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                                        CommandOptionType.SingleValue);
                var optNoCache       = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                var optQuiet         = c.Option("--quiet", "Do not show output such as HTTP request/cache information",
                                                CommandOptionType.NoValue);
                var optIgnoreFailedSources = c.Option("--ignore-failed-sources",
                                                      "Ignore failed remote sources if there are local packages meeting version requirements",
                                                      CommandOptionType.NoValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(async() =>
                {
                    var reports = CreateReports(optionVerbose.HasValue(), optQuiet.HasValue());

                    var addCmd        = new AddCommand();
                    addCmd.Reports    = reports;
                    addCmd.Name       = argName.Value;
                    addCmd.Version    = argVersion.Value;
                    addCmd.ProjectDir = argProject.Value;

                    var restoreCmd     = new RestoreCommand(_environment);
                    restoreCmd.Reports = reports;

                    restoreCmd.RestoreDirectory    = argProject.Value;
                    restoreCmd.Sources             = optSource.Values;
                    restoreCmd.FallbackSources     = optFallbackSource.Values;
                    restoreCmd.NoCache             = optNoCache.HasValue();
                    restoreCmd.PackageFolder       = optPackageFolder.Value();
                    restoreCmd.IgnoreFailedSources = optIgnoreFailedSources.HasValue();

                    if (optProxy.HasValue())
                    {
                        Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                    }

                    var installCmd     = new InstallCommand(addCmd, restoreCmd);
                    installCmd.Reports = reports;

                    var success = await installCmd.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            return(app.Execute(args));
        }
Exemple #22
0
        public int Main(string[] args)
        {
            _originalForeground = Console.ForegroundColor;

            var app = new CommandLineApplication();

            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);

            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return(0);
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot   = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                                         CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                                                 "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                                        CommandOptionType.SingleValue);
                var optNoCache       = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    try
                    {
                        var command     = new RestoreCommand(_environment);
                        command.Reports = new Reports()
                        {
                            Information = this,
                            Verbose     = optionVerbose.HasValue() ? (this as IReport) : new NullReport()
                        };

                        // If the root argument is a directory
                        if (Directory.Exists(argRoot.Value))
                        {
                            command.RestoreDirectory = argRoot.Value;
                        }
                        // If the root argument is a project.json file
                        else if (string.Equals(
                                     Project.ProjectFileName,
                                     Path.GetFileName(argRoot.Value),
                                     StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                        }
                        // If the root argument is a global.json file
                        else if (string.Equals(
                                     GlobalSettings.GlobalFileName,
                                     Path.GetFileName(argRoot.Value),
                                     StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                            command.GlobalJsonFile   = argRoot.Value;
                        }
                        else if (!string.IsNullOrEmpty(argRoot.Value))
                        {
                            throw new InvalidOperationException("The given root is invalid.");
                        }

                        if (optSource.HasValue())
                        {
                            command.Sources = optSource.Values;
                        }

                        if (optFallbackSource.HasValue())
                        {
                            command.FallbackSources = optFallbackSource.Values;
                        }

                        if (optProxy.HasValue())
                        {
                            Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                        }

                        command.NoCache       = optNoCache.HasValue();
                        command.PackageFolder = optPackageFolder.Value();

                        var success = command.ExecuteCommand();

                        return(success ? 0 : 1);
                    }
                    catch (Exception ex)
                    {
                        this.WriteLine("----------");
                        this.WriteLine(ex.ToString());
                        this.WriteLine("----------");
                        this.WriteLine("Restore failed");
                        this.WriteLine(ex.Message);
                        return(1);
                    }
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject          = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut           = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment", CommandOptionType.SingleValue);
                var optionOverwrite     = c.Option("--overwrite", "Remove existing files in target folders",
                                                   CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Don't include sources of project dependencies",
                                              CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <KRE>", "Names or paths to KRE files to include",
                                             CommandOptionType.MultipleValue);
                var optionAppFolder = c.Option("--appfolder <NAME>",
                                               "Determine the name of the application primary folder", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    Console.WriteLine("verbose:{0} out:{1} project:{2}",
                                      optionVerbose.HasValue(),
                                      optionOut.Value(),
                                      argProject.Value);

                    var options = new PackOptions
                    {
                        OutputDir              = optionOut.Value(),
                        ProjectDir             = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        AppFolder              = optionAppFolder.Value(),
                        Configuration          = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.TargetFramework,
                        Overwrite              = optionOverwrite.HasValue(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                                   string.Join(";", optionRuntime.Values).
                                   Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                                   new string[0],
                    };

                    var manager = new PackManager(_hostServices, options);
                    if (!manager.Package())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework     = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut           = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionCheck         = c.Option("--check", "Check diagnostics", CommandOptionType.NoValue);
                var optionDependencies  = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var argProjectDir       = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.RuntimeTargetFramework = _environment.TargetFramework;
                    buildOptions.OutputDir        = optionOut.Value();
                    buildOptions.ProjectDir       = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.CheckDiagnostics = optionCheck.HasValue();
                    buildOptions.Configurations   = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return(-1);
                    }

                    return(0);
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName    = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var command        = new AddCommand();
                    command.Report     = this;
                    command.Name       = argName.Value;
                    command.Version    = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return(success ? 0 : 1);
                });
            });

            return(app.Execute(args));
        }
Exemple #23
0
        /// <inheritdoc />
        public Task PackAsync(string projectPath, PackOptions options)
        {
            var args = CreateArguments(projectPath, options);

            return(_commandRunner.RunAsync("dotnet", "pack", args));
        }
Exemple #24
0
        static async Task PushPackagesAsync([NotNull] PackOptions packOptions, [NotNull] ILog logger, [NotNull] ISnapFilesystem filesystem,
                                            [NotNull] INugetService nugetService, [NotNull] ISnapPackageManager snapPackageManager, [NotNull] IDistributedMutex distributedMutex, [NotNull] SnapAppsReleases snapAppsReleases,
                                            [NotNull] SnapApp snapApp, [NotNull] SnapChannel snapChannel,
                                            [NotNull] List <string> packages, CancellationToken cancellationToken)
        {
            if (packOptions == null)
            {
                throw new ArgumentNullException(nameof(packOptions));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (filesystem == null)
            {
                throw new ArgumentNullException(nameof(filesystem));
            }
            if (nugetService == null)
            {
                throw new ArgumentNullException(nameof(nugetService));
            }
            if (snapPackageManager == null)
            {
                throw new ArgumentNullException(nameof(snapPackageManager));
            }
            if (distributedMutex == null)
            {
                throw new ArgumentNullException(nameof(distributedMutex));
            }
            if (snapAppsReleases == null)
            {
                throw new ArgumentNullException(nameof(snapAppsReleases));
            }
            if (snapApp == null)
            {
                throw new ArgumentNullException(nameof(snapApp));
            }
            if (snapChannel == null)
            {
                throw new ArgumentNullException(nameof(snapChannel));
            }
            if (packages == null)
            {
                throw new ArgumentNullException(nameof(packages));
            }
            if (packages.Count == 0)
            {
                throw new ArgumentException("Value cannot be an empty collection.", nameof(packages));
            }

            logger.Info('-'.Repeat(TerminalBufferWidth));

            var pushDegreeOfParallelism = Math.Min(Environment.ProcessorCount, packages.Count);

            var nugetSources          = snapApp.BuildNugetSources(filesystem.PathGetTempPath());
            var pushFeedPackageSource = nugetSources.Items.Single(x => x.Name == snapChannel.PushFeed.Name);

            if (pushFeedPackageSource.IsLocalOrUncPath())
            {
                filesystem.DirectoryCreateIfNotExists(pushFeedPackageSource.SourceUri.AbsolutePath);
            }

            if (snapChannel.UpdateFeed.HasCredentials())
            {
                if (!logger.Prompt("y|yes", "Update feed contains credentials. Do you want to continue? [y|n]", infoOnly: packOptions.YesToAllPrompts))
                {
                    logger.Error("Publish aborted.");
                    return;
                }
            }

            logger.Info("Ready to publish application!");

            logger.Info($"Id: {snapApp.Id}");
            logger.Info($"Rid: {snapApp.Target.Rid}");
            logger.Info($"Channel: {snapChannel.Name}");
            logger.Info($"Version: {snapApp.Version}");
            logger.Info($"Feed name: {snapChannel.PushFeed.Name}");

            if (!logger.Prompt("y|yes", "Are you ready to push release upstream? [y|n]", infoOnly: packOptions.YesToAllPrompts))
            {
                logger.Error("Publish aborted.");
                return;
            }

            var stopwatch = new Stopwatch();

            stopwatch.Restart();

            logger.Info($"Pushing packages to default channel: {snapChannel.Name}. Feed: {snapChannel.PushFeed.Name}.");

            await packages.ForEachAsync(async packageAbsolutePath =>
                                        await PushPackageAsync(nugetService, filesystem, distributedMutex,
                                                               nugetSources, pushFeedPackageSource, snapChannel, packageAbsolutePath, logger, cancellationToken), pushDegreeOfParallelism);

            logger.Info($"Successfully pushed {packages.Count} packages in {stopwatch.Elapsed.TotalSeconds:F1}s.");

            var skipInitialBlock = pushFeedPackageSource.IsLocalOrUncPath();

            await BlockUntilSnapUpdatedReleasesNupkgAsync(logger, snapPackageManager, snapAppsReleases,
                                                          snapApp, snapChannel, TimeSpan.FromSeconds(15), cancellationToken, skipInitialBlock, packOptions.SkipAwaitUpdate);
        }
Exemple #25
0
        static async Task <int> CommandPackAsync([NotNull] PackOptions packOptions, [NotNull] ISnapFilesystem filesystem,
                                                 [NotNull] ISnapAppReader snapAppReader, [NotNull] ISnapAppWriter snapAppWriter, [NotNull] INuGetPackageSources nuGetPackageSources,
                                                 [NotNull] ISnapPack snapPack, [NotNull] INugetService nugetService, [NotNull] ISnapOs snapOs,
                                                 [NotNull] ISnapxEmbeddedResources snapxEmbeddedResources, [NotNull] ISnapExtractor snapExtractor,
                                                 [NotNull] ISnapPackageManager snapPackageManager, [NotNull] ICoreRunLib coreRunLib, [NotNull] ISnapNetworkTimeProvider snapNetworkTimeProvider,
                                                 [NotNull] ILog logger, [NotNull] IDistributedMutexClient distributedMutexClient, [NotNull] string workingDirectory, CancellationToken cancellationToken)
        {
            if (packOptions == null)
            {
                throw new ArgumentNullException(nameof(packOptions));
            }
            if (filesystem == null)
            {
                throw new ArgumentNullException(nameof(filesystem));
            }
            if (snapAppReader == null)
            {
                throw new ArgumentNullException(nameof(snapAppReader));
            }
            if (snapAppWriter == null)
            {
                throw new ArgumentNullException(nameof(snapAppWriter));
            }
            if (nuGetPackageSources == null)
            {
                throw new ArgumentNullException(nameof(nuGetPackageSources));
            }
            if (snapPack == null)
            {
                throw new ArgumentNullException(nameof(snapPack));
            }
            if (nugetService == null)
            {
                throw new ArgumentNullException(nameof(nugetService));
            }
            if (snapOs == null)
            {
                throw new ArgumentNullException(nameof(snapOs));
            }
            if (snapxEmbeddedResources == null)
            {
                throw new ArgumentNullException(nameof(snapxEmbeddedResources));
            }
            if (snapExtractor == null)
            {
                throw new ArgumentNullException(nameof(snapExtractor));
            }
            if (snapPackageManager == null)
            {
                throw new ArgumentNullException(nameof(snapPackageManager));
            }
            if (coreRunLib == null)
            {
                throw new ArgumentNullException(nameof(coreRunLib));
            }
            if (snapNetworkTimeProvider == null)
            {
                throw new ArgumentNullException(nameof(snapNetworkTimeProvider));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (distributedMutexClient == null)
            {
                throw new ArgumentNullException(nameof(distributedMutexClient));
            }
            if (workingDirectory == null)
            {
                throw new ArgumentNullException(nameof(workingDirectory));
            }

            var stopwatch = new Stopwatch();

            stopwatch.Restart();

            var(snapApps, snapApp, error, snapsManifestAbsoluteFilename) = BuildSnapAppFromDirectory(filesystem, snapAppReader,
                                                                                                     nuGetPackageSources, packOptions.Id, packOptions.Rid, workingDirectory);
            if (snapApp == null)
            {
                if (!error)
                {
                    logger.Error($"Snap with id {packOptions.Id} was not found in manifest: {snapsManifestAbsoluteFilename}");
                }

                return(1);
            }

            if (!SemanticVersion.TryParse(packOptions.Version, out var semanticVersion))
            {
                logger.Error($"Unable to parse semantic version (v2): {packOptions.Version}");
                return(1);
            }

            snapApp.Version = semanticVersion;

            if (packOptions.ReleasesNotes != null)
            {
                snapApp.ReleaseNotes = packOptions.ReleasesNotes;
            }

            var artifactsDirectory  = BuildArtifactsDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);
            var installersDirectory = BuildInstallersDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);
            var packagesDirectory   = BuildPackagesDirectory(filesystem, workingDirectory, snapApps.Generic, snapApp);

            filesystem.DirectoryCreateIfNotExists(installersDirectory);
            filesystem.DirectoryCreateIfNotExists(packagesDirectory);

            var snapAppChannel = snapApp.GetDefaultChannelOrThrow();

            MaybeOverrideLockToken(snapApps, logger, packOptions.Id, packOptions.LockToken);

            if (string.IsNullOrWhiteSpace(snapApps.Generic.Token))
            {
                logger.Error("Please specify a token in your snapx.yml file. A random UUID is sufficient.");
                return(1);
            }

            await using var distributedMutex = WithDistributedMutex(distributedMutexClient, logger, snapApps.BuildLockKey(snapApp), cancellationToken);

            logger.Info($"Schema version: {snapApps.Schema}");
            logger.Info($"Packages directory: {packagesDirectory}");
            logger.Info($"Artifacts directory: {artifactsDirectory}");
            logger.Info($"Installers directory: {installersDirectory}");
            logger.Info($"Pack strategy: {snapApps.Generic.PackStrategy}");
            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Id: {snapApp.Id}");
            logger.Info($"Version: {snapApp.Version}");
            logger.Info($"Channel: {snapAppChannel.Name}");
            logger.Info($"Rid: {snapApp.Target.Rid}");
            logger.Info($"OS: {snapApp.Target.Os.ToString().ToLowerInvariant()}");
            var installersStr = !snapApp.Target.Installers.Any() ? "None" : string.Join(", ", snapApp.Target.Installers);

            logger.Info($"Installers: {installersStr}");
            var shortcutsStr = !snapApp.Target.Shortcuts.Any() ? "None" : string.Join(", ", snapApp.Target.Shortcuts);

            logger.Info($"Shortcuts: {shortcutsStr}");

            logger.Info('-'.Repeat(TerminalBufferWidth));

            var tryAcquireRetries = packOptions.LockRetries == -1 ? int.MaxValue : packOptions.LockRetries;

            if (!await distributedMutex.TryAquireAsync(TimeSpan.FromSeconds(15), tryAcquireRetries))
            {
                logger.Info('-'.Repeat(TerminalBufferWidth));
                return(1);
            }

            logger.Info('-'.Repeat(TerminalBufferWidth));

            var updateFeedPackageSource = await snapPackageManager.GetPackageSourceAsync(snapApp);

            logger.Info("Downloading releases nupkg.");

            var snapReleasesPackageDirectory = filesystem.DirectoryGetParent(packagesDirectory);

            filesystem.DirectoryCreateIfNotExists(snapReleasesPackageDirectory);

            var(snapAppsReleases, _, currentReleasesMemoryStream) = await snapPackageManager.GetSnapsReleasesAsync(snapApp, logger, cancellationToken);

            if (currentReleasesMemoryStream != null)
            {
                await currentReleasesMemoryStream.DisposeAsync();
            }

            if (snapAppsReleases == null)
            {
                if (!logger.Prompt("y|yes", "Unable to find a previous release in any of your NuGet package sources. " +
                                   "Is this the first time you are publishing this application? " +
                                   "NB! The package may not yet be visible to due to upstream caching. [y/n]", infoOnly: packOptions.YesToAllPrompts)
                    )
                {
                    return(1);
                }

                snapAppsReleases = new SnapAppsReleases();
            }
            else
            {
                logger.Info($"Downloaded releases nupkg. Current version: {snapAppsReleases.Version}.");

                if (packOptions.Gc)
                {
                    var releasesRemoved = snapAppsReleases.Gc(snapApp);
                    logger.Info($"Garbage collected (removed) {releasesRemoved} releases.");
                }

                var snapAppChannelReleases = snapAppsReleases.GetReleases(snapApp, snapAppChannel);

                var restoreSummary = await snapPackageManager.RestoreAsync(packagesDirectory, snapAppChannelReleases,
                                                                           updateFeedPackageSource, SnapPackageManagerRestoreType.Pack, logger : logger, cancellationToken : cancellationToken);

                if (!restoreSummary.Success)
                {
                    return(1);
                }

                if (snapAppChannelReleases.Any(x => x.Version >= snapApp.Version))
                {
                    logger.Error($"Version {snapApp.Version} is already published to feed: {updateFeedPackageSource.Name}.");
                    return(1);
                }
            }

            var snapPackageDetails = new SnapPackageDetails
            {
                SnapApp             = snapApp,
                NuspecBaseDirectory = artifactsDirectory,
                PackagesDirectory   = packagesDirectory,
                SnapAppsReleases    = snapAppsReleases
            };

            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Building nupkg: {snapApp.Version}.");

            var pushPackages = new List <string>();

            var(fullNupkgMemoryStream, fullSnapApp, fullSnapRelease, deltaNupkgMemorystream, deltaSnapApp, deltaSnapRelease) =
                await snapPack.BuildPackageAsync(snapPackageDetails, coreRunLib, cancellationToken);

            var fullNupkgAbsolutePath = filesystem.PathCombine(packagesDirectory, fullSnapRelease.Filename);

            await using (fullNupkgMemoryStream)
                await using (deltaNupkgMemorystream)
                {
                    logger.Info($"Writing full nupkg to disk: {fullSnapRelease.Filename}. File size: {fullSnapRelease.FullFilesize.BytesAsHumanReadable()}");
                    await filesystem.FileWriteAsync(fullNupkgMemoryStream, fullNupkgAbsolutePath, default);

                    if (!fullSnapRelease.IsGenesis)
                    {
                        var deltaNupkgAbsolutePath = filesystem.PathCombine(packagesDirectory, deltaSnapRelease.Filename);
                        logger.Info(
                            $"Writing delta nupkg to disk: {deltaSnapRelease.Filename}. File size: {deltaSnapRelease.DeltaFilesize.BytesAsHumanReadable()}");
                        await filesystem.FileWriteAsync(deltaNupkgMemorystream, deltaNupkgAbsolutePath, default);
                    }
                }

            var fullOrDeltaSnapApp           = deltaSnapApp ?? fullSnapApp;
            var fullOrDeltaNupkgAbsolutePath = filesystem.PathCombine(packagesDirectory, fullOrDeltaSnapApp.BuildNugetFilename());

            pushPackages.Add(fullOrDeltaNupkgAbsolutePath);

            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Retrieving network time from: {snapNetworkTimeProvider}.");

            var nowUtc = await SnapUtility.RetryAsync(async() => await snapNetworkTimeProvider.NowUtcAsync(), 3);

            if (!nowUtc.HasValue)
            {
                logger.Error($"Unknown error retrieving network time from: {snapNetworkTimeProvider}");
                return(1);
            }

            var localTimeStr = TimeZoneInfo
                               .ConvertTimeFromUtc(nowUtc.Value, TimeZoneInfo.Local)
                               .ToString("F", CultureInfo.CurrentCulture);

            logger.Info($"Successfully retrieved network time. Time is now: {localTimeStr}");
            logger.Info('-'.Repeat(TerminalBufferWidth));

            fullSnapRelease.CreatedDateUtc = nowUtc.Value;
            if (deltaSnapRelease != null)
            {
                deltaSnapRelease.CreatedDateUtc = nowUtc.Value;
            }
            snapAppsReleases.LastWriteAccessUtc = nowUtc.Value;

            int?forcedDbVersion = null;

            if (packOptions.DbVersion > 0)
            {
                if (packOptions.DbVersion <= snapAppsReleases.DbVersion)
                {
                    logger.Error($"Unable to force database version because version is less than or equal to current database version. \n" +
                                 $"Forced version: {packOptions.DbVersion}.\n" +
                                 $"Current database version: {snapAppsReleases.DbVersion}.");
                    return(1);
                }

                forcedDbVersion = packOptions.DbVersion;

                logger.Info($"Database version is forced because of '--db-version' option. Initial database version: {forcedDbVersion}.");
            }
            else if (fullOrDeltaSnapApp.IsGenesis &&
                     fullOrDeltaSnapApp.Version.Major > snapAppsReleases.Version.Major)
            {
                forcedDbVersion = fullOrDeltaSnapApp.Version.Major;
                logger.Info($"Database version is forced because genesis nupkg detected. Initial database version: {forcedDbVersion}");
            }

            logger.Info($"Building releases nupkg. Current database version: {snapAppsReleases.Version}.");

            var releasesMemoryStream      = snapPack.BuildReleasesPackage(fullOrDeltaSnapApp, snapAppsReleases, forcedDbVersion);
            var releasesNupkgAbsolutePath = snapOs.Filesystem.PathCombine(snapReleasesPackageDirectory, fullOrDeltaSnapApp.BuildNugetReleasesFilename());
            var releasesNupkgFilename     = filesystem.PathGetFileName(releasesNupkgAbsolutePath);
            await snapOs.Filesystem.FileWriteAsync(releasesMemoryStream, releasesNupkgAbsolutePath, cancellationToken);

            pushPackages.Add(releasesNupkgAbsolutePath);

            logger.Info("Finished building releases nupkg.\n" +
                        $"Filename: {releasesNupkgFilename}.\n" +
                        $"Size: {releasesMemoryStream.Length.BytesAsHumanReadable()}.\n" +
                        $"New database version: {snapAppsReleases.Version}.\n" +
                        $"Pack id: {snapAppsReleases.PackId:N}.");

            logger.Info('-'.Repeat(TerminalBufferWidth));

            await using (releasesMemoryStream)
            {
                if (!packOptions.SkipInstallers && fullOrDeltaSnapApp.Target.Installers.Any())
                {
                    var channels = fullOrDeltaSnapApp.IsGenesis ? fullOrDeltaSnapApp.Channels : new List <SnapChannel> {
                        snapAppChannel
                    };

                    foreach (var channel in channels)
                    {
                        var snapAppInstaller = new SnapApp(fullOrDeltaSnapApp);
                        snapAppInstaller.SetCurrentChannel(channel.Name);

                        if (fullOrDeltaSnapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Offline)))
                        {
                            logger.Info('-'.Repeat(TerminalBufferWidth));

                            var(installerOfflineSuccess, canContinueIfError, installerOfflineExeAbsolutePath) = await BuildInstallerAsync(logger, snapOs, snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                                                                                                          installersDirectory, fullNupkgAbsolutePath, releasesNupkgAbsolutePath,
                                                                                                                                          true, cancellationToken);

                            if (!installerOfflineSuccess)
                            {
                                if (!canContinueIfError ||
                                    !logger.Prompt("y|yes", "Installer was not built. Do you still want to continue? (y|n)",
                                                   infoOnly: packOptions.YesToAllPrompts))
                                {
                                    logger.Info('-'.Repeat(TerminalBufferWidth));
                                    logger.Error("Unknown error building offline installer.");
                                    return(1);
                                }
                            }
                            else
                            {
                                var installerOfflineExeStat = snapOs.Filesystem.FileStat(installerOfflineExeAbsolutePath);
                                logger.Info($"Successfully built offline installer. File size: {installerOfflineExeStat.Length.BytesAsHumanReadable()}.");
                            }
                        }

                        if (fullOrDeltaSnapApp.Target.Installers.Any(x => x.HasFlag(SnapInstallerType.Web)))
                        {
                            logger.Info('-'.Repeat(TerminalBufferWidth));

                            var(installerWebSuccess, canContinueIfError, installerWebExeAbsolutePath) = await BuildInstallerAsync(logger, snapOs, snapxEmbeddedResources, snapAppWriter, snapAppInstaller, coreRunLib,
                                                                                                                                  installersDirectory, null, releasesNupkgAbsolutePath,
                                                                                                                                  false, cancellationToken);

                            if (!installerWebSuccess)
                            {
                                if (!canContinueIfError ||
                                    !logger.Prompt("y|yes", "Installer was not built. Do you still want to continue? (y|n)",
                                                   infoOnly: packOptions.YesToAllPrompts))
                                {
                                    logger.Info('-'.Repeat(TerminalBufferWidth));
                                    logger.Error("Unknown error building offline installer.");
                                    return(1);
                                }
                            }
                            else
                            {
                                var installerWebExeStat = snapOs.Filesystem.FileStat(installerWebExeAbsolutePath);
                                logger.Info($"Successfully built web installer. File size: {installerWebExeStat.Length.BytesAsHumanReadable()}.");
                            }
                        }
                    }
                }
            }

            if (snapApps.Generic.PackStrategy == SnapAppsPackStrategy.push)
            {
                await PushPackagesAsync(packOptions, logger, filesystem, nugetService,
                                        snapPackageManager, distributedMutex, snapAppsReleases, fullOrDeltaSnapApp, snapAppChannel, pushPackages, cancellationToken);
            }

            logger.Info($"Fetching releases overview from feed {updateFeedPackageSource.Name}.");

            await CommandListAsync(new ListOptions { Id = fullOrDeltaSnapApp.Id }, filesystem, snapAppReader,
                                   nuGetPackageSources, nugetService, snapExtractor, snapPackageManager, logger, workingDirectory, cancellationToken);

            logger.Info('-'.Repeat(TerminalBufferWidth));
            logger.Info($"Pack completed in {stopwatch.Elapsed.TotalSeconds:F1}s.");

            return(0);
        }
Exemple #26
0
 public void PackCharts(PackOptions packOptions) => XAtlas.PackCharts(this, packOptions);
Exemple #27
0
 public void Generate(ChartOptions chartOptions, PackOptions packOptions) => XAtlas.Generate(this, chartOptions, packOptions);
Exemple #28
0
        public int Main(string[] args)
        {
            _originalForeground = Console.ForegroundColor;

            var app = new CommandLineApplication();
            app.Name = "kpm";

            var optionVerbose = app.Option("-v|--verbose", "Show verbose output", CommandOptionType.NoValue);
            app.HelpOption("-?|-h|--help");
            app.VersionOption("--version", GetVersion());

            // Show help information if no subcommand was specified
            app.OnExecute(() =>
            {
                app.ShowHelp();
                return 0;
            });

            app.Command("restore", c =>
            {
                c.Description = "Restore packages";

                var argRoot = c.Argument("[root]", "Root of all projects to restore. It can be a directory, a project.json, or a global.json.");
                var optSource = c.Option("-s|--source <FEED>", "A list of packages sources to use for this command",
                    CommandOptionType.MultipleValue);
                var optFallbackSource = c.Option("-f|--fallbacksource <FEED>",
                    "A list of packages sources to use as a fallback", CommandOptionType.MultipleValue);
                var optProxy = c.Option("-p|--proxy <ADDRESS>", "The HTTP proxy to use when retrieving packages",
                    CommandOptionType.SingleValue);
                var optNoCache = c.Option("--no-cache", "Do not use local cache", CommandOptionType.NoValue);
                var optPackageFolder = c.Option("--packages", "Path to restore packages", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    try
                    {
                        var command = new RestoreCommand(_environment);
                        command.Reports = new Reports()
                        {
                            Information = this,
                            Verbose = optionVerbose.HasValue() ? (this as IReport) : new NullReport()
                        };

                        // If the root argument is a directory
                        if (Directory.Exists(argRoot.Value))
                        {
                            command.RestoreDirectory = argRoot.Value;
                        }
                        // If the root argument is a project.json file
                        else if (string.Equals(
                            Project.ProjectFileName,
                            Path.GetFileName(argRoot.Value),
                            StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                        }
                        // If the root argument is a global.json file
                        else if (string.Equals(
                            GlobalSettings.GlobalFileName,
                            Path.GetFileName(argRoot.Value),
                            StringComparison.OrdinalIgnoreCase))
                        {
                            command.RestoreDirectory = Path.GetDirectoryName(Path.GetFullPath(argRoot.Value));
                            command.GlobalJsonFile = argRoot.Value;
                        }
                        else if (!string.IsNullOrEmpty(argRoot.Value))
                        {
                            throw new InvalidOperationException("The given root is invalid.");
                        }

                        if (optSource.HasValue())
                        {
                            command.Sources = optSource.Values;
                        }

                        if (optFallbackSource.HasValue())
                        {
                            command.FallbackSources = optFallbackSource.Values;
                        }

                        if (optProxy.HasValue())
                        {
                            Environment.SetEnvironmentVariable("http_proxy", optProxy.Value());
                        }

                        command.NoCache = optNoCache.HasValue();
                        command.PackageFolder = optPackageFolder.Value();

                        var success = command.ExecuteCommand();

                        return success ? 0 : 1;
                    }
                    catch (Exception ex)
                    {
                        this.WriteLine("----------");
                        this.WriteLine(ex.ToString());
                        this.WriteLine("----------");
                        this.WriteLine("Restore failed");
                        this.WriteLine(ex.Message);
                        return 1;
                    }
                });
            });

            app.Command("pack", c =>
            {
                c.Description = "Bundle application for deployment";

                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                var optionOut = c.Option("-o|--out <PATH>", "Where does it go", CommandOptionType.SingleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "The configuration to use for deployment", CommandOptionType.SingleValue);
                var optionOverwrite = c.Option("--overwrite", "Remove existing files in target folders",
                    CommandOptionType.NoValue);
                var optionNoSource = c.Option("--no-source", "Don't include sources of project dependencies",
                    CommandOptionType.NoValue);
                var optionRuntime = c.Option("--runtime <KRE>", "Names or paths to KRE files to include",
                    CommandOptionType.MultipleValue);
                var optionAppFolder = c.Option("--appfolder <NAME>",
                    "Determine the name of the application primary folder", CommandOptionType.SingleValue);
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    Console.WriteLine("verbose:{0} out:{1} project:{2}",
                        optionVerbose.HasValue(),
                        optionOut.Value(),
                        argProject.Value);

                    var options = new PackOptions
                    {
                        OutputDir = optionOut.Value(),
                        ProjectDir = argProject.Value ?? System.IO.Directory.GetCurrentDirectory(),
                        AppFolder = optionAppFolder.Value(),
                        Configuration = optionConfiguration.Value() ?? "Debug",
                        RuntimeTargetFramework = _environment.TargetFramework,
                        Overwrite = optionOverwrite.HasValue(),
                        NoSource = optionNoSource.HasValue(),
                        Runtimes = optionRuntime.HasValue() ?
                            string.Join(";", optionRuntime.Values).
                                Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) :
                            new string[0],
                    };

                    var manager = new PackManager(_hostServices, options);
                    if (!manager.Package())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("build", c =>
            {
                c.Description = "Build NuGet packages for the project in given directory";

                var optionFramework = c.Option("--framework <TARGET_FRAMEWORK>", "A list of target frameworks to build.", CommandOptionType.MultipleValue);
                var optionConfiguration = c.Option("--configuration <CONFIGURATION>", "A list of configurations to build.", CommandOptionType.MultipleValue);
                var optionOut = c.Option("--out <OUTPUT_DIR>", "Output directory", CommandOptionType.SingleValue);
                var optionCheck = c.Option("--check", "Check diagnostics", CommandOptionType.NoValue);
                var optionDependencies = c.Option("--dependencies", "Copy dependencies", CommandOptionType.NoValue);
                var argProjectDir = c.Argument("[project]", "Project to build, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var buildOptions = new BuildOptions();
                    buildOptions.RuntimeTargetFramework = _environment.TargetFramework;
                    buildOptions.OutputDir = optionOut.Value();
                    buildOptions.ProjectDir = argProjectDir.Value ?? Directory.GetCurrentDirectory();
                    buildOptions.CheckDiagnostics = optionCheck.HasValue();
                    buildOptions.Configurations = optionConfiguration.Values;
                    buildOptions.TargetFrameworks = optionFramework.Values;

                    var projectManager = new BuildManager(_hostServices, buildOptions);

                    if (!projectManager.Build())
                    {
                        return -1;
                    }

                    return 0;
                });
            });

            app.Command("add", c =>
            {
                c.Description = "Add a dependency into dependencies section of project.json";

                var argName = c.Argument("[name]", "Name of the dependency to add");
                var argVersion = c.Argument("[version]", "Version of the dependency to add");
                var argProject = c.Argument("[project]", "Path to project, default is current directory");
                c.HelpOption("-?|-h|--help");

                c.OnExecute(() =>
                {
                    var command = new AddCommand();
                    command.Report = this;
                    command.Name = argName.Value;
                    command.Version = argVersion.Value;
                    command.ProjectDir = argProject.Value;

                    var success = command.ExecuteCommand();

                    return success ? 0 : 1;
                });
            });

            return app.Execute(args);
        }
Exemple #29
0
 public PackPluginRunner(PackOptions packOpts)
 {
     _packOpts = packOpts;
 }
Exemple #30
0
        public int Execute(PackOptions options)
        {
            var sourcePath = Path.GetFullPath(options.ManifestPath);
            var outputPath = Path.GetDirectoryName(Path.GetFullPath(options.OutputPath));

            var stagingPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(options.OutputPath));

            var doc = new XmlDocument();

            doc.Load(Path.Combine(sourcePath, "manifest.xml"));

            if (!Directory.Exists(stagingPath))
            {
                Directory.CreateDirectory(stagingPath);
            }
            if (Directory.EnumerateFileSystemEntries(stagingPath).Any())
            {
                throw new ApplicationException("Staging folder was not cleaned up");
            }

            var package = doc["package"];

            // Stage Forms

            if (package["FormList"] != null)
            {
                foreach (var form in package["FormList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Form"))
                {
                    Console.WriteLine($"Staging Form {form.Attributes["mname"].Value}");
                    var sourceFile = form.Attributes["fname"].Value;
                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, sourceFile));
                }
            }

            // Stage Form Codebase Assemblies

            if (package["AssemblyList"] != null)
            {
                foreach (var codebase in package["AssemblyList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Assembly"))
                {
                    Console.WriteLine($"Staging Form Codebase {codebase.Attributes["name"].Value}");
                    var sourceFile = codebase.Attributes["fname"].Value;

                    if (options.SetAssemblyVersions)
                    {
                        var assemblyVersion = Assembly.ReflectionOnlyLoadFrom(Path.Combine(sourcePath, sourceFile)).GetName().Version;
                        Console.WriteLine("Assembly Version {0}", assemblyVersion);

                        if (codebase.Attributes["version"] == null)
                        {
                            codebase.Attributes.Append(doc.CreateAttribute("version"));
                        }

                        codebase.Attributes["version"].Value = assemblyVersion.ToString();
                    }

                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, sourceFile));
                }
            }

            // Stage Plugin Assemblies

            if (package["PluginList"] != null)
            {
                Directory.CreateDirectory(Path.Combine(stagingPath, "Plugins"));

                foreach (var plugin in package["PluginList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Plugin"))
                {
                    Console.WriteLine($"Staging Plugin {plugin.Attributes["name"].Value}");
                    var sourceFile = plugin.Attributes["fname"].Value;

                    if (options.SetAssemblyVersions)
                    {
                        var assemblyVersion = Assembly.ReflectionOnlyLoadFrom(Path.Combine(sourcePath, sourceFile)).GetName().Version;
                        Console.WriteLine("Assembly Version {0}", assemblyVersion);

                        if (plugin.Attributes["version"] == null)
                        {
                            plugin.Attributes.Append(doc.CreateAttribute("version"));
                        }

                        plugin.Attributes["version"].Value = assemblyVersion.ToString();
                    }

                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, "Plugins", sourceFile));
                }
            }


            // Stage Custom Data Objects

            if (package["CustomDataObjectList"] != null)
            {
                Directory.CreateDirectory(Path.Combine(stagingPath, "CustomData"));

                foreach (var cdo in package["CustomDataObjectList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "CustomDataObject"))
                {
                    Console.WriteLine($"Staging Custom Data Object {cdo.Attributes["name"].Value}");
                    var sourceFile = cdo.Attributes["fname"].Value;
                    File.Copy(Path.Combine(sourcePath, "CustomData", sourceFile), Path.Combine(stagingPath, "CustomData", sourceFile));
                }
            }

            // Stage Manifest

            Console.WriteLine("Staging Manifest");
            using (var writer = XmlWriter.Create(Path.Combine(stagingPath, "manifest.xml"), new XmlWriterSettings
            {
                Indent = true,
                OmitXmlDeclaration = true,
            }))
            {
                doc.WriteTo(writer);
            }

            // Make the Package File

            ZipFile.CreateFromDirectory(stagingPath, options.OutputPath, CompressionLevel.Optimal, includeBaseDirectory: false);

            // Clean up the staging directory

            Directory.Delete(stagingPath, recursive: true);

            return(0);
        }