Save() public method

public Save ( Stream stream ) : void
stream Stream
return void
コード例 #1
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();
        }
コード例 #2
0
ファイル: NuPackage.cs プロジェクト: alexis-y/NuBuild
        /// <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);
        }
コード例 #3
0
        /// <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;
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: ledgarl/Samples
        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();
        }
コード例 #5
0
        public virtual void CreateNugetPackage([NotNull] string tempDirectory, [NotNull] string fileName, [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);
                }
            }
        }
コード例 #6
0
 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);
 }
コード例 #7
0
ファイル: NuPackage.cs プロジェクト: lmagyar/NuBuild
        /// <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);
        }
コード例 #8
0
ファイル: PackageHelper.cs プロジェクト: jacksonh/nuget
        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
                }
            }
        }
コード例 #9
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);
            }
        }
コード例 #10
0
 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);
 }
コード例 #11
0
        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);
        }
コード例 #12
0
        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);
                }
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: Tauron1990/Radio-Streamer
        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();
        }
コード例 #14
0
        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);
            }
        }
コード例 #15
0
        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;
        }
コード例 #16
0
        /// <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;
        }
コード例 #17
0
        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);
        }
コード例 #18
0
        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);
            }
        }
コード例 #19
0
ファイル: PackageFactory.cs プロジェクト: run00/TeamCity
        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);
        }
コード例 #20
0
ファイル: NugetPack.cs プロジェクト: secretGeek/choco
        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);
        }
コード例 #21
0
        public IPackage GetPackage()
        {
            var args = Environment.GetCommandLineArgs();
            var spec = GetArgValue(args, "--plugin-nuspec");
            var path = GetArgValue(args, "--plugin-path");

            if (string.IsNullOrEmpty(spec) || string.IsNullOrEmpty(path))
            {
                _logger.Debug("No development package found.");
                return null;
            }

            var builder = new PackageBuilder(spec, path, new NullProvider(), false);
            var outputPath = Path.GetTempFileName();

            _logger.Information("Building development package at {Path}", outputPath);

            using (var stream = File.Create(outputPath))
            {
                builder.Save(stream);
            }

            return new OptimizedZipPackage(outputPath);
        }
コード例 #22
0
        private IPackage AddPackage(IPackageManager manager, string id, string version, string payloadAssemblyFilePath, params IPackage[] dependencies)
        {
            PackageBuilder builder = new PackageBuilder();

            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "dummy author 1,dummy author 2",
                Owners = "dummy owner 1,dummy owner 2",
                Title = "dummy title",
                Version = new SemanticVersion(version).ToString(),
                Id = id,
                Description = "dummy description",
                LicenseUrl = "http://my.license/readme.txt",
                ProjectUrl = "http://dummyurl/"
            };

            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 = payloadAssemblyFilePath;
            file.TargetPath = "analyzers/" + Path.GetFileName(payloadAssemblyFilePath);
            builder.Files.Add(file);

            using (MemoryStream stream = new MemoryStream())
            {
                builder.Save(stream);
                stream.Position = 0;

                ZipPackage pkg = new ZipPackage(stream);
                manager.InstallPackage(pkg, true, true);

                return pkg;
            }
        }
コード例 #23
0
ファイル: BuildManager.cs プロジェクト: leloulight/dnx
        private bool GeneratePackage(bool success, List<DiagnosticMessage> allDiagnostics, PackageBuilder packageBuilder, PackageBuilder symbolPackageBuilder, string nupkg, string symbolsNupkg)
        {
            var packDiagnostics = new List<DiagnosticMessage>();
            foreach (var sharedFile in _currentProject.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile));
                packageBuilder.Files.Add(file);
            }

            var root = _currentProject.ProjectDirectory;

            if (_currentProject.Files.PackInclude != null && _currentProject.Files.PackInclude.Any())
            {
                AddPackageFiles(_currentProject.ProjectDirectory, _currentProject.Files.PackInclude, packageBuilder, packDiagnostics);
            }
            success &= !packDiagnostics.HasErrors();
            allDiagnostics.AddRange(packDiagnostics);

            foreach (var path in _currentProject.Files.SourceFiles)
            {
                var srcFile = new PhysicalPackageFile();
                srcFile.SourcePath = path;
                srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path));
                symbolPackageBuilder.Files.Add(srcFile);
            }

            // Write the packages as long as we're still in a success state.
            if (success)
            {
                using (var fs = File.Create(nupkg))
                {
                    packageBuilder.Save(fs);
                    _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(nupkg));
                }

                if (symbolPackageBuilder.Files.Any())
                {
                    using (var fs = File.Create(symbolsNupkg))
                    {
                        symbolPackageBuilder.Save(fs);
                        _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(symbolsNupkg));
                    }
                }
            }

            WriteDiagnostics(packDiagnostics);
            return success;
        }
