Beispiel #1
0
        //download the specified version of the package and update project reference to it. The newly downloaded package
        //will be located in /packages folder. The updated project reference can be checked in corresponding .csproj file.
        public bool Execute(string packageid, string projectFile, SemanticVersion version, string packages)
        {
            try
            {
                System.Console.WriteLine("-------------------------------------");
                System.Console.WriteLine("Project File " + projectFile);
                System.Console.WriteLine("Package " + packageid);
                System.Console.WriteLine("Version " + version);

                IPackageRepository repo      = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
                var packagePathResolver      = new DefaultPackagePathResolver(packages);
                var packagesFolderFileSystem = new PhysicalFileSystem(packages);
                var projectSystem            = new MSBuildProjectSystem(projectFile);
                var localRepository          = new LocalPackageRepository(packagePathResolver, packagesFolderFileSystem);
                var projectManager           = new ProjectManager(repo, packagePathResolver, projectSystem, localRepository);

                projectManager.RemovePackageReference(packageid, true, false);
                projectManager.AddPackageReference(packageid, version, true, false);
                projectSystem.Save();

                string   filename = packageid + "." + version;
                string[] s        = Directory.GetFiles(packages + @"\" + filename);
                if (s.IsEmpty())
                {
                    System.Console.WriteLine("empty");
                }
                else
                {
                    var        nupkgFile = new PhysicalFileSystem(s[0]);
                    ZipPackage z         = new ZipPackage(s[0]);
                    z.ExtractContents(nupkgFile, packages + @"\" + filename);
                }
                System.Console.WriteLine("Successfully updated");
                return(true);
            }
            catch (Exception e)
            {
                System.Console.Write("failure");
                System.Console.Write(e.StackTrace);
                return(false);
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            var          indexJsonUrl                = args[0];
            var          tfsUserName                 = args.Length > 1 ? args[1] : null;
            var          tfsPwd                      = args.Length > 2 ? args[2] : null;
            var          workDir                     = $"Backup_{DateTime.Now:yyyyMMddHHmmss}";
            const string packageFolderName           = "Packages";
            const string packageHashAlgorithm        = "sha512";
            var          backupPath                  = $"{workDir}\\{packageFolderName}";
            var          cachePackageRootPath        = $"{workDir}\\Caches";
            var          cachePackagesBatchBuilder   = new StringBuilder();
            var          publishPackagesBatchBuilder = new StringBuilder("set source=%1\r\nset apiKey=%2\r\n");

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

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

            if (indexJsonUrl.ToLower().EndsWith("v3/index.json"))
            {
                Console.WriteLine("Detected v3 feed URL, try to find legacy v2 feed URL...");

                var client = new RestClient(indexJsonUrl)
                {
                    Authenticator = new NtlmAuthenticator(tfsUserName, tfsPwd)
                };

                var request  = new RestRequest(Method.GET);
                var response = client.Execute <NugetV3IndexJson>(request);

                if (response.IsSuccessful)
                {
                    SaveTextFile($"{workDir}\\index.json", response.Content);

                    var v2Feed = response.Data.Resources.FirstOrDefault(r => r.Type.Contains("LegacyGallery/2.0.0"));

                    if (v2Feed != null)
                    {
                        Console.WriteLine($"Found legacy v2 feed URL: {v2Feed.Id}");
                        indexJsonUrl = v2Feed.Id;
                    }
                }
                else
                {
                    Console.WriteLine($"Failed to find legacy v2 feed URL: {response.ErrorMessage}");
                    return;
                }
            }

            IList <IPackage> packages;

            try
            {
                var packageRepository = PackageRepositoryFactory.Default.CreateRepository(indexJsonUrl);
                packages = packageRepository.GetPackages().ToList();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }

            foreach (var package in packages.OrderBy(p => p.Id).ThenBy(p => p.Version))
            {
                var dataServicePackage  = (DataServicePackage)package;
                var packageFileName     = $"{package.Id}.{package.Version}.nupkg";
                var downloadPackagePath = $"{backupPath}\\{packageFileName}";

                cachePackagesBatchBuilder.AppendLine($"nuget.exe install {package.Id} -OutputDirectory tempPackages -Version {package.Version} -NonInteractive");
                publishPackagesBatchBuilder.AppendLine($"nuget.exe push -Source \"%source%\" -ApiKey %apiKey% {packageFolderName}\\{packageFileName}");

                var request = new RestRequest(dataServicePackage.DownloadUrl.PathAndQuery, Method.GET)
                {
                    ResponseWriter = stream =>
                    {
                        using (var fileStream = File.Create(downloadPackagePath))
                        {
                            stream.CopyTo(fileStream);
                        }

                        var zipPackage       = new ZipPackage(downloadPackagePath);
                        var cachePackagePath = $"{package.Id}\\{package.Version}".ToLower();
                        zipPackage.ExtractContents(new PhysicalFileSystem(cachePackageRootPath), cachePackagePath);
                        var packageHash          = zipPackage.GetHash(packageHashAlgorithm);
                        var cachePackageFileName = $"{cachePackageRootPath}\\{cachePackagePath}\\{packageFileName.ToLower()}";
                        var fastZip = new FastZip();
                        fastZip.ExtractZip(downloadPackagePath, $"{cachePackageRootPath}\\{cachePackagePath}", @"\.nuspec$;\.nupkg$");
                        var nuspecFilePath = $"{cachePackageRootPath}\\{cachePackagePath}\\{package.Id}.nuspec";
                        if (File.Exists(nuspecFilePath))
                        {
                            File.Move(nuspecFilePath, nuspecFilePath.ToLower());
                        }

                        File.Copy(downloadPackagePath, cachePackageFileName, true);

                        var sha512FileName = $"{cachePackageFileName}.{packageHashAlgorithm}";
                        SaveTextFile(sha512FileName, packageHash);
                    }
                };

                var restClient = new RestClient($"http://{dataServicePackage.DownloadUrl.Host}")
                {
                    Authenticator = new NtlmAuthenticator(tfsUserName, tfsPwd)
                };
                var response = restClient.DownloadData(request);

                Console.WriteLine($"{packageFileName} is download.");
            }

            cachePackagesBatchBuilder.AppendLine("rmdir /Q /S tempPackages");

            SaveTextFile($"{workDir}\\BuildNugetCacheBatch.bat", cachePackagesBatchBuilder.ToString());
            SaveTextFile($"{workDir}\\PublishNugetPackagesBatch.bat", publishPackagesBatchBuilder.ToString());
        }
Beispiel #3
0
        private static void Main(string[] args)
        {
            var options = new Options();
            var result  = Parser.Default.ParseArguments(args, options);

            if (!result)
            {
                throw new NotSupportedException("Invalid arguments");
            }

            if (!File.Exists(options.PackageToPromote))
            {
                throw new FileNotFoundException("Cannot find the file", options.PackageToPromote);
            }

            var package  = new ZipPackage(options.PackageToPromote);
            var temppath = Path.GetTempPath() + Guid.NewGuid();

            package.ExtractContents(new PhysicalFileSystem(temppath), "");

            Console.WriteLine("Package Id: " + package.Id);
            Console.WriteLine($"Extracted to {temppath}");

            var match = Regex.Match(package.Version.ToString(), @"\d+\.\d+\.\d+");

            if (!match.Success)
            {
                throw new NotSupportedException("No semantic version was found in the metadata of the package.");
            }

            var newVersion = match.Value;

            Console.WriteLine($"The new version of the package will be {newVersion}");

            // Try to find rcedit.exe
            var exe = findExecutable("rcedit.exe");

            foreach (var dimaExe in Directory.GetFiles(temppath, "*.exe"))
            {
                Console.WriteLine($"Adjusting the product version of {dimaExe} to {newVersion}");
                var rceditargs = $"{dimaExe} --set-product-version {newVersion}";
                var process    = Process.Start(exe, rceditargs);
                process.WaitForExit(10000);
                if (process.ExitCode != 0)
                {
                    var msg = $"Failed to modify resources, command invoked was: '{exe} {string.Join(" ", rceditargs)}'";
                    throw new Exception(msg);
                }
            }

            var metadata = new ManifestMetadata
            {
                Id           = package.Id,
                Version      = newVersion,
                Title        = package.Title,
                ReleaseNotes = package.ReleaseNotes,
                Summary      = package.Summary,
                Description  = package.Description,
                Copyright    = package.Copyright,
                Language     = package.Language
            };

            if (package.IconUrl != null)
            {
                metadata.IconUrl = package.IconUrl.ToString();
            }
            if (package.LicenseUrl != null)
            {
                metadata.LicenseUrl = package.LicenseUrl.ToString();
            }
            if (package.ProjectUrl != null)
            {
                metadata.ProjectUrl = package.ProjectUrl.ToString();
            }
            if (package.Owners != null)
            {
                metadata.Owners = string.Join(", ", package.Owners);
            }
            if (package.Authors != null)
            {
                metadata.Authors = string.Join(", ", package.Authors);
            }

            var builder = new PackageBuilder();
            var files   = Directory.GetFiles(temppath, "*", SearchOption.AllDirectories)
                          .Where(f => !f.EndsWith(".nuspec"))
                          .Select(f => new ManifestFile {
                Source = f, Target = f.Replace(temppath, "")
            })
                          .ToList();

            builder.PopulateFiles("", files);
            builder.Populate(metadata);

            if (string.IsNullOrEmpty(options.OutputPath))
            {
                options.OutputPath = Directory.GetCurrentDirectory();
            }

            var outputFile = Path.Combine(options.OutputPath, $"{package.Id}.{newVersion}.nupkg");

            Console.WriteLine($"Saving new file to {outputFile}");
            using (var stream = File.Open(outputFile, FileMode.Create))
            {
                builder.Save(stream);
            }

            Console.WriteLine("Succesfully promoted package");
        }