Inheritance: IPackageBuilder
Beispiel #1
0
        public bool BuildPackage(IEnumerable <ProjectContext> contexts, List <DiagnosticMessage> packDiagnostics)
        {
            Reporter.Output.WriteLine($"Producing nuget package \"{GetPackageName()}\" for {Project.Name}");

            PackageBuilder = CreatePackageBuilder(Project);

            // TODO: Report errors for required fields
            // id
            // author
            // description
            foreach (var context in contexts)
            {
                Reporter.Verbose.WriteLine($"Processing {context.TargetFramework.ToString().Yellow()}");
                ProcessContext(context);
                Reporter.Verbose.WriteLine("");
            }

            var packageOutputPath = Path.Combine(
                ArtifactPathsCalculator.PackageOutputPath,
                GetPackageName() + NuGet.Constants.PackageExtension);

            if (GeneratePackage(packageOutputPath, packDiagnostics))
            {
                return(true);
            }

            return(false);
        }
Beispiel #2
0
        /// <summary>
        /// Compiles a single .nuspec file
        /// </summary>
        /// <param name="specItem">
        /// The .nuspec file to compile
        /// </param>
        private void BuildPackage(ITaskItem specItem)
        {
            // load the package manifest (nuspec) from the task item
            // using the nuget package builder
            var specPath = specItem.GetMetadata("FullPath");
            var builder  = new NuGet.PackageBuilder(
                specPath,
                this as NuGet.IPropertyProvider,
                true
                );
            // initialize dynamic manifest properties
            var version = specItem.GetMetadata("NuPackageVersion");

            if (!String.IsNullOrEmpty(version))
            {
                builder.Version = new NuGet.SemanticVersion(version);
            }
            // add a new file to the folder for each project
            // referenced by the current project
            AddLibraries(builder);
            // write the configured package out to disk
            var pkgPath = specItem.GetMetadata("NuPackagePath");

            using (var pkgFile = File.Create(pkgPath))
                builder.Save(pkgFile);
        }
        public static Response Pack(NuGetPackRequest request)
        {
            var console = new Console();
            PackageBuilder builder = new PackageBuilder();
            var command = new PackCommand
            {
                BasePath = PathTools.OptimizePath(request.BaseDirectory),
                OutputDirectory = PathTools.OptimizePath(request.OutputDirectory),
                Version = request.Version,
                Console = console,
                Verbosity = Verbosity.Detailed,
                Rules = new IPackageRule[0],
            };
            command.Arguments.Add(request.SpecPath);

            try
            {
                command.Execute();
            }
            catch (Exception e)
            {
                console.WriteError(e);
            }

            return new Response(console.Messages);
        }
Beispiel #4
0
        public static void SavePackage(IPackageMetadata packageMetadata, IEnumerable<IPackageFile> files, string targetFilePath, bool useTempFile)
        {
            var builder = new PackageBuilder();
            // set metadata
            CopyMetadata(packageMetadata, builder);
            // add files
            builder.Files.AddRange(files);

            // create package in the temprary file first in case the operation fails which would
            // override existing file with a 0-byte file.
            string fileNameToUse = useTempFile ? Path.GetTempFileName() : targetFilePath;
            try {
                using (Stream stream = File.Create(fileNameToUse)) {
                    builder.Save(stream);
                }

                if (useTempFile) {
                    File.Copy(fileNameToUse, targetFilePath, true);
                }
            }
            finally {
                try {
                    if (useTempFile && File.Exists(fileNameToUse)) {
                        File.Delete(fileNameToUse);
                    }
                }
                catch {
                    // don't care if this fails
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// Go through each referenced project, and add any nuget dependencies from
        /// their packages.config file.  Ignores any that have developerDependency=true
        /// </summary>
        /// <param name="builder"></param>
        private void AddDependencies(NuGet.PackageBuilder builder)
        {
            Dictionary <string, string> NugetPackages = new Dictionary <string, string>();

            string projectRoot = Path.GetDirectoryName(this.ProjectPath);

            XElement root  = XElement.Load(this.ProjectPath);
            var      ns    = root.Name.Namespace;
            var      elems = (from el in root.Descendants(ns + "ProjectReference")
                              select el).ToList();

            if (elems.Any())
            {
                foreach (var item in elems)
                {
                    string itemPath     = item.Attribute("Include").Value;
                    string packagesPath = Path.GetFullPath(Path.Combine(projectRoot, Path.GetDirectoryName(itemPath))) + Path.DirectorySeparatorChar + PACKAGES_CONFIG;
                    GetNuGetDependencies(packagesPath, NugetPackages);
                }
            }

            if (NugetPackages.Any())
            {
                AddNugetDependencies(builder, NugetPackages);
            }
        }
        /// <summary>
        /// Creates a test package. - Take from NuGet.Core.Tests
        /// </summary>
        /// <param name="packageId">The id of the created package.</param>
        /// <param name="version">The version of the created package.</param>
        /// <param name="path">The directory where the package is created.</param>
        /// <returns>The full path of the created package file.</returns>
        public static string CreateTestPackage(string packageId, string version, string path, Uri licenseUrl = null)
        {
            var packageBuilder = new PackageBuilder
            {
                Id = packageId,
                Version = new SemanticVersion(version)
            };
            packageBuilder.Description = string.Format(
                CultureInfo.InvariantCulture,
                "desc of {0} {1}",
                packageId, version);

            if (licenseUrl != null)
            {
                packageBuilder.LicenseUrl = licenseUrl;
            }

            packageBuilder.Files.Add(CreatePackageFile(@"content\test1.txt"));
            packageBuilder.Authors.Add("test author");

            var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version);
            var packageFileFullPath = Path.Combine(path, packageFileName);
            using (var fileStream = File.Create(packageFileFullPath))
            {
                packageBuilder.Save(fileStream);
            }

            return packageFileFullPath;
        }
Beispiel #7
0
        /// <summary>
        /// Adds framework assembly and package dependencies to the package
        /// </summary>
        /// <param name="builder">
        /// The current package builder
        /// </param>
        private void AddDependencies(NuGet.PackageBuilder builder)
        {
            var dependencyManager = new DependencyManager(TargetFrameworkMoniker, AddBinariesToSubfolder, LimitMajorVersionOfDependencies, Log);

            dependencyManager.CalculateMinimalSet(this.ReferenceProjects, this.ReferenceLibraries, builder);

            foreach (var fr in dependencyManager.FrameworkReferences)
            {
                if (builder.FrameworkReferences.Any(_fr => string.Compare(_fr.AssemblyName, fr.AssemblyName, true) == 0))
                {
                    Log.LogWarning("Same frameworkAssembly reference ({0}) found in .nuspec and in referenced projects, frameworkAssembly reference from the referenced project is skipped!", fr.AssemblyName);
                }
                else
                {
                    builder.FrameworkReferences.Add(fr);
                }
            }
            foreach (var pds in dependencyManager.DependencySets)
            {
                if (pds.TargetFramework != null && builder.DependencySets.Any(_pds => _pds.TargetFramework == null && _pds.Dependencies.Any(_ds => pds.Dependencies.Any(ds => string.Compare(_ds.Id, ds.Id, true) == 0))))
                {
                    Log.LogWarning("Same dependency reference found in .nuspec (without targetFramework) and in referenced projects (with targetFrameWork), dependency reference from the referenced project is skipped!");
                }
                else if (pds.TargetFramework == null && builder.DependencySets.Any(_pds => _pds.TargetFramework != null && _pds.Dependencies.Any(_ds => pds.Dependencies.Any(ds => string.Compare(_ds.Id, ds.Id, true) == 0))))
                {
                    Log.LogWarning("Same dependency reference found in .nuspec (with targetFramework) and in referenced projects (without targetFrameWork), dependency reference from the referenced project is skipped!");
                }
                else
                {
                    builder.DependencySets.Add(pds);
                }
            }
        }
Beispiel #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("Create NuGet Package via Code");
            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "Authors Name",
                Version = "1.0.0.0",
                Id = "NuGetId",
                Description = "NuGet Package Description goes here!",
            };

            PackageBuilder builder = new PackageBuilder();


            var path = AppDomain.CurrentDomain.BaseDirectory + "..\\..\\DemoContent\\";

            builder.PopulateFiles(path, new[] { new ManifestFile { Source = "**", Target = "content" } });
            builder.Populate(metadata);

            using (FileStream stream = File.Open("test.nupkg", FileMode.OpenOrCreate))
            {
                builder.Save(stream);
            }

            Console.WriteLine("... and extract NuGet Package via Code");

            NuGet.ZipPackage package = new ZipPackage("test.nupkg");
            var content = package.GetContentFiles();

            Console.WriteLine("Package Id: " + package.Id);
            Console.WriteLine("Content-Files-Count: " + content.Count());

            Console.ReadLine();
        }