コード例 #24
0
            private Stream CreateTestPackageStream(Package commandLinePackage)
            {
                var packageStream = new MemoryStream();
                var builder = new PackageBuilder
                {
                    Id = commandLinePackage.PackageRegistration.Id,
                    Version = SemanticVersion.Parse(commandLinePackage.Version),
                    Authors = 
                    {
                        "dummyAuthor",
                    },
                    Description = commandLinePackage.Description ?? "dummyDesription",
                };

                // Make the package buildable by adding a dependency
                if (builder.Files.Count == 0 && !builder.DependencySets.Any(s => s.Dependencies.Any()))
                {
                    builder.DependencySets.Add(new PackageDependencySet(null, new[] { new NuGet.PackageDependency("dummy") }));
                }

                builder.Save(packageStream);
                return packageStream;
            }
コード例 #25
0
        public static Stream CreateSimplePackageStream(string id, string version = "1.0")
        {
            var packageBuilder = new PackageBuilder
            {
                Id = id,
                Version = SemanticVersion.Parse(version),
                Description = "Test description",
            };

            var dependencySet = new PackageDependencySet(VersionUtility.DefaultTargetFramework,
                new PackageDependency[] {
                    new PackageDependency("Foo")
                });
            packageBuilder.DependencySets.Add(dependencySet);
            packageBuilder.Authors.Add("foo");

            var memoryStream = new MemoryStream();
            packageBuilder.Save(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            return memoryStream;
        }
コード例 #26
0
        // If content is null, "file1.txt" is used added as a content file.
        public static IPackage CreatePackage(string id,
                                              string version,
                                              IEnumerable<string> content,
                                              IEnumerable<IPackageAssemblyReference> assemblyReferences,
                                              IEnumerable<string> tools,
                                              IEnumerable<PackageDependencySet> dependencySets,
                                              int downloadCount,
                                              string description,
                                              string summary,
                                              bool listed,
                                              string tags,
                                              string language,
                                              IEnumerable<IPackageAssemblyReference> satelliteAssemblies,
                                              string minClientVersion = null,
                                              bool createRealStream = true)
        {
            content = content ?? new[] { "file1.txt" };
            assemblyReferences = assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>();
            satelliteAssemblies = satelliteAssemblies ?? Enumerable.Empty<IPackageAssemblyReference>();
            dependencySets = dependencySets ?? Enumerable.Empty<PackageDependencySet>();
            tools = tools ?? Enumerable.Empty<string>();
            description = description ?? "Mock package " + id;

            var allFiles = new List<IPackageFile>();
            allFiles.AddRange(CreateFiles(content, "content"));
            allFiles.AddRange(CreateFiles(tools, "tools"));
            allFiles.AddRange(assemblyReferences);
            allFiles.AddRange(satelliteAssemblies);

            var mockPackage = new Mock<IPackage>(MockBehavior.Strict) { CallBase = true };
            mockPackage.Setup(m => m.IsAbsoluteLatestVersion).Returns(true);
            mockPackage.Setup(m => m.IsLatestVersion).Returns(String.IsNullOrEmpty(SemanticVersion.Parse(version).SpecialVersion));
            mockPackage.Setup(m => m.Id).Returns(id);
            mockPackage.Setup(m => m.Listed).Returns(true);
            mockPackage.Setup(m => m.Version).Returns(new SemanticVersion(version));
            mockPackage.Setup(m => m.GetFiles()).Returns(allFiles);
            mockPackage.Setup(m => m.AssemblyReferences).Returns(assemblyReferences);
            mockPackage.Setup(m => m.DependencySets).Returns(dependencySets);
            mockPackage.Setup(m => m.Description).Returns(description);
            mockPackage.Setup(m => m.Language).Returns("en-US");
            mockPackage.Setup(m => m.Authors).Returns(new[] { "Tester" });
            mockPackage.Setup(m => m.LicenseUrl).Returns(new Uri("ftp://test/somelicense.txts"));
            mockPackage.Setup(m => m.Summary).Returns(summary);
            mockPackage.Setup(m => m.FrameworkAssemblies).Returns(Enumerable.Empty<FrameworkAssemblyReference>());
            mockPackage.Setup(m => m.Tags).Returns(tags);
            mockPackage.Setup(m => m.Title).Returns(String.Empty);
            mockPackage.Setup(m => m.DownloadCount).Returns(downloadCount);
            mockPackage.Setup(m => m.RequireLicenseAcceptance).Returns(false);
            mockPackage.Setup(m => m.DevelopmentDependency).Returns(false);
            mockPackage.Setup(m => m.Listed).Returns(listed);
            mockPackage.Setup(m => m.Language).Returns(language);
            mockPackage.Setup(m => m.IconUrl).Returns((Uri)null);
            mockPackage.Setup(m => m.ProjectUrl).Returns((Uri)null);
            mockPackage.Setup(m => m.ReleaseNotes).Returns("");
            mockPackage.Setup(m => m.Owners).Returns(new string[0]);
            mockPackage.Setup(m => m.Copyright).Returns("");
            mockPackage.Setup(m => m.MinClientVersion).Returns(minClientVersion == null ? new Version() : Version.Parse(minClientVersion));
            mockPackage.Setup(m => m.PackageAssemblyReferences).Returns(new PackageReferenceSet[0]);
            if (!listed)
            {
                mockPackage.Setup(m => m.Published).Returns(Constants.Unpublished);
            }
            var targetFramework = allFiles.Select(f => f.TargetFramework).Where(f => f != null);
            mockPackage.Setup(m => m.GetSupportedFrameworks()).Returns(targetFramework);

            // Create the package's stream
            if (createRealStream)
            {
                PackageBuilder builder = new PackageBuilder();
                builder.Id = id;
                builder.Version = new SemanticVersion(version);
                builder.Description = description;
                builder.Authors.Add("Tester");

                foreach (var f in allFiles)
                {
                    builder.Files.Add(f);
                }
                var packageStream = new MemoryStream();
                builder.Save(packageStream);
                packageStream.Seek(0, SeekOrigin.Begin);
                mockPackage.Setup(m => m.GetStream()).Returns(packageStream);
            }
            else
            {
                mockPackage.Setup(m => m.GetStream()).Returns(new MemoryStream());
            }

            return mockPackage.Object;
        }
コード例 #27
0
ファイル: NuPackage.cs プロジェクト: keeger/NuBuild
        /// <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);

             //auto generate package dependencies from packages.config file.
             if (AutoGenerateDependencies && !builder.DependencySets.Any())
            AddDependencies(builder);

             // write the configured package out to disk
             var pkgPath = specItem.GetMetadata("NuPackagePath");
             using (var pkgFile = File.Create(pkgPath))
            builder.Save(pkgFile);
        }
