Example #1
0
        static void Run(Options opts)
        {
            /*
             * if (opts.GithubAtomFeed != null)
             * {
             *  GenerateFromAtom(opts);
             *  return;
             * }*/

            if (opts.ShowExtendedExamples)
            {
                PrintExtendedExamples();
                return;
            }

            if (!string.IsNullOrWhiteSpace(opts.PathToKeyFiles))
            {
                _signatureManager.SetStorageDirectory(opts.PathToKeyFiles);
            }

            if (opts.Export)
            {
                Console.WriteLine("Private Key:");
                Console.WriteLine(Convert.ToBase64String(_signatureManager.GetPrivateKey()));
                Console.WriteLine("Public Key:");
                Console.WriteLine(Convert.ToBase64String(_signatureManager.GetPublicKey()));
                return;
            }

            if (opts.GenerateKeys)
            {
                var didSucceed = _signatureManager.Generate(opts.ForceRegeneration);
                if (didSucceed)
                {
                    Console.WriteLine("Keys successfully generated", Color.Green);
                }
                else
                {
                    Console.WriteLine("Keys failed to generate", Color.Red);
                }
                return;
            }

            if (opts.BinaryToSign != null)
            {
                var signature = _signatureManager.GetSignatureForFile(new FileInfo(opts.BinaryToSign));

                Console.WriteLine($"Signature: {signature}", Color.Green);

                return;
            }

            if (opts.BinaryToVerify != null)
            {
                var result = _signatureManager.VerifySignature(new FileInfo(opts.BinaryToVerify), opts.Signature);

                if (result)
                {
                    Console.WriteLine($"Signature valid", Color.Green);
                }
                else
                {
                    Console.WriteLine($"Signature invalid", Color.Red);
                }

                return;
            }


            var search = $"*.{opts.Extension}";

            if (opts.SourceBinaryDirectory == ".")
            {
                opts.SourceBinaryDirectory = Environment.CurrentDirectory;
            }

            var binaries = Directory.GetFiles(opts.SourceBinaryDirectory, search,
                                              opts.SearchBinarySubDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);

            if (binaries.Length == 0)
            {
                Console.WriteLine($"No files founds matching {search} in {opts.SourceBinaryDirectory}", Color.Yellow);
                Environment.Exit(1);
            }

            if (!_operatingSystems.Any(opts.OperatingSystem.Contains))
            {
                Console.WriteLine($"Invalid operating system: {opts.OperatingSystem}", Color.Red);
                Console.WriteLine($"Valid options are: {0}", string.Join(", ", _operatingSystems));
                Environment.Exit(1);
            }

            if (string.IsNullOrEmpty(opts.OutputDirectory))
            {
                opts.OutputDirectory = opts.SourceBinaryDirectory;
            }

            Console.WriteLine("");
            Console.WriteLine($"Operating System: {opts.OperatingSystem}", Color.LightBlue);
            Console.WriteLine($"Searching: {opts.SourceBinaryDirectory}", Color.LightBlue);
            Console.WriteLine($"Found {binaries.Count()} {opts.Extension} files(s)", Color.LightBlue);
            Console.WriteLine("");

            try
            {
                var productName = opts.ProductName;

                var items = new List <AppCastItem>();

                var usesChangelogs = !string.IsNullOrWhiteSpace(opts.ChangeLogPath) && Directory.Exists(opts.ChangeLogPath);

                foreach (var binary in binaries)
                {
                    string version  = null;
                    var    fileInfo = new FileInfo(binary);

                    if (opts.FileExtractVersion)
                    {
                        version = GetVersionFromName(fileInfo);
                    }
                    else
                    {
                        version = GetVersionFromAssembly(fileInfo);
                    }

                    if (version == null)
                    {
                        Console.WriteLine($"Unable to determine version of binary {fileInfo.Name}, try -f parameter");
                        Environment.Exit(1);
                    }

                    var productVersion = version;
                    var itemTitle      = string.IsNullOrWhiteSpace(productName) ? productVersion : productName + " " + productVersion;

                    var urlEncodedFileName = HttpUtility.UrlEncode(fileInfo.Name);
                    var urlToUse           = !string.IsNullOrWhiteSpace(opts.BaseUrl?.ToString())
                        ? (opts.BaseUrl.ToString().EndsWith("/") ? opts.BaseUrl.ToString() : opts.BaseUrl + "/")
                        : "";
                    if (opts.PrefixVersion)
                    {
                        urlToUse += $"{version}/";
                    }
                    if (urlEncodedFileName.StartsWith("/") && urlEncodedFileName.Length > 1)
                    {
                        urlEncodedFileName = urlEncodedFileName.Substring(1);
                    }
                    var remoteUpdateFile = $"{urlToUse}{urlEncodedFileName}";

                    // changelog stuff
                    var changelogFileName   = productVersion + ".md";
                    var changelogPath       = Path.Combine(opts.ChangeLogPath, changelogFileName);
                    var hasChangelogForFile = usesChangelogs && File.Exists(changelogPath);
                    var changelogSignature  = "";

                    if (hasChangelogForFile)
                    {
                        changelogSignature = _signatureManager.GetSignatureForFile(changelogPath);
                    }

                    //
                    var item = new AppCastItem()
                    {
                        Title                 = itemTitle?.Trim(),
                        DownloadLink          = remoteUpdateFile?.Trim(),
                        Version               = productVersion?.Trim(),
                        ShortVersion          = productVersion?.Substring(0, productVersion.LastIndexOf('.'))?.Trim(),
                        PublicationDate       = fileInfo.CreationTime,
                        UpdateSize            = fileInfo.Length,
                        Description           = "",
                        DownloadSignature     = _signatureManager.KeysExist() ? _signatureManager.GetSignatureForFile(fileInfo) : null,
                        OperatingSystemString = opts.OperatingSystem?.Trim(),
                        MIMEType              = MimeTypes.GetMimeType(fileInfo.Name)
                    };

                    if (hasChangelogForFile)
                    {
                        if (!string.IsNullOrWhiteSpace(opts.ChangeLogUrl))
                        {
                            item.ReleaseNotesSignature = changelogSignature;
                            var changeLogUrlBase = opts.ChangeLogUrl.EndsWith("/") || changelogFileName.StartsWith("/")
                                ? opts.ChangeLogUrl
                                : opts.ChangeLogUrl + "/";
                            item.ReleaseNotesLink = (opts.ChangeLogUrl + changelogFileName).Trim();
                        }
                        else
                        {
                            item.Description = File.ReadAllText(changelogPath).Trim();
                        }
                    }

                    items.Add(item);
                }

                var appcastXmlDocument = XMLAppCast.GenerateAppCastXml(items, productName);

                var appcastFileName = Path.Combine(opts.OutputDirectory, "appcast.xml");

                var dirName = Path.GetDirectoryName(appcastFileName);

                if (!Directory.Exists(dirName))
                {
                    Console.WriteLine("Creating {0}", dirName);
                    Directory.CreateDirectory(dirName);
                }

                Console.WriteLine("Writing appcast to {0}", appcastFileName);

                using (var w = XmlWriter.Create(appcastFileName, new XmlWriterSettings {
                    NewLineChars = "\n", Encoding = new UTF8Encoding(false)
                }))
                {
                    appcastXmlDocument.Save(w);
                }

                if (_signatureManager.KeysExist())
                {
                    var appcastFile   = new FileInfo(appcastFileName);
                    var extension     = opts.SignatureFileExtension?.TrimStart('.') ?? "signature";
                    var signatureFile = appcastFileName + "." + extension;
                    var signature     = _signatureManager.GetSignatureForFile(appcastFile);

                    var result = _signatureManager.VerifySignature(appcastFile, signature);

                    if (result)
                    {
                        File.WriteAllText(signatureFile, signature);
                        Console.WriteLine($"Wrote {signatureFile}", Color.Green);
                    }
                    else
                    {
                        Console.WriteLine($"Failed to verify {signatureFile}", Color.Red);
                    }
                }
                else
                {
                    Console.WriteLine("Skipped generating signature.  Generate keys with --generate-keys", Color.Red);
                    Environment.Exit(1);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine();
                Environment.Exit(1);
            }
        }