Beispiel #9
0
        public void AddLibs(PackageBuilder packageBuilder, string pattern, bool recursiveSearch)
        {
            // Look for .dll,.xml files in top directory
            var searchOption = SearchOption.TopDirectoryOnly;
            if (recursiveSearch)
            {
                //for .resources.dll, search all directories
                searchOption = SearchOption.AllDirectories;
            }
            // Add everything in the output folder to the lib path
            foreach (var path in Directory.EnumerateFiles(_outputPath, pattern, searchOption))
            {
                var targetPath = Path.Combine("lib", _targetFrameworkFolder, Path.GetFileName(path));
                if (!Path.GetDirectoryName(path).Equals(_outputPath))
                {
                    string folderName = PathUtility.GetDirectoryName(Path.GetDirectoryName(path));
                    targetPath = Path.Combine("lib", _targetFrameworkFolder, folderName, Path.GetFileName(path));
                }

                packageBuilder.Files.Add(new PhysicalPackageFile
                {
                    SourcePath = path,
                    TargetPath = targetPath
                });
            }
        }
 public void BuildNuGetPackage(NuGetPackSpecification packConfiguration)
 {
     var packageBuilder = new PackageBuilder(packConfiguration.NuSpec, NullPropertyProvider.Instance, true);
     var packagePath = Path.Combine(packConfiguration.OutputDirectory, GetDefaultPackagePath(packageBuilder));
     var packageStream = File.Create(packagePath);
     packageBuilder.Save(packageStream);
 }
Beispiel #11
0
        public static Manifest Create(PackageBuilder copy)
        {
            var metadata = new ManifestMetadata();
            metadata.Id = copy.Id?.Trim();
            metadata.Version = copy.Version;
            metadata.Title = copy.Title?.Trim();
            metadata.Authors = copy.Authors.Distinct();
            metadata.Owners = copy.Owners.Distinct();
            metadata.Tags = string.Join(",", copy.Tags).Trim();
            metadata.LicenseUrl = copy.LicenseUrl;
            metadata.ProjectUrl = copy.ProjectUrl;
            metadata.IconUrl = copy.IconUrl;
            metadata.RequireLicenseAcceptance = copy.RequireLicenseAcceptance;
            metadata.Description = copy.Description?.Trim();
            metadata.Copyright = copy.Copyright?.Trim();
            metadata.Summary = copy.Summary?.Trim();
            metadata.ReleaseNotes = copy.ReleaseNotes?.Trim();
            metadata.Language = copy.Language?.Trim();
            metadata.DependencySets = copy.DependencySets;
            metadata.FrameworkAssemblies = copy.FrameworkAssemblies;
            metadata.PackageAssemblyReferences = copy.PackageAssemblyReferences;
            metadata.MinClientVersionString = copy.MinClientVersion?.ToString();

            return new Manifest(metadata);
        }
        protected virtual void CreateNugetPackage([Diagnostics.NotNull] string tempDirectory, [Diagnostics.NotNull] string fileName, [Diagnostics.NotNull] string sourceFileName)
        {
            var packageId = Path.GetFileNameWithoutExtension(fileName);

            var sb = new StringBuilder();
            sb.AppendLine("<?xml version=\"1.0\"?>");
            sb.AppendLine("<package xmlns=\"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd\">");
            sb.AppendLine("    <metadata>");
            sb.AppendLine("        <id>" + packageId + "</id>");
            sb.AppendLine("        <title>" + packageId + "</title>");
            sb.AppendLine("        <version>1.0.0</version>");
            sb.AppendLine("        <authors>Sitecore Pathfinder</authors>");
            sb.AppendLine("        <requireLicenseAcceptance>false</requireLicenseAcceptance>");
            sb.AppendLine("        <description>Generated by Sitecore Pathfinder</description>");
            sb.AppendLine("    </metadata>");
            sb.AppendLine("    <files>");
            sb.AppendLine("        <file src=\"" + sourceFileName + "\" target=\"content\\sitecore.project\\exports.xml\" />");
            sb.AppendLine("    </files>");
            sb.AppendLine("</package>");

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())))
            {
                var packageBuilder = new PackageBuilder(stream, tempDirectory);

                using (var nupkg = new FileStream(fileName, FileMode.Create))
                {
                    packageBuilder.Save(nupkg);
                }
            }
        }
Beispiel #13
0
 private void AddFileOptionally(NuGet.PackageBuilder builder, String tgtFolder, String filePath)
 {
     if (File.Exists(filePath))
     {
         AddFile(builder, tgtFolder, filePath);
     }
 }
Beispiel #14
0
        public bool BuildPackage(IEnumerable<ProjectContext> contexts, List<DiagnosticMessage> packDiagnostics)
        {

            Reporter.Output.WriteLine($"Producing nuget package \"{GetPackageName()}\" for {Project.Name}");

            PackageBuilder = CreatePackageBuilder(Project);

            // TODO: Report errors for required fields
            // id
            // author
            // description
            foreach (var context in contexts)
            {
                Reporter.Verbose.WriteLine($"Processing {context.TargetFramework.ToString().Yellow()}");
                ProcessContext(context);
                Reporter.Verbose.WriteLine("");
            }

            var packageOutputPath = Path.Combine(
                ArtifactPathsCalculator.PackageOutputPath,
                Configuration,
                GetPackageName() + NuGet.Constants.PackageExtension);

            if (GeneratePackage(packageOutputPath, packDiagnostics))
            {
                return true;
            }

            return false;
        }
 public static IPackage BuildPackage(IPackageMetadata metadata, IEnumerable<IPackageFile> files)
 {
     var builder = new PackageBuilder();
     CopyMetadata(metadata, builder);
     builder.Files.AddRange(files);
     return builder.Build();
 }