コード例 #28
0
        private static Stream CreateCommandLinePackage()
        {
            var packageBuilder = new PackageBuilder
                                 {
                                     Id = "NuGet.CommandLine",
                                     Version = new SemanticVersion("2.0.0"),
                                     Description = "Some desc"
                                 };
            packageBuilder.Authors.Add("test");
            var exeFile = CreateExePackageFile();
            packageBuilder.Files.Add(exeFile);

            var memoryStream = new MemoryStream();
            packageBuilder.Save(memoryStream);
            memoryStream.Seek(0, SeekOrigin.Begin);

            return memoryStream;
        }
コード例 #29
0
ファイル: ProjectManager.cs プロジェクト: Gidra/KRuntime
        public bool Build(string defaultTargetFramework = "net45")
        {
            defaultTargetFramework = Environment.GetEnvironmentVariable("TARGET_FRAMEWORK") ?? defaultTargetFramework;

            KProject project;
            if (!KProject.TryGetProject(_projectDir, out project))
            {
                Trace.TraceInformation("Unable to locate {0}.'", KProject.ProjectFileName);
                return false;
            }

            var sw = Stopwatch.StartNew();

            string outputPath = Path.Combine(_projectDir, "bin");
            string nupkg = GetPackagePath(project, outputPath);

            var configurations = new HashSet<FrameworkName>(
                project.GetTargetFrameworkConfigurations()
                       .Select(c => c.FrameworkName));

            if (configurations.Count == 0)
            {
                configurations.Add(VersionUtility.ParseFrameworkName(defaultTargetFramework));
            }

            var builder = new PackageBuilder();

            // TODO: Support nuspecs in the project folder
            builder.Authors.AddRange(project.Authors);

            if (builder.Authors.Count == 0)
            {
                // Temporary
                builder.Authors.Add("K");
            }

            builder.Description = project.Description ?? project.Name;
            builder.Id = project.Name;
            builder.Version = project.Version;
            builder.Title = project.Name;

            bool success = true;
            bool createPackage = false;

            // Build all target frameworks a project supports
            foreach (var targetFramework in configurations)
            {
                try
                {
                    var result = Build(project, outputPath, targetFramework, builder);

                    if (result != null && result.Errors != null)
                    {
                        success = false;
                        Trace.TraceError(String.Join(Environment.NewLine, result.Errors));
                    }
                    else
                    {
                        createPackage = true;
                    }
                }
                catch (Exception ex)
                {
                    success = false;
                    Trace.TraceError(ex.ToString());
                }
            }

            if (createPackage)
            {
                using (var fs = File.Create(nupkg))
                {
                    builder.Save(fs);
                }

                Trace.TraceInformation("{0} -> {1}", project.Name, nupkg);
            }

            sw.Stop();

            Trace.TraceInformation("Compile took {0}ms", sw.ElapsedMilliseconds);
            return success;
        }