Beispiel #16
0
        /// <summary>
        /// Compiles a single .nuspec file
        /// </summary>
        /// <param name="specItem">
        /// The .nuspec file to compile
        /// </param>
        private void BuildPackage(ITaskItem specItem)
        {
            // load the package manifest (nuspec) from the task item
            // using the nuget package builder
            var specPath = specItem.GetMetadata("FullPath");
            var builder  = new NuGet.PackageBuilder(
                specPath,
                this as NuGet.IPropertyProvider,
                true
                );

            // initialize dynamic manifest properties
            version = specItem.GetMetadata("NuPackageVersion");
            if (!String.IsNullOrEmpty(version))
            {
                builder.Version = new NuGet.SemanticVersion(version);
            }
            // add required frameworkAssemblies and dependencies based on each project
            // referenced by the current project
            if (AutoGenerateDependencies)
            {
                AddDependencies(builder);
            }
            // add a new file to the lib/tools/content folder for each project
            // referenced by the current project
            AddLibraries(builder);
            // add a new file to the tools/content folder for each project
            // specified as embedded resource by the current project
            AddEmbedded(builder);
            // write the configured package out to disk
            var pkgPath = specItem.GetMetadata("NuPackagePath");

            using (var pkgFile = File.Create(pkgPath))
                builder.Save(pkgFile);
        }
        public IPackage CreatePackage(
            string packageId,
            string packageVersion,
            string contentFilePath,
            License requiresLicenseAccept,
            params IPackage[] dependencies)
        {
            PackageBuilder builder = new PackageBuilder();
            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "dummy author",
                Version = new SemanticVersion(packageVersion).ToString(),
                Id = packageId,
                Description = "dummy description",
                LicenseUrl = "http://choosealicense.com/",
                RequireLicenseAcceptance = (requiresLicenseAccept == License.Required)
            };

            List<ManifestDependency> dependencyList = new List<ManifestDependency>();
            foreach (IPackage dependencyNode in dependencies)
            {
                dependencyList.Add(new ManifestDependency()
                {
                    Id = dependencyNode.Id,
                    Version = dependencyNode.Version.ToString(),
                });
            }

            List<ManifestDependencySet> dependencySetList = new List<ManifestDependencySet>()
            {
                new ManifestDependencySet()
                {
                    Dependencies = dependencyList
                }
            };
            metadata.DependencySets = dependencySetList;

            builder.Populate(metadata);

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = contentFilePath;
            file.TargetPath = Path.GetFileName(contentFilePath);
            builder.Files.Add(file);

            string fileName = packageId + "." + metadata.Version + ".nupkg";
            string destinationName = Path.Combine(this.manager.LocalRepository.Source, fileName);

            using (Stream fileStream = File.Open(destinationName, FileMode.OpenOrCreate))
            {
                builder.Save(fileStream);
            }

            // Retrieve and return the newly-created package
            IPackage package = this.fakeRemoteRepo.FindPackage(packageId, new SemanticVersion(packageVersion));
            Assert.IsNotNull(package, "Test setup error: failed to create and retrieve a test package");

            return package;
        }
        public void ParametersOverrideModuleSpecFile()
        {
            // Arrange
            Mock<ExportModuleCommand> mockCmd = new Mock<ExportModuleCommand>() { CallBase = true };
            mockCmd.Object.Description = "Override";
            mockCmd.Object.PackageId = "Override";
            mockCmd.Object.Version = new SemanticVersion(2, 0, 0, 0);
            mockCmd.Object.Authors = new string[] { "Over", "Ride" };
            mockCmd.Object.Copyright = "Override";
            mockCmd.Object.IconUrl = "http://over.ride";
            mockCmd.Object.Language = "ovr-RIDE";
            mockCmd.Object.LicenseUrl = "http://over.ride";
            mockCmd.Object.Owners = new string[] { "Over", "Ride" };
            mockCmd.Object.ProjectUrl = "http://over.ride";
            mockCmd.Object.ReleaseNotes = "Override";
            mockCmd.Object.RequireLicenseAcceptance = SwitchParameter.Present;
            mockCmd.Object.Summary = "Override";
            mockCmd.Object.Tags = new string[] { "Over", "Ride" };
            mockCmd.Object.Title = "Override";

            PackageBuilder expected = new PackageBuilder()
            {
                Id = "Original",
                Description = "Original",
                Version = new SemanticVersion(1, 0, 0, 0)
            };

            Mock<IFileSystem> mockFs = new Mock<IFileSystem>();
            mockFs.Setup(fs => fs.FileExists("Original.nuspec")).Returns(true);
            mockFs.Setup(fs => fs.GetAllFiles()).Returns(new string[0]);
            mockFs.Setup(fs => fs.OpenFile(It.IsAny<string>())).Returns(Stream.Null);
            mockCmd.Setup(c => c.OpenManifest(@"D:\Foo", Stream.Null)).Returns(expected);
            IModuleMetadata module = new SimpleModuleMetadata("Original", new Version(1, 0, 0, 0))
            {
                ModuleBase = @"D:\Foo"
            };

            // Act
            PackageBuilder actual = mockCmd.Object.BuildManifest(module, mockFs.Object);

            // Assert
            Assert.Equal("Override", actual.Description);
            Assert.Equal("Override", actual.Id);
            Assert.Equal(new SemanticVersion(2, 0, 0, 0), actual.Version);
            Assert.Equal(new string[] { "Over", "Ride" }, actual.Authors.ToArray());
            Assert.Equal("Override", actual.Copyright);
            Assert.Equal("http://over.ride/", actual.IconUrl.ToString());
            Assert.Equal("ovr-RIDE", actual.Language);
            Assert.Equal("http://over.ride/", actual.LicenseUrl.ToString());
            Assert.Equal(new string[] { "Over", "Ride" }, actual.Owners.ToArray());
            Assert.Equal("http://over.ride/", actual.ProjectUrl.ToString());
            Assert.Equal("Override", actual.ReleaseNotes);
            Assert.True(actual.RequireLicenseAcceptance);
            Assert.Equal("Override", actual.Summary);
            Assert.Equal(new string[] { "Over", "Ride" }, actual.Tags.ToArray());
            Assert.Equal("Override", actual.Title);
        }
Beispiel #19
0
        /// <summary>
        /// Creates a NuGet package from this mock package spec and copies it into the
        /// specified repository path.
        /// </summary>
        /// <param name="buildPath"></param>
        /// <param name="repositoryPath"></param>
        public void CreatePackage(string buildPath, string repositoryPath)
        {
            NuGet.PackageBuilder   builder  = new NuGet.PackageBuilder();
            NuGet.ManifestMetadata metadata = new NuGet.ManifestMetadata
            {
                Authors        = "AdamsLair",
                Version        = this.name.Version.ToString(),
                Id             = this.name.Id,
                Description    = string.Format("Mock Package: {0} {1}", this.name.Id, this.name.Version),
                Tags           = string.Join(" ", this.tags),
                DependencySets = this.dependencySets.Select(pair => new NuGet.ManifestDependencySet()
                {
                    TargetFramework = pair.Key,
                    Dependencies    =
                        pair.Value
                        .Select(item => new NuGet.ManifestDependency {
                        Id = item.Id, Version = item.Version.ToString()
                    })
                        .ToList()
                }).ToList()
            };

            // Set up file contents metadata for the package
            List <NuGet.ManifestFile> fileMetadata = new List <NuGet.ManifestFile>();

            foreach (var pair in this.files)
            {
                fileMetadata.Add(new NuGet.ManifestFile {
                    Source = pair.Key, Target = pair.Value
                });
                this.CreateFile(buildPath, pair.Key);
            }

            // If we don't have files or dependencies, at least at one mock file so we
            // can create a package at all. This is useful for test cases where we're
            // not actually interested in package contents at all.
            if (this.files.Count == 0 && !this.dependencySets.SelectMany(pair => pair.Value).Any())
            {
                fileMetadata.Add(new NuGet.ManifestFile {
                    Source = "Empty.dll", Target = "lib"
                });
                this.CreateFile(buildPath, "Empty.dll");
            }

            builder.PopulateFiles(buildPath, fileMetadata);
            builder.Populate(metadata);

            string packageFileName = Path.Combine(
                repositoryPath,
                string.Format("{0}.{1}.nupkg", this.name.Id, this.name.Version));

            using (FileStream stream = File.Open(packageFileName, FileMode.Create))
            {
                builder.Save(stream);
            }
        }
 public void BuildPackage(string baseUrl, ManifestMetadata metadata, ManifestFile[] files)
 {
     NuGet.PackageBuilder packageBuilder = new NuGet.PackageBuilder();
     packageBuilder.Populate(metadata);
     packageBuilder.PopulateFiles(baseUrl, files);
     var saveDir = Path.Combine(DEFAULT_PACKAGES_SAVE_PATH, packageBuilder.Id, packageBuilder.Version.ToString().Replace('.', '_'));
     Directory.CreateDirectory(saveDir);
     var saveStream = File.Create(Path.Combine(saveDir, packageBuilder.Id + ".nupkg"));
     packageBuilder.Save(saveStream);
 }
Beispiel #21
0
 private void AddFile(NuGet.PackageBuilder builder, String tgtFolder, String filePath)
 {
     builder.Files.Add(
         new NuGet.PhysicalPackageFile()
     {
         SourcePath = filePath,
         TargetPath = Path.Combine(tgtFolder, Path.GetFileName(filePath))
     }
         );
 }
Beispiel #22
0
        public static void PopulateDependencies(ProjectContext context, PackageBuilder packageBuilder)
        {
            var dependencies = new List<PackageDependency>();
            var project = context.RootProject;

            foreach (var dependency in project.Dependencies)
            {
                if (!dependency.HasFlag(LibraryDependencyTypeFlag.BecomesNupkgDependency))
                {
                    continue;
                }

                // TODO: Efficiency
                var dependencyDescription = context.LibraryManager.GetLibraries().First(l => l.RequestedRanges.Contains(dependency));

                // REVIEW: Can we get this far with unresolved dependencies
                if (dependencyDescription == null || !dependencyDescription.Resolved)
                {
                    continue;
                }

                if (dependencyDescription.Identity.Type == LibraryType.Project &&
                    ((ProjectDescription)dependencyDescription).Project.EmbedInteropTypes)
                {
                    continue;
                }

                if (dependency.Target == LibraryType.ReferenceAssembly)
                {
                    packageBuilder.FrameworkAssemblies.Add(new FrameworkAssemblyReference(dependency.Name, new[] { context.TargetFramework }));

                    Reporter.Verbose.WriteLine($"Adding framework assembly {dependency.Name.Yellow()}");
                }
                else
                {
                    VersionRange dependencyVersion = null;

                    if (dependency.VersionRange == null ||
                        dependency.VersionRange.IsFloating)
                    {
                        dependencyVersion = new VersionRange(dependencyDescription.Identity.Version);
                    }
                    else
                    {
                        dependencyVersion = dependency.VersionRange;
                    }

                    Reporter.Verbose.WriteLine($"Adding dependency {dependency.Name.Yellow()} {VersionUtility.RenderVersion(dependencyVersion).Yellow()}");

                    dependencies.Add(new PackageDependency(dependency.Name, dependencyVersion));
                }
            }

            packageBuilder.DependencySets.Add(new PackageDependencySet(context.TargetFramework, dependencies));
        }