コード例 #30
0
        /// <summary>
        /// Geneates NuGet packages for Android components.
        /// </summary>
        /// <param name="packageContainers">
        /// The Android components for which to generate NuGet packages.
        /// </param>
        /// <param name="packageTemplate">
        /// The template for the <c>.nuspec</c> file.
        /// </param>
        /// <param name="targetDirectory">
        /// The directory to which to download the packages.
        /// </param>
        /// <param name="overwrite">
        /// If set to <see langword="true"/>, any existing directory will be deleted.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that represents the asynchronous operation.
        /// </returns>
        public static async Task GeneratePackages(IEnumerable<IArchiveContainer> packageContainers, string packageTemplate, DirectoryInfo targetDirectory, bool overwrite)
        {
            Dictionary<string, string> runtimes = new Dictionary<string, string>();
            runtimes.Add("win", "windows");
            runtimes.Add("linux", "linux");
            runtimes.Add("osx", "macosx");

            foreach (var package in packageContainers)
            {
                Console.WriteLine($"Generating package {package.ToString()}");

                // Make sure the package is available locally
                var dir = await DownloadAndExtract(package, targetDirectory, overwrite);

                // Generate the .nuspec file
                foreach (var runtime in runtimes)
                {
                    string packagePath = $"{dir.FullName}-{runtime.Key}.nuspec";

                    string nugetPackage = packageTemplate.Replace("{Version}", package.Revision.ToSematicVersion().ToString() + "-beta004");
                    nugetPackage = nugetPackage.Replace("{Dir}", dir.FullName);
                    nugetPackage = nugetPackage.Replace("{Runtime}", runtime.Key);
                    nugetPackage = nugetPackage.Replace("{OS}", runtime.Value);

                    switch (runtime.Key)
                    {
                        case "win":
                            nugetPackage = nugetPackage.Replace("{LibPrefix}", string.Empty);
                            nugetPackage = nugetPackage.Replace("{LibExtension}", ".dll");
                            break;

                        case "linux":
                            nugetPackage = nugetPackage.Replace("{LibPrefix}", "lib");
                            nugetPackage = nugetPackage.Replace("{LibExtension}", ".so");
                            break;

                        case "osx":
                            nugetPackage = nugetPackage.Replace("{LibPrefix}", "lib");
                            nugetPackage = nugetPackage.Replace("{LibExtension}", ".dylib");
                            break;
                    }

                    File.WriteAllText(packagePath, nugetPackage);

                    PackageBuilder builder = new PackageBuilder(packagePath, null, false);
                    var packageOutputPath = Path.Combine(targetDirectory.FullName, $"{builder.Id}-{builder.Version}.nupkg");

                    using (Stream stream = File.Open(packageOutputPath, FileMode.Create, FileAccess.ReadWrite))
                    {
                        builder.Save(stream);
                    }
                }
            }
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: niemyjski/cli
        private static bool GeneratePackage(Project project, PackageBuilder packageBuilder, string nupkg, List<DiagnosticMessage> packDiagnostics)
        {
            foreach (var sharedFile in project.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = Path.Combine("shared", Path.GetFileName(sharedFile));
                packageBuilder.Files.Add(file);
            }

            var root = project.ProjectDirectory;

            if (project.Files.PackInclude != null && project.Files.PackInclude.Any())
            {
                AddPackageFiles(project, project.Files.PackInclude, packageBuilder, packDiagnostics);
            }

            // Write the packages as long as we're still in a success state.
            if (!packDiagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                Reporter.Verbose.WriteLine($"Adding package files");
                foreach (var file in packageBuilder.Files.OfType<PhysicalPackageFile>())
                {
                    if (file.SourcePath != null && File.Exists(file.SourcePath))
                    {
                        Reporter.Verbose.WriteLine($"Adding {file.Path.Yellow()}");
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(nupkg));

                using (var fs = File.Create(nupkg))
                {
                    packageBuilder.Save(fs);
                    Reporter.Output.WriteLine($"{project.Name} -> {Path.GetFullPath(nupkg)}");
                }

                return true;
            }

            return false;
        }
コード例 #32
0
ファイル: PackageService.cs プロジェクト: pkdevbox/Rock
        /// <summary>
        /// Exports the page.
        /// </summary>
        /// <param name="page">The page.</param>
        /// <param name="isRecursive">if set to <c>true</c> [should export children].</param>
        /// <returns>a <see cref="T:System.IO.MemoryStream"/> of the exported page package.</returns>
        public MemoryStream ExportPage( Page page, bool isRecursive )
        {
            // Create a temp directory to hold package contents in staging area
            string packageId = Guid.NewGuid().ToString();
            var packageDirectory = CreatePackageDirectory( page.InternalName, packageId );
            var webRootPath = HttpContext.Current.Server.MapPath( "~" );

            // Create a manifest for this page export...
            Manifest manifest = new Manifest();
            manifest.Metadata = new ManifestMetadata();
            manifest.Metadata.Authors = "PageExport";
            manifest.Metadata.Version = "0.0";
            manifest.Metadata.Id = packageId;
            manifest.Metadata.Description = ( string.IsNullOrEmpty( page.Description ) ) ? "a page export" : page.Description;
            manifest.Files = new List<ManifestFile>();

            // Generate the JSON from model data and write it to disk, then add it to the manifest
            var json = GetJson( page, isRecursive );
            using ( var file = new StreamWriter( Path.Combine( packageDirectory.FullName, "export.json" ) ) )
            {
                file.Write( json );
            }
            AddToManifest( manifest, packageDirectory.FullName, webRootPath, "export.json", SearchOption.TopDirectoryOnly );

            // * Find out from `page` which Blocks need to be packaged up (recursively if ExportChildren box is checked)
            // * Grab asset folders for each Block's code file uniquely (Scripts, Assets, CSS folders)
            // * Add them to the package manifest
            var blockTypes = new Dictionary<Guid, BlockType>();
            var uniqueDirectories = new Dictionary<string, string>();
            FindUniqueBlockTypesAndDirectories( page, isRecursive, blockTypes, uniqueDirectories );

            foreach ( var blockType in blockTypes.Values )
            {
                var sourcePath = HttpContext.Current.Server.MapPath( blockType.Path );
                var directory = sourcePath.Substring( 0, sourcePath.LastIndexOf( Path.DirectorySeparatorChar ) );
                var fileName = Path.GetFileNameWithoutExtension( sourcePath );
                var pattern = string.Format( "{0}.*", fileName );
                AddToManifest( manifest, directory, webRootPath, pattern, SearchOption.TopDirectoryOnly );
            }

            // Second pass through blocks. Determine which folders (by convention) need to be added
            // to the package manifest.
            foreach ( var dir in uniqueDirectories.Keys )
            {
                var sourcePath = HttpContext.Current.Server.MapPath( dir );
                // Are there any folders present named "CSS", "Scripts" or "Assets"?
                AddToManifest( manifest, Path.Combine( sourcePath, "CSS" ), webRootPath );
                AddToManifest( manifest, Path.Combine( sourcePath, "Scripts" ), webRootPath );
                AddToManifest( manifest, Path.Combine( sourcePath, "Assets" ), webRootPath );
            }

            // Save the manifest as "pageexport.nuspec" in the temp folder
            string basePath = packageDirectory.FullName;
            string manifestPath = Path.Combine( basePath, "pageexport.nuspec" );
            using ( Stream fileStream = File.Create( manifestPath ) )
            {
                manifest.Save( fileStream );
            }

            // Create a NuGet package from the manifest and 'save' it to a memory stream for the consumer...
            // BTW - don't use anything older than nuget 2.1 due to Manifest bug (http://nuget.codeplex.com/workitem/2813)
            // which will cause the PackageBuilder constructor to fail due to <Files> vs <files> being in the manifest.
            PackageBuilder packageBuilder = new PackageBuilder( manifestPath, basePath, NullPropertyProvider.Instance, false );

            var outputStream = new MemoryStream();
            packageBuilder.Save( outputStream );

            // Clean up staging area
            packageDirectory.Delete( recursive: true );
            return outputStream;
        }
コード例 #33
0
ファイル: IPublishingService.cs プロジェクト: ventaur/ripple
        private IPackage createPackage(PackageBuilder builder, string outputPath)
        {
            bool isExistingPackage = File.Exists(outputPath);
            try
            {
                using (Stream stream = File.Create(outputPath))
                {
                    builder.Save(stream);
                }
            }
            catch(Exception exc)
            {
                if (!isExistingPackage && File.Exists(outputPath))
                {
                    File.Delete(outputPath);
                }

                RippleAssert.Fail("Error creating package: " + exc.Message);
            }

            RippleLog.Info("Created nuget at: " + outputPath);
            return new OptimizedZipPackage(outputPath);
        }
コード例 #34
0
ファイル: Program.cs プロジェクト: xero-github/Nuget
        static void CreatePackage(PackageInfo package)
        {
            var packageBuilder = new PackageBuilder()
            {
                Id = package.Id,
                Version = package.Version,
                Description = "Some test package"
            };

            packageBuilder.Authors.Add("Outercurve Foundation");

            string assemblySourcePath = GetAssemblyFullPath(package.FullName);
            packageBuilder.Files.Add(new PhysicalPackageFile()
            {
                SourcePath = assemblySourcePath,
                TargetPath = @"lib\" + Path.GetFileName(assemblySourcePath)
            });

            foreach (DependencyInfo dependency in package.Dependencies)
            {
                packageBuilder.Dependencies.Add(new PackageDependency(dependency.Id, dependency.VersionSpec));
            }

            using (var stream = File.Create(GetPackageFileFullPath(package)))
            {
                packageBuilder.Save(stream);
            }
        }
コード例 #35
0
ファイル: Program.cs プロジェクト: rerbes/OCTGN
        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();
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: xero-github/Nuget
        private static void BuildPackage(string nuspecPath, bool signBinaries)
        {
            var repositoryPath = Path.GetDirectoryName(nuspecPath);
            var basePath = Path.Combine(repositoryPath, "files", Path.GetFileNameWithoutExtension(nuspecPath));
            Directory.CreateDirectory(basePath);
            
            var createdFiles = new List<string>();
            bool deleteDir = true;
            using (var fileStream = File.OpenRead(nuspecPath))
            {
                var manifest = Manifest.ReadFrom(fileStream);
                foreach (var file in manifest.Files)
                {
                    string outputPath = Path.Combine(basePath, file.Source);
                    if (File.Exists(outputPath))
                    {
                        deleteDir = false;
                        // A user created file exists. Continue to next file.
                        continue;
                    }
                    
                    createdFiles.Add(outputPath);
                    string outputDir = Path.GetDirectoryName(outputPath);
                    if (!Directory.Exists(outputDir))
                    {
                        Directory.CreateDirectory(outputDir);
                    }

                    if (file.Source.StartsWith(@"lib" + Path.DirectorySeparatorChar) && !file.Source.EndsWith("resources.dll"))
                    {
                        var name = Path.GetFileNameWithoutExtension(file.Source);
                        CreateAssembly(new PackageInfo(manifest.Metadata.Id + ":" + manifest.Metadata.Version),
                                       outputPath: outputPath);
                    }
                    else
                    {
                        File.WriteAllBytes(outputPath, new byte[0]);
                    }
                }

                var packageBuilder = new PackageBuilder();
                packageBuilder.Populate(manifest.Metadata);
                packageBuilder.PopulateFiles(basePath, manifest.Files);
                
                string nupkgDirectory = Path.GetFullPath("packages");
                Directory.CreateDirectory(nupkgDirectory);
                string nupkgPath = Path.Combine(nupkgDirectory, Path.GetFileNameWithoutExtension(nuspecPath)) + ".nupkg";
                using (var nupkgStream = File.Create(nupkgPath))
                {
                    packageBuilder.Save(nupkgStream);
                }
                
                
            }
            try
            {
                if (deleteDir)
                {
                    Directory.Delete(basePath, recursive: true);
                }
                else 
                {
                    // Delete files that we created.
                    createdFiles.ForEach(File.Delete);
                }
            }
            catch { }
        }