Beispiel #23
0
        private static void BuildPackages()
        {
            var           directory  = new DirectoryInfo(BuildDirectory);
            XmlSerializer serializer = new XmlSerializer(typeof(game));
            var           fs         = File.Open(directory.GetFiles().First().FullName, FileMode.Open);
            var           game       = (game)serializer.Deserialize(fs);

            fs.Close();
            var builder = new NuGet.PackageBuilder()
            {
                Id          = game.id,
                Description = game.description,
                ProjectUrl  = new Uri(game.gameurl),
                Version     = new SemanticVersion(game.version),
                Title       = game.name,
                IconUrl     = new Uri(game.iconurl),
            };

            foreach (var author in game.authors.Split(','))
            {
                builder.Authors.Add(author);
            }
            foreach (var tag in game.tags.Split(' '))
            {
                builder.Tags.Add(tag);
            }
            // files and maybe release notes
            var allFiles = directory
                           .GetFiles("*.*", SearchOption.AllDirectories)
                           .Where(x => x.Extension.ToLower() != ".nupkg" && x.Extension.ToLower() != ".o8g");

            foreach (var file in allFiles)
            {
                var path    = file.FullName;
                var relPath = path.Replace(directory.FullName, "\\def");
                var pf      = new PhysicalPackageFile()
                {
                    SourcePath = path, TargetPath = relPath
                };

                builder.Files.Add(pf);
            }
            var feedPath   = Path.Combine(directory.FullName, game.name + '-' + game.version + ".nupkg");
            var olPath     = Path.Combine(directory.FullName, game.name + '-' + game.version + ".o8g");
            var filestream = File.Open(feedPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
            filestream = File.Open(olPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
        }
Beispiel #24
0
 /// <summary>
 /// Adds project references to the package lib/tools/content section
 /// </summary>
 /// <param name="builder">
 /// The current package builder
 /// </param>
 private void AddLibraries(NuGet.PackageBuilder builder)
 {
     // add package files from project references
     // . DLL references go in the lib package folder
     // . EXE references go in the tools package folder
     // . everything else goes in the content package folder
     // . folders may be overridden using NuBuildTargetFolder metadata (lib\net40, etc.)
     // . folders may be overridden using TargetFramework attribute (lib\net40, etc.)
     foreach (var libItem in this.ReferenceLibraries
              .ValidReferenceLibraryForBinaryNuSource())
     {
         //AddFile(builder, libItem.GetMetadata("FullPath"), libItem.GetMetadata("NuBuildTargetFolder"));
         var srcPath   = libItem.GetMetadata("FullPath");;
         var srcExt    = Path.GetExtension(srcPath).ToLower();
         var tgtFolder = "content";
         var hasPdb    = false;
         if (srcExt == ".dll")
         {
             tgtFolder = "lib";
             hasPdb    = true;
         }
         else if (srcExt == ".exe")
         {
             tgtFolder = AddExecutablesToLibFolder ? "lib" : "tools";
             hasPdb    = true;
         }
         // apply the custom folder override on the reference, or based on TargetFramework
         var customFolder = libItem.GetMetadata("NuBuildTargetFolder");
         if (!String.IsNullOrWhiteSpace(customFolder))
         {
             tgtFolder = customFolder;
         }
         else if (AddBinariesToSubfolder)
         {
             try
             {
                 var targetFrameworkName = AssemblyReader.Read(srcPath).TargetFrameworkName;
                 if (!String.IsNullOrWhiteSpace(targetFrameworkName))
                 {
                     tgtFolder = Path.Combine(tgtFolder, VersionUtility.GetShortFrameworkName(new FrameworkName(targetFrameworkName)));
                 }
             }
             catch { }
         }
         // add the source library file to the package
         AddFile(builder, tgtFolder, srcPath);
         // add PDB and/or XML if specified and exist
         if (hasPdb && this.IncludePdbs)
         {
             AddFileOptionally(builder, tgtFolder, Path.ChangeExtension(srcPath, ".pdb"));
             AddFileOptionally(builder, tgtFolder, Path.ChangeExtension(srcPath, ".xml"));
         }
     }
 }
Beispiel #25
0
 public void AddLibs(PackageBuilder packageBuilder, string pattern)
 {
     // Add everything in the output folder to the lib path
     foreach (var path in Directory.EnumerateFiles(_outputPath, pattern))
     {
         packageBuilder.Files.Add(new PhysicalPackageFile
         {
             SourcePath = path,
             TargetPath = Path.Combine("lib", _targetFrameworkFolder, Path.GetFileName(path))
         });
     }
 }
        protected override void ProcessCompleted(string url, string targetFileName, Action <string> completed)
        {
            Debug.ArgumentNotNull(completed, nameof(completed));
            Debug.ArgumentNotNull(targetFileName, nameof(targetFileName));
            Debug.ArgumentNotNull(url, nameof(url));

            targetFileName = Path.ChangeExtension(targetFileName, "nuspec");

            var client = new WebClient();

            try
            {
                client.DownloadFile(url, targetFileName);
            }
            catch (WebException ex)
            {
                if (AppHost.MessageBox(string.Format("Failed to download the package file: {0}\n\nDo you want to report this error?\n\n{1}\n{2}", url, ex.Message, ex.StackTrace), "Information", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                {
                    AppHost.Shell.HandleException(ex);
                }

                completed(string.Empty);
                return;
            }

            var nuspecFileName = targetFileName;
            var nupkgFileName  = Path.ChangeExtension(nuspecFileName, string.Empty) + Version + ".nupkg";

            try
            {
                using (var nuspec = new FileStream(nuspecFileName, FileMode.Open, FileAccess.Read))
                {
                    var packageBuilder = new NuGet.PackageBuilder(nuspec, Path.GetDirectoryName(targetFileName));

                    using (var nupkg = new FileStream(nupkgFileName, FileMode.Create))
                    {
                        packageBuilder.Save(nupkg);
                    }
                }
            }
            catch (Exception ex)
            {
                if (AppHost.MessageBox(string.Format("Failed to create the NuGet package file: {0}\n\nDo you want to report this error?\n\n{1}", url, ex.Message), "Information", MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                {
                    AppHost.Shell.HandleException(ex);
                }

                completed(string.Empty);
                return;
            }

            completed(nupkgFileName);
        }
        private void ExecuteBuildNuGetPackages(BuildConfiguration configuration)
        {
            foreach (var buildNuGetPackage in configuration.BuildNuGetPackages)
            {
                try
                {
                    var properties = new PropertyProvider();

                    string version = buildNuGetPackage.Version;

                    if (version == null)
                        version = VersionRetriever.GetVersion(TargetPath);

                    properties.Properties["version"] = version;

                    string manifest = TranslatePath(buildNuGetPackage.Manifest);

                    var builder = new PackageBuilder(
                        manifest,
                        buildNuGetPackage.BasePath ?? TargetDir,
                        properties,
                        false
                    );

                    string target =
                        buildNuGetPackage.Target != null
                        ? TranslatePath(buildNuGetPackage.Target)
                        : Path.Combine(TargetDir, Path.GetFileNameWithoutExtension(manifest) + "." + version + ".nupkg");

                    bool isExistingPackage = File.Exists(target);
                    try
                    {
                        using (Stream stream = File.Create(target))
                        {
                            builder.Save(stream);
                        }
                    }
                    catch
                    {
                        if (!isExistingPackage && File.Exists(target))
                            File.Delete(target);

                        throw;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogErrorFromException(ex);
                }
            }
        }
        private PackageBuilder CreatePackage()
        {
            PackageBuilder pb = new PackageBuilder();
            pb.Id = Id;
            pb.Version = new SemanticVersion(Version);
            pb.Title = Title;
            pb.Description = Description;
            pb.Authors.AddRange(Authors.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            pb.Owners.AddRange(Owners.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
            if (FrameworkAssemblies != null)
                foreach (var fa in FrameworkAssemblies)
                    pb.FrameworkReferences.Add(new FrameworkAssemblyReference(fa.FrameworkName));
            if (Dependencies != null)
            {
                var groups = new Dictionary<string, List<NuGetDependency>>();
                foreach (var dpg in Dependencies)
                {
                    string framework = dpg.TargetFramework;
                    if (String.IsNullOrWhiteSpace(framework))
                        framework = "";

                    List<NuGetDependency> list;
                    if (!groups.TryGetValue(framework, out list))
                        groups[framework] = list = new List<NuGetDependency>();

                    list.AddRange(dpg.Dependencies);
                }

                foreach (var g in groups)
                {
                    FrameworkName fn = g.Key == "" ? null : VersionUtility.ParseFrameworkName(g.Key);
                    PackageDependencySet ds = new PackageDependencySet(fn, g.Value.Select(v => (PackageDependency)v));
                    pb.DependencySets.Add(ds);
                }
            }
            if (Icon != null)
                pb.IconUrl = Icon;
            if (Url != null)
                pb.ProjectUrl = Url;
            if (License != null)
                pb.LicenseUrl = License;
            if (Summary != null)
                pb.Summary = Summary;
            if (Copyright != null)
                pb.Copyright = Copyright;
            if (ReleaseNotes != null)
                pb.ReleaseNotes = ReleaseNotes;

            return pb;
        }
Beispiel #29
0
        private static PackageBuilder CreatePackageBuilder(Project project)
        {
            var builder = new PackageBuilder();

            builder.Authors.AddRange(project.Authors);
            builder.Owners.AddRange(project.PackOptions.Owners);

            if (builder.Authors.Count == 0)
            {
                var defaultAuthor = Environment.GetEnvironmentVariable("NUGET_AUTHOR");
                if (string.IsNullOrEmpty(defaultAuthor))
                {
                    builder.Authors.Add(project.Name);
                }
                else
                {
                    builder.Authors.Add(defaultAuthor);
                }
            }

            builder.Description = project.Description ?? project.Name;
            builder.Id          = project.Name;
            builder.Version     = project.Version;
            builder.Title       = project.Title;
            builder.Summary     = project.PackOptions.Summary;
            builder.Copyright   = project.Copyright;
            builder.RequireLicenseAcceptance = project.PackOptions.RequireLicenseAcceptance;
            builder.ReleaseNotes             = project.PackOptions.ReleaseNotes;
            builder.Language = project.Language;
            builder.Tags.AddRange(project.PackOptions.Tags);
            builder.Serviceable = project.Serviceable;

            if (!string.IsNullOrEmpty(project.PackOptions.IconUrl))
            {
                builder.IconUrl = new Uri(project.PackOptions.IconUrl);
            }

            if (!string.IsNullOrEmpty(project.PackOptions.ProjectUrl))
            {
                builder.ProjectUrl = new Uri(project.PackOptions.ProjectUrl);
            }

            if (!string.IsNullOrEmpty(project.PackOptions.LicenseUrl))
            {
                builder.LicenseUrl = new Uri(project.PackOptions.LicenseUrl);
            }

            return(builder);
        }
Beispiel #30
0
        /// <summary>
        /// Inserts a dependency set into the packagebuilder object, based on a dictionary
        /// containing Id/version pairs (Newtonsoft.json, 5.0.6 for example).
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="packages"></param>
        private void AddNugetDependencies(NuGet.PackageBuilder builder, Dictionary <string, string> packages)
        {
            //add dependencies
            List <PackageDependency> dependencies = new List <PackageDependency>();

            foreach (var package in packages)
            {
                dependencies.Add(new PackageDependency(package.Key, new VersionSpec {
                    MinVersion = new SemanticVersion(package.Value), IsMinInclusive = true
                }));
            }

            var set = new PackageDependencySet(null, dependencies);

            builder.DependencySets.Add(set);
        }
Beispiel #31
0
        static void Main()
        {
            Console.Title = "Nuget Packer";
            Console.WriteLine("Prepare...");

            string packages = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Packages");
            if (Directory.Exists(packages))
                Directory.Delete(packages, true);
            Directory.CreateDirectory(packages);
            Console.WriteLine();

            foreach (var directory in Directory.EnumerateDirectories(AppDomain.CurrentDomain.BaseDirectory))
            {
                try
                {
                    Console.Write("Packing... ");
                    if(directory.EndsWith("Packages")) continue;

                    string name = Path.GetFileName(directory) + ".nuspec";
                    var pack = new PackageBuilder(Directory.EnumerateFiles(directory).First(s => s.EndsWith(name)),
                                                  directory, null, true);
                    Console.Write(pack.Id + "... ");

                    using (var stream = new FileStream(Path.Combine(packages, pack.Id + ".nupkg"), FileMode.Create))
                    {
                        pack.Save(stream);
                    }

                    Directory.Delete(directory, true);

                    Console.WriteLine("Done");
                }
                catch (Exception e)
                {
                    Console.WriteLine();
                    Console.Write("Error: ");
                    Console.WriteLine(e);
                    Console.WriteLine("Press enter.");
                    Console.ReadKey();
                }
            }

            Console.WriteLine();
            Console.WriteLine("Finished");
            Console.WriteLine("Press Enter...");
            Console.ReadKey();
        }
        private void Pack([NotNull] IBuildContext context, [NotNull] string zipFileName)
        {
            var packageName = Path.GetFileNameWithoutExtension(zipFileName);
            var packageId = packageName.GetSafeCodeIdentifier();

            var srcFileName = PathHelper.UnmapPath(context.ProjectDirectory, zipFileName);
            var targetFileName = "content\\packages\\" + Path.GetFileName(zipFileName);

            context.Trace.TraceInformation(Msg.M1016, Texts.Packing, packageName);

            var nuspec = new StringWriter();
            nuspec.WriteLine("<package xmlns=\"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd\">");
            nuspec.WriteLine("    <metadata>");
            nuspec.WriteLine("        <id>" + packageId + "</id>");
            nuspec.WriteLine("        <title>" + packageName + "</title>");
            nuspec.WriteLine("        <version>1.0.0</version>");
            nuspec.WriteLine("        <authors>Sitecore Pathfinder</authors>");
            nuspec.WriteLine("        <requireLicenseAcceptance>false</requireLicenseAcceptance>");
            nuspec.WriteLine("        <description>Generated by Sitecore Pathfinder</description>");
            nuspec.WriteLine("    </metadata>");
            nuspec.WriteLine("    <files>");
            nuspec.WriteLine("        <file src=\"" + srcFileName + "\" target=\"" + targetFileName + "\"/>");
            nuspec.WriteLine("    </files>");
            nuspec.WriteLine("</package>");

            var nupkgFileName = Path.Combine(Path.GetDirectoryName(zipFileName) ?? string.Empty, packageId + ".nupkg");

            try
            {
                var byteArray = Encoding.UTF8.GetBytes(nuspec.ToString());
                using (var nuspecStream = new MemoryStream(byteArray))
                {
                    var packageBuilder = new PackageBuilder(nuspecStream, context.ProjectDirectory);

                    using (var nupkg = new FileStream(nupkgFileName, FileMode.Create))
                    {
                        packageBuilder.Save(nupkg);
                    }
                }
            }
            catch (Exception ex)
            {
                context.Trace.TraceError(Msg.M1003, Texts.Failed_to_create_the_Nupkg_file, ex.Message);
            }
        }
Beispiel #33
0
 private static void CopyMetadata(IPackageMetadata source, PackageBuilder builder)
 {
     builder.Id = source.Id;
     builder.Version = source.Version;
     builder.Title = source.Title;
     builder.Authors.AddRange(source.Authors);
     builder.Owners.AddRange(source.Owners);
     builder.IconUrl = source.IconUrl;
     builder.LicenseUrl = source.LicenseUrl;
     builder.ProjectUrl = source.ProjectUrl;
     builder.RequireLicenseAcceptance = source.RequireLicenseAcceptance;
     builder.Description = source.Description;
     builder.Summary = source.Summary;
     builder.Language = source.Language;
     builder.Tags.AddRange(ParseTags(source.Tags));
     builder.Dependencies.AddRange(source.Dependencies);
     builder.FrameworkReferences.AddRange(source.FrameworkAssemblies);
 }
        private static Stream CreateTestPackageStream()
        {
            var packageStream = new MemoryStream();
            var builder = new PackageBuilder
            {
                Id = "TestPackage",
                Version = SemanticVersion.Parse("0.0.0.1"),
                Description = "Trivial Description",
                Authors = { "AuthorsIsRequiredSayWhaat?" },
            };

            var file = new Mock<IPackageFile>();
            file.Setup(s => s.Path).Returns(@"content\HelloWorld.cs");
            file.Setup(s => s.GetStream()).Returns(Stream.Null);
            builder.Files.Add(file.Object);

            builder.Save(packageStream);
            return packageStream;
        }
        /// <summary>
        /// Creates a local nupkg file, and stores it in a local folder (<see cref="LocalNuGetPackageFolder"/>).
        /// </summary>
        /// <returns>The path to the nupkg file</returns>
        public static string CreateLocalNupkgFile(string nuspecFilePath, string directory)
        {
            var packageName = nuspecFilePath.Substring(nuspecFilePath.LastIndexOf(Path.DirectorySeparatorChar) + 1)
                .Replace(".nuspec", ".nupkg");
            var nupkg = Path.Combine(LocalNuGetPackageFolder, packageName);

            // read the nuspec metadata file 
            using (var stream = new FileStream(nuspecFilePath, FileMode.Open, FileAccess.Read))
            {
                TraceSource.TraceEvent(TraceEventType.Verbose, "Creating {0}", packageName);
                // create the package and save it to disk
                var builder = new PackageBuilder(stream, directory);
                using (FileStream nupkgStream = File.Open(nupkg, FileMode.Create))
                {
                    builder.Save(nupkgStream);
                }
                TraceSource.TraceEvent(TraceEventType.Verbose, "{0} was created", nupkg);
            }
            return nupkg;
        }
        public void BuildPackage(string basePath, IList<string> includes, ManifestMetadata metadata, string outFolder, bool overwrite)
        {
            var package = new PackageBuilder();

            package.PopulateFiles(basePath, includes.Select(i => new ManifestFile { Source = i }));
            package.Populate(metadata);

            var filename = metadata.Id + "." + metadata.Version + ".nupkg";
            var output = Path.Combine(outFolder, filename);

            if (fileSystem.FileExists(output) && !overwrite)
                throw new CommandException("The package file already exists and --overwrite was not specified");

            log.InfoFormat("Saving {0} to {1}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            using (var outStream = fileSystem.OpenFile(output, FileMode.Create))
                package.Save(outStream);
        }
        public PackageBuilder BuildPackage(IEnumerable<IPackageFile> packageFiles, PackageMetadata metaData)
        {
            var package = new PackageBuilder
            {
                Id = metaData.Id,
                Version = metaData.Version,
                Description = metaData.Description
            };

            foreach (var item in metaData.Authors)
            {
                package.Authors.Add(item);
            }

            foreach (var file in packageFiles)
            {
                package.Files.Add(file);
            }

            return package;
        }
Beispiel #38
0
        private IPackage createPackage(PackageBuilder builder, string outputPath)
        {
            bool isExistingPackage = File.Exists(outputPath);
            try
            {
                using (Stream stream = File.Create(outputPath))
                {
                    builder.Save(stream);
                }
            }
            catch
            {
                if (!isExistingPackage && File.Exists(outputPath))
                {
                    File.Delete(outputPath);
                }
                throw;
            }

            RippleLog.Info("Created nuget at: " + outputPath);
            return new ZipPackage(outputPath);
        }
        protected virtual void BuildNupkgFile([NotNull] IBuildContext context, [NotNull] string nuspecFileName, [NotNull] string nupkgFileName)
        {
            var configFileName = Path.Combine(context.ToolsDirectory, context.Configuration.GetString(Constants.Configuration.ProjectConfigFileName));

            var nuspec = context.FileSystem.ReadAllText(nuspecFileName);
            nuspec = nuspec.Replace("$global.scconfig.json$", configFileName);

            var stream = new MemoryStream(Encoding.UTF8.GetBytes(nuspec));
            try
            {
                var packageBuilder = new PackageBuilder(stream, context.ProjectDirectory);

                using (var nupkg = new FileStream(nupkgFileName, FileMode.Create))
                {
                    packageBuilder.Save(nupkg);
                }
            }
            catch (Exception ex)
            {
                context.Trace.TraceError(Msg.D1020, Texts.Failed_to_create_the_Nupkg_file, ex.Message);
            }
        }
Beispiel #40
0
        IPackage IPackageFactory.CreateFromProject(string nupecFile, string csprojFile, string buildConfiguration, bool includeBinOutput)
        {
            var projectReader = _projectReaderFactory.Create(csprojFile);
            var binDir = projectReader.GetBinPath(buildConfiguration);
            var assemblyName = projectReader.GetAssemblyName();
            var assemblyPath = _fileSystem.CombinePaths(binDir, assemblyName);
            var assemblyReader = _assemblyReaderFactory.Create(assemblyPath);

            var manifest = new ManifestMetadata()
            {
                Id = assemblyReader.GetPackageId(),
                Title = assemblyReader.GetPackageTitle(),
                Owners = assemblyReader.GetCompany(),
                Authors = assemblyReader.GetCompany(),
                Description = assemblyReader.GetDescription(),
                Copyright = assemblyReader.GetCopyright(),
                Version = assemblyReader.GetFileVersion()
            };

            var files = new List<ManifestFile>();
            foreach (var dll in _fileSystem.FindFiles(binDir, "*.dll", false))
                files.Add(new ManifestFile() { Source = dll, Target = @"lib\net40" });

            var packageBuilder = new PackageBuilder();
            packageBuilder.Populate(manifest);
            packageBuilder.PopulateFiles(string.Empty, files);

            var projDir = _fileSystem.GetDirectory(csprojFile);
            var packagefile = _fileSystem.CombinePaths(projDir, "packages.config");

            var packagePath = _fileSystem.ChangeFileExtension(csprojFile, "nupkg");
            using (var stream = _fileSystem.OpenWrite(packagePath))
            {
                packageBuilder.Save(stream);
            }

            return new ZipPackage(packagePath);
        }
Beispiel #41
0
        public static Response Restore(NuGetRestoreRequest request)
        {
            var console = new Console();
            PackageBuilder builder = new PackageBuilder();
            var command = new RestoreCommand
            {
                FileSystem = new PhysicalFileSystem(PathTools.OptimizePath(request.BaseDirectory)),
                Console = console,
                Verbosity = Verbosity.Detailed,
            };
            command.Arguments.Add(request.SolutionPath);

            try
            {
                command.Execute();
            }
            catch (Exception e)
            {
                console.WriteError(e);
            }

            return new Response(console.Messages);
        }
Beispiel #42
0
        public static IPackage BuildPackage(PackageBuilder builder, IFileSystem fileSystem, string outputPath = null)
        {
            ExcludeFiles(builder.Files);
            // Track if the package file was already present on disk
            bool isExistingPackage = fileSystem.file_exists(outputPath);
            try
            {
                using (Stream stream = fileSystem.create_file(outputPath))
                {
                    builder.Save(stream);
                }
            }
            catch
            {
                if (!isExistingPackage && fileSystem.file_exists(outputPath))
                {
                    fileSystem.delete_file(outputPath);
                }
                throw;
            }

            return new OptimizedZipPackage(outputPath);
        }
 private static void CopyMetadata(IPackageMetadata source, PackageBuilder builder)
 {
     builder.Id = source.Id;
     builder.Version = source.Version;
     builder.Title = source.Title;
     builder.Authors.AddRange(source.Authors);
     builder.Owners.AddRange(source.Owners);
     builder.IconUrl = source.IconUrl;
     builder.LicenseUrl = source.LicenseUrl;
     builder.ProjectUrl = source.ProjectUrl;
     builder.RequireLicenseAcceptance = source.RequireLicenseAcceptance;
     builder.DevelopmentDependency = source.DevelopmentDependency;
     builder.Description = source.Description;
     builder.Summary = source.Summary;
     builder.ReleaseNotes = source.ReleaseNotes;
     builder.Copyright = source.Copyright;
     builder.Language = source.Language;
     builder.Tags.AddRange(ParseTags(source.Tags));
     builder.DependencySets.AddRange(source.DependencySets);
     builder.FrameworkReferences.AddRange(source.FrameworkAssemblies);
     builder.PackageAssemblyReferences.AddRange(source.PackageAssemblyReferences);
     builder.MinClientVersion = source.MinClientVersion;
 }
Beispiel #44
0
 /// <summary>
 /// Adds embedded resources to the package tools/content section
 /// </summary>
 /// <param name="builder">
 /// The current package builder
 /// </param>
 private void AddEmbedded(NuGet.PackageBuilder builder)
 {
     // add package files from project embedded resources
     foreach (var fileItem in this.Embedded)
     {
         // only link items has Link metadata, that is the path, where the link itself is located (not the referred item)
         var tgtPath = fileItem.GetMetadata("Link");
         // if it is not a link, handle as normal file
         if (String.IsNullOrEmpty(tgtPath))
         {
             tgtPath = fileItem.GetMetadata("Identity");
         }
         if (tgtPath.IndexOf('\\') == -1)
         {
             // warning if file is not in a subfolder
             Log.LogWarning(
                 "The source item '{0}' is not a valid content! Files has to be in a subfolder, like content or tools! File skipped.",
                 tgtPath);
         }
         else
         {
             // determine pre package processing necessity
             var prePackProc = tgtPath.EndsWith(".ppp");
             if (prePackProc)
             {
                 tgtPath = tgtPath.Substring(0, tgtPath.Length - 4);
             }
             // create the source file
             var file = prePackProc ? new TokenProcessingPhysicalPackageFile(this) : new PhysicalPackageFile();
             file.SourcePath = fileItem.GetMetadata("FullPath");
             file.TargetPath = tgtPath;
             // add the source file to the package
             builder.Files.Add(file);
         }
     }
 }
Beispiel #45
0
        private static void BuildPackages()
        {
            var           directory  = new DirectoryInfo(BuildDirectory);
            XmlSerializer serializer = new XmlSerializer(typeof(game));
            var           fs         = File.Open(directory.GetFiles().First(x => x.Name == "definition.xml").FullName, FileMode.Open);
            var           game       = (game)serializer.Deserialize(fs);

            fs.Close();
            var builder = new NuGet.PackageBuilder()
            {
                Id          = game.id,
                Description = game.description,
                ProjectUrl  = new Uri(game.gameurl),
                Version     = new SemanticVersion(game.version),
                Title       = game.name,
                IconUrl     = new Uri(game.iconurl),
            };

            foreach (var author in game.authors.Split(','))
            {
                builder.Authors.Add(author);
            }
            foreach (var tag in game.tags.Split(' '))
            {
                builder.Tags.Add(tag);
            }
            // files and maybe release notes

            var baseRefPath = "\\def";

            foreach (var dir in directory.GetDirectories())
            {
                if (dir.Name == "Sets")
                {
                    var refpath = baseRefPath + "\\" + "Sets" + "\\";
                    foreach (var setdir in dir.GetDirectories())
                    {
                        var doc        = XDocument.Load(Path.Combine(setdir.FullName, "set.xml"));
                        var gameId     = doc.Root.Attribute("id").Value;
                        var setRefPath = refpath + gameId;
                        foreach (var f in setdir.GetFiles("*", SearchOption.AllDirectories))
                        {
                            var relPath = f.FullName.Replace(setdir.FullName, setRefPath);
                            var pf      = new PhysicalPackageFile()
                            {
                                SourcePath = f.FullName, TargetPath = relPath
                            };
                            builder.Files.Add(pf);
                        }
                    }
                }
                else
                {
                    var refpath = baseRefPath + "\\" + dir.Name;
                    var files   = dir.GetFiles("*", SearchOption.AllDirectories);
                    foreach (var f in files)
                    {
                        var relPath = f.FullName.Replace(dir.FullName, refpath);
                        var pf      = new PhysicalPackageFile()
                        {
                            SourcePath = f.FullName, TargetPath = relPath
                        };
                        builder.Files.Add(pf);
                    }
                }
            }
            var defFile     = new FileInfo(Path.Combine(directory.FullName, "definition.xml"));
            var defFilePack = new PhysicalPackageFile()
            {
                SourcePath = defFile.FullName,
                TargetPath =
                    defFile.FullName.Replace(defFile.Directory.FullName, baseRefPath)
            };

            builder.Files.Add(defFilePack);


            //var allFiles = directory
            //    .GetFiles("*.*", SearchOption.AllDirectories)
            //    .Where(x=>x.Extension.ToLower() != ".nupkg" && x.Extension.ToLower() != ".o8g");
            //foreach (var file in allFiles)
            //{
            //    //Sets\0abccf03-2825-4b6e-ba59-698408a2005c
            //    var path = file.FullName;
            //    var relPath = path.Replace(directory.FullName, "\\def");
            //    var pf = new PhysicalPackageFile() { SourcePath = path, TargetPath = relPath };

            //    builder.Files.Add(pf);
            //}
            var feedPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".nupkg");

            // var olPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".o8g");
            // O8gPath = olPath;
            NupkgPath = feedPath;
            Console.WriteLine("Feed Path: " + feedPath);
            // Console.WriteLine("Manual Path: " + olPath);
            var filestream = File.Open(feedPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
            // filestream = File.Open(olPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            // builder.Save(filestream);
            // filestream.Flush(true);
            // filestream.Close();
        }
Beispiel #46
0
        /// <summary>
        /// Adds project references to the package lib section
        /// </summary>
        /// <param name="builder">
        /// The current package builder
        /// </param>
        private void AddLibraries(NuGet.PackageBuilder builder)
        {
            // add package files from project references
            // . DLL references go in the lib package folder
            // . EXE references go in the tools package folder
            // . everything else goes in the content package folder
            // . folders may be overridden using NuBuildTargetFolder metadata (lib\net40, etc.)
            // . folders may be overridden using TargetFramework attribute (lib\net40, etc.)
            foreach (var libItem in this.ReferenceLibraries)
            {
                var srcPath   = libItem.GetMetadata("FullPath");
                var srcExt    = Path.GetExtension(srcPath).ToLower();
                var tgtFolder = "content";
                var hasPdb    = false;
                if (srcExt == ".dll")
                {
                    tgtFolder = "lib";
                    hasPdb    = true;
                }
                else if (srcExt == ".exe")
                {
                    tgtFolder = "tools";
                    hasPdb    = true;
                }

                // apply the custom folder override on the reference, or based on TargetFramework
                var customFolder = libItem.GetMetadata("NuBuildTargetFolder");
                if (!String.IsNullOrWhiteSpace(customFolder))
                {
                    tgtFolder = customFolder;
                }
                else if (AddBinariesToSubfolder)
                {
                    try
                    {
                        var targetFrameworkName = libItem.GetMetadata("TargetFrameworkName");
                        if (!String.IsNullOrWhiteSpace(targetFrameworkName))
                        {
                            tgtFolder = Path.Combine(tgtFolder, VersionUtility.GetShortFrameworkName(new FrameworkName(targetFrameworkName)));
                        }
                    }
                    catch { }
                }
                // add the source library file to the package
                builder.Files.Add(
                    new NuGet.PhysicalPackageFile()
                {
                    SourcePath = srcPath,
                    TargetPath = String.Format(
                        @"{0}\{1}",
                        tgtFolder,
                        Path.GetFileName(srcPath)
                        )
                }
                    );
                // add PDBs if specified and exist
                if (hasPdb && this.IncludePdbs)
                {
                    var pdbPath = Path.ChangeExtension(srcPath, ".pdb");
                    if (File.Exists(pdbPath))
                    {
                        builder.Files.Add(
                            new NuGet.PhysicalPackageFile()
                        {
                            SourcePath = pdbPath,
                            TargetPath = String.Format(
                                @"{0}\{1}",
                                tgtFolder,
                                Path.GetFileName(pdbPath)
                                )
                        }
                            );
                    }
                }
            }
        }