Exemple #1
0
		public static ManifestMetadata ReadMetadata(string path)
		{
			var document = XDocument.Load(path);
			var xElement = document.Root.ElementsNoNamespace("metadata").FirstOrDefault();
			var manifestMetadata = new ManifestMetadata
			{
				DependencySets = new List<ManifestDependencySet>(),
				ReferenceSets = new List<ManifestReferenceSet>(),
				MinClientVersionString = xElement.GetOptionalAttributeValue("minClientVersion")
			};
			var allElements = new HashSet<string>();
			for (var node = xElement.FirstNode; node != null; node = node.NextNode)
			{
				var element = node as XElement;
				if (element != null)
				{
					ReadMetadataValue(manifestMetadata, element, allElements);
				}
			}
			foreach (string str in RequiredElements)
			{
				if (!allElements.Contains(str))
				{
					throw new InvalidDataException(string.Format(CultureInfo.CurrentCulture, "", new object[] { str }));
				}
			}
			return manifestMetadata;
		}
        public string GenerateSingleCustomPackage(PackageDefinition definition,
                                              string binFolderPath,
                                              string outputFolderPath,
                                              string releaseVersion,
                                              IEnumerable<string> singleDLLPackages,
                                              IEnumerable<string> customPackages,
                                              string packageNamePrefix)
        {
            // if no dependencies exist, don't create package from definition
              IEnumerable<ManifestDependency> dependencies = this.GenerateDependencies(definition.Dependencies,
                                                                               binFolderPath,
                                                                               releaseVersion,
                                                                               singleDLLPackages,
                                                                               customPackages,
                                                                               packageNamePrefix);
              if (!dependencies.Any())
              {
            return String.Empty;
              }

              // Create nupkg file
              var packageId = packageNamePrefix + definition.Id + "." + releaseVersion;
              var nugetFilePath = Path.Combine(outputFolderPath, packageId + ".nupkg");

              var metadata = new ManifestMetadata
              {
            Id = packageNamePrefix + definition.Id,
            Title = packageNamePrefix + definition.Id,
            Version = releaseVersion,
            Tags = definition.Tag,
            Authors = "Sitecore",
            Owners = "Sitecore",
            Description = definition.Description,
            RequireLicenseAcceptance = false,
            IconUrl = "http://www.sitecore.net/favicon.ico",
            DependencySets = new List<ManifestDependencySet>
                {
                  new ManifestDependencySet
                  {
                        Dependencies =  dependencies.ToList()
                  }
                }
              };

              var builder = new PackageBuilder();
              builder.Populate(metadata);
              using (FileStream stream = File.Open(nugetFilePath, FileMode.OpenOrCreate))
              {
            builder.Save(stream);
              }

              return nugetFilePath;
        }
 public virtual void ApplyTo(ManifestMetadata metadata)
 {
     metadata.Title = Title;
     metadata.Authors = Authors;
     metadata.Copyright = Copyright;
     metadata.Description = Description;
     metadata.IconUrl = IconUrl;
     metadata.LicenseUrl = LicenseUrl;
     metadata.ProjectUrl = ProjectUrl;
     metadata.ReleaseNotes = ReleaseNotes;
     metadata.RequireLicenseAcceptance = RequiresLicenseAcceptance;
     metadata.Summary = Summary;
     metadata.Tags = Tags;
 }
        public void ProjectFactoryInitializesPropertiesForPreprocessor()
        {
            // arrange
            const string inputSpec = @"<?xml version=""1.0""?>
<package>
    <metadata>
        <id>$id$</id>
        <version>$version$</version>
        <description>$description$</description>
        <authors>$author$</authors>
        <copyright>$copyright$</copyright>
        <licenseUrl>http://nuget.codeplex.com/license</licenseUrl>
        <projectUrl>http://nuget.codeplex.com</projectUrl>
        <tags>nuget</tags>
    </metadata>
</package>";
            var metadata = new ManifestMetadata
            {
                Id = "ProjectFactoryTest",
                Version = "2.0.30619.9000",
                Title = "NuGet.Test",
                Description = "",
                Copyright = "\x00a9 Outercurve. All rights reserved.",
                Authors = "Outercurve Foundation",
            };
            var projectMock = new Mock<Project>();
            var factory = new ProjectFactory(projectMock.Object);

            // act
            var author = factory.InitializeProperties(metadata);
            var actual = Preprocessor.Process(inputSpec.AsStream(), factory, false);

            // assert
            Assert.Equal("Outercurve Foundation", author);
            const string expected = @"<?xml version=""1.0""?>
<package>
    <metadata>
        <id>ProjectFactoryTest</id>
        <version>2.0.30619.9000</version>
        <description></description>
        <authors>Outercurve Foundation</authors>
        <copyright>© Outercurve. All rights reserved.</copyright>
        <licenseUrl>http://nuget.codeplex.com/license</licenseUrl>
        <projectUrl>http://nuget.codeplex.com</projectUrl>
        <tags>nuget</tags>
    </metadata>
</package>";
            Assert.Equal(expected, actual);
        }
        public void GetManifestVersionReturns1IfNoNewPropertiesAreSet()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description"
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(1, version);
        }
        public void GetManifestVersionReturns2IfCopyrightIsSet()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                Copyright = "© Outercurve Foundation"
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(2, version);
        }
        public void GetManifestVersionReturns1IfFrameworkAssemblyHasValues()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                FrameworkAssemblies = new List<ManifestFrameworkAssembly> {  
                    new ManifestFrameworkAssembly { AssemblyName = "System.Data.dll" }
                }
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(1, version);
        }
        public void BuildPackage(string basePath, IList<string> includes, ManifestMetadata metadata, string outFolder, bool overwrite)
        {
            var nugetPkgBuilder = new PackageBuilder();

            nugetPkgBuilder.PopulateFiles(basePath, includes.Select(i => new ManifestFile { Source = i }));
            nugetPkgBuilder.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.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            using (var outStream = fileSystem.OpenFile(output, FileMode.Create))
                nugetPkgBuilder.Save(outStream);
        }
        public void BuildPackage(string basePath, IList<string> includes, ManifestMetadata metadata, string outFolder, bool overwrite)
        {
            var filename = metadata.Id + "." + metadata.Version + ".zip";
            var output = fileSystem.GetFullPath(Path.Combine(outFolder, filename));

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

            log.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            var basePathLength = fileSystem.GetFullPath(basePath).Length;
            using (var stream = fileSystem.OpenFile(output, FileAccess.Write))
            using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
            {
                foreach (var pattern in includes)
                {
                    log.Debug("Adding files from {Path} matching pattern {Pattern}", basePath, pattern);
                    foreach (var file in PathResolver.PerformWildcardSearch(basePath, pattern))
                    {
                        var fullFilePath = fileSystem.GetFullPath(file);
                        if (string.Equals(fullFilePath, output, StringComparison.CurrentCultureIgnoreCase))
                            continue;

                        var relativePath = UseCrossPlatformDirectorySeparator(
                            fullFilePath.Substring(basePathLength).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
                        log.Debug("Adding file: {Path}", relativePath);

                        var entry = archive.CreateEntry(relativePath, CompressionLevel.Optimal);
                        entry.LastWriteTime = new DateTimeOffset(new FileInfo(file).LastWriteTime);

                        using (var entryStream = entry.Open())
                        using (var sourceStream = File.OpenRead(file))
                        {
                            sourceStream.CopyTo(entryStream);
                        }
                    }
                }
            }
        }
        public void GetManifestVersionReturns2IfFrameworkAssemblyAndReferencesAreSet()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                FrameworkAssemblies = new List<ManifestFrameworkAssembly> {  
                    new ManifestFrameworkAssembly { AssemblyName = "System.Data.dll" }
                },
                References = new List<ManifestReference> {
                    new ManifestReference { File = "Foo.dll" }
                }
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(2, version);
        }
Exemple #11
0
        private bool PublishProject()
        {
            try
            {
                string[] scriptFiles = Directory.GetFiles(_projectPath, "*.*", SearchOption.AllDirectories);
                List <ManifestContentFiles> manifestFiles = new List <ManifestContentFiles>();
                foreach (string file in scriptFiles)
                {
                    ManifestContentFiles manifestFile = new ManifestContentFiles
                    {
                        Include = file.Replace(_projectPath, "")
                    };
                    manifestFiles.Add(manifestFile);
                }

                ManifestMetadata metadata = new ManifestMetadata()
                {
                    Id          = _projectName.Replace(" ", "_"),
                    Title       = _projectName,
                    Authors     = txtAuthorName.Text.Trim(),
                    Version     = txtVersion.Text.Trim(),
                    Description = txtDescription.Text.Trim(),
                    RequireLicenseAcceptance = false,
                    IconUrl        = "https://openbots.ai/wp-content/uploads/2020/11/Studio-Icon-256px.png",
                    DependencySets = new List <ManifestDependencySet>()
                    {
                        new ManifestDependencySet()
                        {
                            Dependencies = new List <ManifestDependency>()
                            {
                                new ManifestDependency()
                                {
                                    Id      = "OpenBots.Studio",
                                    Version = new Version(Application.ProductVersion).ToString()
                                },
                            }
                        }
                    },
                    ContentFiles = manifestFiles,
                };

                foreach (var dependency in _projectDependencies)
                {
                    var dep = new ManifestDependency
                    {
                        Id      = dependency.Key,
                        Version = dependency.Value
                    };
                    metadata.DependencySets[0].Dependencies.Add(dep);
                }

                PackageBuilder builder = new PackageBuilder();
                builder.PopulateFiles(_projectPath, new[] { new ManifestFile()
                                                            {
                                                                Source = "**"
                                                            } });
                builder.Populate(metadata);

                if (!Directory.Exists(txtLocation.Text))
                {
                    Directory.CreateDirectory(txtLocation.Text);
                }

                string nugetFilePath = Path.Combine(txtLocation.Text.Trim(), $"{_projectName}_{txtVersion.Text.Trim()}.nupkg");
                using (FileStream stream = File.Open(nugetFilePath, FileMode.OpenOrCreate))
                    builder.Save(stream);

                NotificationMessage = $"'{_projectName}' published successfully";

                if (cbxLocation.Text == "Local Only")
                {
                    return(true);
                }

                try {
                    lblError.Text = $"Publishing {_projectName} to the server...";
                    var client = AuthMethods.GetAuthToken();
                    AutomationMethods.UploadAutomation(client, _projectName, nugetFilePath, _automationEngine);
                }
                catch (Exception)
                {
                    NotificationMessage = $"'{_projectName}' was published locally. To publish to an OpenBots Server please install and connect the OpenBots Agent.";
                }

                return(true);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                return(false);
            }
        }
Exemple #12
0
        public void ReadFromReadsAllMetadataValues()
        {
            var references = new List <PackageReferenceSet>
            {
                new PackageReferenceSet(
                    (NuGetFramework)null,
                    new [] { "Test.dll" }
                    ),
                new PackageReferenceSet(
                    NuGetFramework.Parse("hello"),
                    new [] { "world.winmd" }
                    )
            };

            // Arrange
            var manifestStream = CreateManifest(
                id: "Test-Pack2",
                version: "1.0.0-alpha",
                title: "blah",
                authors: "Outercurve",
                licenseUrl: "http://nuget.org/license", projectUrl: "http://nuget.org/project", iconUrl: "https://nuget.org/icon",
                requiresLicenseAcceptance: true, developmentDependency: true, description: "This is not a description",
                summary: "This is a summary", releaseNotes: "Release notes",
                copyright: "Copyright 2012", language: "fr-FR", tags: "Test Unit",
                dependencies: new[] { new PackageDependency("Test", VersionRange.Parse("1.2.0")) },
                assemblyReference: new[] { new FrameworkAssemblyReference("System.Data", new[] { NuGetFramework.Parse("4.0") }) },
                references: references,
                serviceable: true,
                packageTypes: new[]
            {
                new PackageType("foo", new Version(2, 0, 0)),
                new PackageType("bar", new Version(0, 0))
            },
                minClientVersion: "2.0.1.0"
                );

            var manifestMetadata = new ManifestMetadata
            {
                Id          = "Test-Pack2",
                Version     = NuGetVersion.Parse("1.0.0-alpha"),
                Description = "This is not a description",
                Authors     = new[] { "Outercurve" },
                RequireLicenseAcceptance = true,
                DevelopmentDependency    = true,
                Summary          = "This is a summary",
                ReleaseNotes     = "Release notes",
                Copyright        = "Copyright 2012",
                Language         = "fr-FR",
                Tags             = "Test Unit",
                Serviceable      = true,
                DependencyGroups = new[]
                {
                    new PackageDependencyGroup(
                        NuGetFramework.AnyFramework,
                        new []
                    {
                        new PackageDependency("Test", VersionRange.Parse("1.2.0"))
                    }
                        )
                },
                FrameworkReferences = new[]
                {
                    new FrameworkAssemblyReference("System.Data",
                                                   new [] { NuGetFramework.Parse("4.0") }
                                                   )
                },
                PackageAssemblyReferences = new[]
                {
                    new PackageReferenceSet(
                        (NuGetFramework)null,
                        new [] { "Test.dll" }
                        ),
                    new PackageReferenceSet(
                        NuGetFramework.Parse("hello"),
                        new [] { "world.winmd" }
                        )
                },
                PackageTypes = new[]
                {
                    new PackageType("foo", new Version(2, 0, 0)),
                    new PackageType("bar", new Version(0, 0))
                },
                MinClientVersionString = "2.0.1.0",
            };

            manifestMetadata.SetLicenseUrl("http://nuget.org/license");
            manifestMetadata.SetProjectUrl("http://nuget.org/project");
            manifestMetadata.SetIconUrl("https://nuget.org/icon");

            var expectedManifest = new Manifest(manifestMetadata);

            // Act
            var manifest = Manifest.ReadFrom(manifestStream, validateSchema: true);

            // Assert
            AssertManifest(expectedManifest, manifest);
        }
Exemple #13
0
        private string CreateNugget()
        {
            var csproj             = Path.GetFullPath(Path.Combine(ClientDirectory, "LIC.Malone.Client.Desktop.csproj"));
            var bin                = Path.GetFullPath(Path.Combine(ClientDirectory, "bin", "Release"));
            var buildDirectoryInfo = Directory.CreateDirectory(BuildDirectory);

            Directory.SetCurrentDirectory(buildDirectoryInfo.FullName);

            Clean(buildDirectoryInfo);

            // Rely on standard nuget process to build the project and create a starting package to copy metadata from.
            StartProcess("nuget.exe", string.Format("pack {0} -Build -Prop Configuration=Release", csproj));

            var nupkg   = buildDirectoryInfo.GetFiles("*.nupkg").Single();
            var package = new ZipPackage(nupkg.FullName);

            // Copy all of the metadata *EXCEPT* for dependencies. Kill those.
            var manifest = new ManifestMetadata
            {
                Id             = package.Id,
                Version        = package.Version.ToString(),
                Authors        = string.Join(", ", package.Authors),
                Copyright      = package.Copyright,
                DependencySets = null,
                Description    = package.Description,
                Title          = package.Title,
                IconUrl        = package.IconUrl.ToString(),
                ProjectUrl     = package.ProjectUrl.ToString(),
                LicenseUrl     = package.LicenseUrl.ToString()
            };

            const string target = @"lib\net45";

            // Include dependencies in the package.
            var files = new List <ManifestFile>
            {
                new ManifestFile {
                    Source = "*.dll", Target = target
                },
                new ManifestFile {
                    Source = "Malone.exe", Target = target
                },
                new ManifestFile {
                    Source = "Malone.exe.config", Target = target
                },
            };

            var builder = new PackageBuilder();

            builder.Populate(manifest);
            builder.PopulateFiles(bin, files);

            var nugget = Path.Combine(buildDirectoryInfo.FullName, nupkg.Name);

            using (var stream = File.Open(nugget, FileMode.OpenOrCreate))
            {
                builder.Save(stream);
            }

            return(nugget);
        }
        public static XElement ToXElement(this ManifestMetadata metadata, XNamespace ns, bool generateBackwardsCompatible = true)
        {
            var elem = new XElement(ns + "metadata");

            if (metadata.MinClientVersionString != null)
            {
                elem.SetAttributeValue("minClientVersion", metadata.MinClientVersionString);
            }

            elem.Add(new XElement(ns + "id", metadata.Id));
            AddElementIfNotNull(elem, ns, "version", metadata.Version?.ToFullString());
            AddElementIfNotNull(elem, ns, "title", metadata.Title);
            if (!metadata.PackageTypes.Contains(PackageType.SymbolsPackage))
            {
                AddElementIfNotNull(elem, ns, "authors", metadata.Authors, authors => string.Join(",", authors));
                AddElementIfNotNull(elem, ns, "owners", metadata.Owners, owners => string.Join(",", owners));
            }
            if (metadata.DevelopmentDependency)
            {
                elem.Add(new XElement(ns + "developmentDependency", metadata.DevelopmentDependency));
            }
            if (!metadata.PackageTypes.Contains(PackageType.SymbolsPackage))
            {
                elem.Add(new XElement(ns + "requireLicenseAcceptance", metadata.RequireLicenseAcceptance));
                var licenseUrlToWrite = metadata.LicenseUrl?.ToString();
                if (metadata.LicenseMetadata != null)
                {
                    var licenseElement = GetXElementFromLicenseMetadata(ns, metadata.LicenseMetadata);
                    if (licenseElement != null)
                    {
                        elem.Add(licenseElement);
                    }
                    if (generateBackwardsCompatible)
                    {
                        licenseUrlToWrite = metadata.LicenseMetadata.LicenseUrl.OriginalString;
                    }
                }
                AddElementIfNotNull(elem, ns, "licenseUrl", licenseUrlToWrite);

                AddElementIfNotNull(elem, ns, "icon", metadata.Icon);
            }
            AddElementIfNotNull(elem, ns, "projectUrl", metadata.ProjectUrl);
            AddElementIfNotNull(elem, ns, "iconUrl", metadata.IconUrl);
            AddElementIfNotNull(elem, ns, "description", metadata.Description);
            AddElementIfNotNull(elem, ns, "summary", metadata.Summary);
            AddElementIfNotNull(elem, ns, "releaseNotes", metadata.ReleaseNotes);
            AddElementIfNotNull(elem, ns, "copyright", metadata.Copyright);
            AddElementIfNotNull(elem, ns, "language", metadata.Language);
            AddElementIfNotNull(elem, ns, "tags", metadata.Tags);
            if (metadata.Serviceable)
            {
                elem.Add(new XElement(ns + "serviceable", metadata.Serviceable));
            }

            if (metadata.PackageTypes != null && metadata.PackageTypes.Any())
            {
                elem.Add(GetXElementFromManifestPackageTypes(ns, metadata.PackageTypes));
            }

            if (metadata.Repository != null)
            {
                var repoElement = GetXElementFromManifestRepository(ns, metadata.Repository);
                if (repoElement != null)
                {
                    elem.Add(repoElement);
                }
            }

            elem.Add(GetXElementFromGroupableItemSets(
                         ns,
                         metadata.DependencyGroups,
                         set => set.TargetFramework.IsSpecificFramework ||
                         set.Packages.Any(dependency => dependency.Exclude.Count > 0 || dependency.Include.Count > 0),
                         set => set.TargetFramework.IsSpecificFramework ? set.TargetFramework.GetFrameworkString() : null,
                         set => set.Packages,
                         GetXElementFromPackageDependency,
                         Dependencies,
                         TargetFramework));

            elem.Add(GetXElementFromGroupableItemSets(
                         ns,
                         metadata.PackageAssemblyReferences,
                         set => set.TargetFramework?.IsSpecificFramework == true,
                         set => set.TargetFramework?.GetFrameworkString(),
                         set => set.References,
                         GetXElementFromPackageReference,
                         References,
                         TargetFramework));

            elem.Add(GetXElementFromGroupableItemSets(
                         ns: ns,
                         objectSets: metadata.FrameworkReferenceGroups,
                         isGroupable: set => true, // the TFM is required for framework references
                         getGroupIdentifer: set => set.TargetFramework.GetFrameworkString(),
                         getItems: set => set.FrameworkReferences,
                         getXElementFromItem: GetXElementFromFrameworkReference,
                         parentName: NuspecUtility.FrameworkReferences,
                         identifierAttributeName: TargetFramework));

            elem.Add(GetXElementFromFrameworkAssemblies(ns, metadata.FrameworkReferences));
            elem.Add(GetXElementFromManifestContentFiles(ns, metadata.ContentFiles));

            return(elem);
        }
 public static XElement ToXElement(this ManifestMetadata metadata, XNamespace ns)
 {
     return(ToXElement(metadata, ns, generateBackwardsCompatible: true));
 }
Exemple #16
0
        private bool PublishProject()
        {
            try
            {
                string[] scriptFiles = Directory.GetFiles(_projectPath, "*.json", SearchOption.AllDirectories);
                List <ManifestContentFiles> manifestFiles = new List <ManifestContentFiles>();
                foreach (string file in scriptFiles)
                {
                    ManifestContentFiles manifestFile = new ManifestContentFiles
                    {
                        Include = file.Replace(_projectPath, "")
                    };
                    manifestFiles.Add(manifestFile);
                }

                ManifestMetadata metadata = new ManifestMetadata()
                {
                    Id          = _projectId.ToString(),
                    Title       = _projectName,
                    Authors     = txtAuthorName.Text.Trim(),
                    Version     = txtVersion.Text.Trim(),
                    Description = txtDescription.Text.Trim(),
                    RequireLicenseAcceptance = false,
                    DependencySets           = new List <ManifestDependencySet>()
                    {
                        new ManifestDependencySet()
                        {
                            Dependencies = new List <ManifestDependency>()
                            {
                                new ManifestDependency()
                                {
                                    Id      = "OpenBots.Studio",
                                    Version = new Version(Application.ProductVersion).ToString()
                                }
                            }
                        }
                    },
                    ContentFiles = manifestFiles,
                };

                PackageBuilder builder = new PackageBuilder();
                builder.PopulateFiles(_projectPath, new[] { new ManifestFile()
                                                            {
                                                                Source = "**"
                                                            } });
                builder.Populate(metadata);

                if (!Directory.Exists(txtLocation.Text))
                {
                    Directory.CreateDirectory(txtLocation.Text);
                }

                string nugetFilePath = Path.Combine(txtLocation.Text.Trim(), $"{_projectName}_{txtVersion.Text.Trim()}.nupkg");
                using (FileStream stream = File.Open(nugetFilePath, FileMode.OpenOrCreate))
                    builder.Save(stream);

                NotificationMessage = $"'{_projectName}' published successfully";

                try {
                    lblError.Text = $"Publishing {_projectName} to the server...";
                    var client = AuthMethods.GetAuthToken();
                    ProcessMethods.UploadProcess(client, _projectName, nugetFilePath);
                }
                catch (Exception)
                {
                    NotificationMessage = $"'{_projectName}' was published locally. To publish to an OpenBots Server please install and connect the OpenBots Agent.";
                }

                return(true);
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                return(false);
            }
        }
        public void GetManifestVersionIgnoresEmptyStrings()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                ReleaseNotes = ""
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(1, version);
        }
Exemple #18
0
        public static void Build(ILogger log, Package package, string outputDirectory = null)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            var meta = new ManifestMetadata();

            PackageStore.ToNugetManifest(package.Meta, meta);

            // Sanity check: Xenko version should be same between NuGet package and Xenko package
            var nugetVersion   = new PackageVersion(XenkoVersion.NuGetVersion).Version;
            var packageVersion = package.Meta.Version.Version;

            if (nugetVersion != packageVersion)
            {
                log.Error($"Package has mismatching version: NuGet package version is {nugetVersion} and Xenko Package version is {packageVersion}");
                return;
            }

            if (nugetVersion.Revision <= 0)
            {
                // If 0, we have special cases with NuGet dropping it in install path, could be dangerous and lead to bugs if not properly tested.
                log.Error($"Package has revision {nugetVersion} but 4th digit needs to be at least 1.");
                return;
            }

            // Override version with NuGet version (4th number is different in Xenko package)
            meta.Version = XenkoVersion.NuGetVersion;

            var builder = new NugetPackageBuilder();

            builder.Populate(meta);

            var currentAssemblyLocation = Assembly.GetExecutingAssembly().Location;
            var mainPlatformDirectory   = Path.GetFileName(Path.GetDirectoryName(currentAssemblyLocation));

            // TODO this is not working
            // We are excluding everything that is in a folder that starts with a dot (ie. .shadow, .vs)
            var files = new List <ManifestFile>()
            {
                NewFile(@"Bin\**\*.exe", "Bin", @"Bin\**\.*\**\*.exe;Bin\**\Tools\**.exe"),
                NewFile(@"Bin\**\*.so", "Bin", @"Bin\**\.*\**\*.so;Bin\Windows\lib\**\*.so"),
                NewFile(@"Bin\**\*.ssdeps", "Bin", @"Bin\**\.*\**\*.ssdeps"),
                NewFile(@"Bin\**\*.a", "Bin", @"Bin\**\.*\**\*.a"),
                NewFile(@"Bin\**\*.md", "Bin", @"Bin\**\.*\**\*.md"),
                NewFile(@"Bin\**\*.html", "Bin", @"Bin\**\.*\**\*.html"),
                NewFile(@"Bin\**\*.config", "Bin", @"Bin\**\.*\**\*.config"),
                NewFile(@"Bin\**\*.dll", "Bin", @"Bin\**\.*\**\*.dll;Bin\Windows\lib\**\*.dll"),
                NewFile(@"Bin\**\*.xml", "Bin", @"Bin\**\.*\**\*.xml"),
                NewFile(@"Bin\**\*.usrdoc", "Bin", @"Bin\**\.*\**\*.usrdoc"),
                NewFile(@"Bin\**\*.winmd", "Bin", @"Bin\**\.*\**\*.winmd"),
                NewFile(@"Bin\**\*.sh", "Bin", @"Bin\**\.*\**\*.sh"),
                NewFile(@"Bin\**\*.json", "Bin", @"Bin\**\.*\**\*.json"),
                NewFile(@"deps\AssemblyProcessor\*.exe", @"deps/AssemblyProcessor"),
                NewFile(@"deps\AssemblyProcessor\*.dll", @"deps/AssemblyProcessor"),
                NewFile($@"Bin\{mainPlatformDirectory}\ios-tcprelay\*.py", $@"Bin\{mainPlatformDirectory}\ios-tcprelay"),
                NewFile(@"Targets\*.targets", "Targets"),
                NewFile(@"Targets\*.props", "Targets"),
                NewFile($@"Bin\{mainPlatformDirectory}\Xenko.Core.*.pdb", $@"Bin\{mainPlatformDirectory}", @"Bin\**\Xenko.Importer*.pdb;Bin\**\Xenko.Assimp.Translation.pdb"),
                NewFile(@"build\Xenko.targets", @"build"),
                NewFile(@"build\Xenko.props", @"build"),
                NewFile(@"tools\**\*.exe", "tools"),
                NewFile(@"tools\**\*.dll", "tools"),
                NewFile(@"LICENSE.md", @""),
                NewFile(@"THIRD PARTY.md", @""),
            };

            // Handle Assets
            var rootDir = package.RootDirectory;

            var newPackage = new Package {
                Meta = AssetCloner.Clone(package.Meta)
            };

            newPackage.Meta.Version = new PackageVersion(meta.Version);

            foreach (var profile in package.Profiles)
            {
                var target = "Assets/" + profile.Name;
                foreach (var assetFolder in profile.AssetFolders)
                {
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xk*", target));
                }
                foreach (var resourceFolder in profile.ResourceFolders)
                {
                    files.Add(NewFile(resourceFolder.MakeRelative(rootDir) + "/**/*.*", "Resources"));
                }

                var targetProfile = new PackageProfile(profile.Name);
                if (profile.AssetFolders.Count > 0)
                {
                    targetProfile.AssetFolders.Add(new AssetFolder(target));
                }
                if (profile.ResourceFolders.Count > 0)
                {
                    targetProfile.ResourceFolders.Add("Resources");
                }

                newPackage.Profiles.Add(targetProfile);
            }

            //Handle RootAssets
            foreach (var rootAsset in package.RootAssets)
            {
                newPackage.RootAssets.Add(rootAsset);
            }

            // Handle templates
            var targetFolder = new TemplateFolder("Templates");

            foreach (var templateFolder in package.TemplateFolders)
            {
                var        source = templateFolder.Path.MakeRelative(rootDir) + "/**";
                UDirectory target = targetFolder.Path;
                if (templateFolder.Group != null)
                {
                    target = UPath.Combine(target, templateFolder.Group);
                }

                var excludeFiles = templateFolder.Exclude;
                files.Add(NewFile(source, target, excludeFiles));

                // Add template files
                foreach (var templateFile in templateFolder.Files)
                {
                    var newTemplateFile = templateFile.MakeRelative(templateFolder.Path);
                    if (templateFolder.Group != null)
                    {
                        newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile);
                    }

                    newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile);
                    targetFolder.Files.Add(newTemplateFile);
                }
            }

            // Create temp package for archive
            newPackage.TemplateFolders.Add(targetFolder);
            var newPackageFileName = "temp" + Guid.NewGuid() + ".xkpkg";

            newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName;
            var result = new LoggerResult();

            newPackage.Save(result);
            if (result.HasErrors)
            {
                throw new InvalidOperationException(result.ToText());
                // TODO throw error
            }
            files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension));

            // Add files
            builder.PopulateFiles(package.RootDirectory, files);

            outputDirectory = outputDirectory ?? Environment.CurrentDirectory;

            // Save the nupkg
            var  outputPath        = GetOutputPath(builder, outputDirectory);
            bool isExistingPackage = File.Exists(outputPath);

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

            File.Delete(newPackage.FullPath);
        }
Exemple #19
0
        public static XElement ToXElement(this ManifestMetadata metadata, XNamespace ns)
        {
            var elem = new XElement(ns + "metadata");

            if (metadata.MinClientVersionString != null)
            {
                elem.SetAttributeValue("minClientVersion", metadata.MinClientVersionString);
            }

            elem.Add(new XElement(ns + "id", metadata.Id));
            AddElementIfNotNull(elem, ns, "version", metadata.Version?.ToFullString());
            AddElementIfNotNull(elem, ns, "title", metadata.Title);
            if (!metadata.PackageTypes.Contains(PackageType.SymbolsPackage))
            {
                AddElementIfNotNull(elem, ns, "authors", metadata.Authors, authors => string.Join(",", authors));
                AddElementIfNotNull(elem, ns, "owners", metadata.Owners, owners => string.Join(",", owners));
            }

            elem.Add(new XElement(ns + "requireLicenseAcceptance", metadata.RequireLicenseAcceptance));
            if (metadata.DevelopmentDependency)
            {
                elem.Add(new XElement(ns + "developmentDependency", metadata.DevelopmentDependency));
            }
            AddElementIfNotNull(elem, ns, "licenseUrl", metadata.LicenseUrl);
            AddElementIfNotNull(elem, ns, "projectUrl", metadata.ProjectUrl);
            AddElementIfNotNull(elem, ns, "iconUrl", metadata.IconUrl);
            AddElementIfNotNull(elem, ns, "description", metadata.Description);
            AddElementIfNotNull(elem, ns, "summary", metadata.Summary);
            AddElementIfNotNull(elem, ns, "releaseNotes", metadata.ReleaseNotes);
            AddElementIfNotNull(elem, ns, "copyright", metadata.Copyright);
            AddElementIfNotNull(elem, ns, "language", metadata.Language);
            AddElementIfNotNull(elem, ns, "tags", metadata.Tags);
            if (metadata.Serviceable)
            {
                elem.Add(new XElement(ns + "serviceable", metadata.Serviceable));
            }

            if (metadata.PackageTypes != null && metadata.PackageTypes.Any())
            {
                elem.Add(GetXElementFromManifestPackageTypes(ns, metadata.PackageTypes));
            }

            if (metadata.Repository != null)
            {
                XElement repoElement = GetXElementFromManifestRepository(ns, metadata.Repository);
                if (repoElement != null)
                {
                    elem.Add(repoElement);
                }
            }

            elem.Add(GetXElementFromGroupableItemSets(
                         ns,
                         metadata.DependencyGroups,
                         set => set.TargetFramework.IsSpecificFramework ||
                         set.Packages.Any(dependency => dependency.Exclude.Count > 0 || dependency.Include.Count > 0),
                         set => set.TargetFramework.IsSpecificFramework ? set.TargetFramework.GetFrameworkString() : null,
                         set => set.Packages,
                         GetXElementFromPackageDependency,
                         Dependencies,
                         TargetFramework));

            elem.Add(GetXElementFromGroupableItemSets(
                         ns,
                         metadata.PackageAssemblyReferences,
                         set => set.TargetFramework?.IsSpecificFramework == true,
                         set => set.TargetFramework?.GetFrameworkString(),
                         set => set.References,
                         GetXElementFromPackageReference,
                         References,
                         TargetFramework));

            elem.Add(GetXElementFromFrameworkAssemblies(ns, metadata.FrameworkReferences));
            elem.Add(GetXElementFromManifestContentFiles(ns, metadata.ContentFiles));

            return(elem);
        }
Exemple #20
0
        /// <summary>
        /// Gets the <see cref="ManifestMetadata" /> for a package.
        /// </summary>
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageManifest"/> class.
        /// </summary>
        /// <param name="name">The name or ID of the package.</param>
        /// <param name="version">The semantic version of the package.</param>
        /// <param name="authors">An optional semicolon delimited list of authors of the package.  The default value is &quot;UserA&quot;</param>
        /// <param name="description">An optional description of the package.  The default value is &quot;Description&quot;</param>
        /// <param name="copyright">An optional copyright of the package.</param>
        /// <param name="developmentDependency">An optional value indicating whether or not the package is a development dependency.  The default value is <code>false</code>.</param>
        /// <param name="iconUrl">An optional URL to the icon of the package.</param>
        /// <param name="language">An optional language of the package.</param>
        /// <param name="licenseUrl">An optional URL to the license of the package.</param>
        /// <param name="licenseMetadata">An optional <see cref="LicenseMetadata" /> of the package.</param>
        /// <param name="owners">An optional semicolon delimited list of owners of the package.</param>
        /// <param name="packageTypes">An optional <see cref="IEnumerable{PackageType}" /> containing the package types of the package.</param>
        /// <param name="projectUrl">An optional URL to the project of the package.</param>
        /// <param name="releaseNotes">An optional value specifying release notes of the package.</param>
        /// <param name="repositoryType">An optional value specifying the type of source code repository of the package.</param>
        /// <param name="repositoryUrl">An optional value specifying the URL of the source code repository of the package.</param>
        /// <param name="repositoryBranch">An optional value specifying the branch of the source code repository of the package.</param>
        /// <param name="repositoryCommit">An optional value specifying the commit of the source code repository of the package.</param>
        /// <param name="requireLicenseAcceptance">An optional value indicating whether or not the package requires license acceptance  The default value is <code>false</code>.</param>
        /// <param name="serviceable">An option value indicating whether or not the package is serviceable.  The default value is <code>false</code>.</param>
        /// <param name="summary">An optional summary of the package.</param>
        /// <param name="tags">An optional set of tags of the package.</param>
        /// <param name="title">An optional title of the package.</param>
        /// <returns>The <see cref="ManifestMetadata" /> for the package.</returns>
#else
        /// <summary>
        /// Gets the <see cref="ManifestMetadata" /> for a package.
        /// </summary>
        /// <summary>
        /// Initializes a new instance of the <see cref="PackageManifest"/> class.
        /// </summary>
        /// <param name="name">The name or ID of the package.</param>
        /// <param name="version">The semantic version of the package.</param>
        /// <param name="authors">An optional semicolon delimited list of authors of the package.  The default value is &quot;UserA&quot;</param>
        /// <param name="description">An optional description of the package.  The default value is &quot;Description&quot;</param>
        /// <param name="copyright">An optional copyright of the package.</param>
        /// <param name="developmentDependency">An optional value indicating whether or not the package is a development dependency.  The default value is <code>false</code>.</param>
        /// <param name="icon">An optional path in the package that should be used for the icon of the package.</param>
        /// <param name="iconUrl">An optional URL to the icon of the package.</param>
        /// <param name="language">An optional language of the package.</param>
        /// <param name="licenseUrl">An optional URL to the license of the package.</param>
        /// <param name="licenseMetadata">An optional <see cref="LicenseMetadata" /> of the package.</param>
        /// <param name="owners">An optional semicolon delimited list of owners of the package.</param>
        /// <param name="packageTypes">An optional <see cref="IEnumerable{PackageType}" /> containing the package types of the package.</param>
        /// <param name="projectUrl">An optional URL to the project of the package.</param>
        /// <param name="releaseNotes">An optional value specifying release notes of the package.</param>
        /// <param name="repositoryType">An optional value specifying the type of source code repository of the package.</param>
        /// <param name="repositoryUrl">An optional value specifying the URL of the source code repository of the package.</param>
        /// <param name="repositoryBranch">An optional value specifying the branch of the source code repository of the package.</param>
        /// <param name="repositoryCommit">An optional value specifying the commit of the source code repository of the package.</param>
        /// <param name="requireLicenseAcceptance">An optional value indicating whether or not the package requires license acceptance  The default value is <code>false</code>.</param>
        /// <param name="serviceable">An option value indicating whether or not the package is serviceable.  The default value is <code>false</code>.</param>
        /// <param name="summary">An optional summary of the package.</param>
        /// <param name="tags">An optional set of tags of the package.</param>
        /// <param name="title">An optional title of the package.</param>
        /// <returns>The <see cref="ManifestMetadata" /> for the package.</returns>
#endif
        private static ManifestMetadata GetManifestMetadata(
            string name,
            string version,
            string authors             = null,
            string description         = null,
            string copyright           = null,
            bool developmentDependency = false,
#if !NET46
            string icon = null,
#endif
            string iconUrl    = null,
            string language   = null,
            string licenseUrl = null,
            LicenseMetadata licenseMetadata = null,
            string owners = null,
            IEnumerable <PackageType> packageTypes = null,
            string projectUrl             = null,
            string releaseNotes           = null,
            string repositoryType         = null,
            string repositoryUrl          = null,
            string repositoryBranch       = null,
            string repositoryCommit       = null,
            bool requireLicenseAcceptance = false,
            bool serviceable = false,
            string summary   = null,
            string tags      = null,
            string title     = null)
        {
            ManifestMetadata metadata = new ManifestMetadata
            {
                Authors               = MSBuildStringUtility.Split(authors ?? "UserA"),
                Copyright             = copyright,
                Description           = description ?? "Description",
                DevelopmentDependency = developmentDependency,
#if !NET46
                Icon = icon,
#endif
                Id                       = name,
                Language                 = language,
                LicenseMetadata          = licenseMetadata,
                Owners                   = string.IsNullOrWhiteSpace(owners) ? null : MSBuildStringUtility.Split(owners),
                PackageTypes             = packageTypes ?? new[] { PackageType.Dependency },
                ReleaseNotes             = releaseNotes,
                Repository               = new RepositoryMetadata(repositoryType, repositoryUrl, repositoryBranch, repositoryCommit),
                RequireLicenseAcceptance = requireLicenseAcceptance,
                Serviceable              = serviceable,
                Summary                  = summary,
                Tags                     = tags,
                Title                    = title,
                Version                  = NuGetVersion.Parse(version),
            };

            if (!string.IsNullOrWhiteSpace(iconUrl))
            {
                metadata.SetIconUrl(iconUrl);
            }

            if (!string.IsNullOrWhiteSpace(licenseUrl))
            {
                metadata.SetLicenseUrl(licenseUrl);
            }

            if (!string.IsNullOrWhiteSpace(projectUrl))
            {
                metadata.SetProjectUrl(projectUrl);
            }

            return(metadata);
        }
        private static List <PackageDependencySet> GetOtherDependencySets(ManifestMetadata manifestMetadata)
        {
            var dependencySets = manifestMetadata.DependencyGroups.Where(x => !x.TargetFramework.IsAgnostic);

            return(s_mapper.Map <List <PackageDependencySet> >(dependencySets));
        }
        public void OWnersIsEmptyByDefault()
        {
            var metadata = new ManifestMetadata();

            Assert.Empty(metadata.Owners);
        }
        public void AuthorsIsEmptyByDefault()
        {
            var metadata = new ManifestMetadata();

            Assert.Empty(metadata.Authors);
        }
Exemple #24
0
        public static void Build(ILogger log, Package package, string outputDirectory = null)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            var meta = new ManifestMetadata();

            PackageStore.ToNugetManifest(package.Meta, meta);

            // Sanity check: Xenko version should be same between NuGet package and Xenko package
            var nugetVersion   = new PackageVersion(XenkoVersion.NuGetVersion).Version;
            var packageVersion = package.Meta.Version.Version;

            if (nugetVersion != packageVersion)
            {
                log.Error($"Package has mismatching version: NuGet package version is {nugetVersion} and Xenko Package version is {packageVersion}");
                return;
            }

            if (nugetVersion.Revision <= 0)
            {
                // If 0, we have special cases with NuGet dropping it in install path, could be dangerous and lead to bugs if not properly tested.
                log.Error($"Package has revision {nugetVersion} but 4th digit needs to be at least 1.");
                return;
            }

            // Override version with NuGet version (4th number is different in Xenko package)
            meta.Version = XenkoVersion.NuGetVersion;

            var builder = new NugetPackageBuilder();

            builder.Populate(meta);

            var currentAssemblyLocation = Assembly.GetExecutingAssembly().Location;
            var mainPlatformDirectory   = Path.GetFileName(Path.GetDirectoryName(currentAssemblyLocation));

            // TODO this is not working
            // We are excluding everything that is in a folder that starts with a dot (ie. .shadow, .vs)
            var files = new List <ManifestFile>()
            {
                NewFile(@"Bin\**\*.exe", "Bin", @"Bin\**\.*\**\*.exe;Bin\**\Tools\**.exe"),
                NewFile(@"Bin\**\*.so", "Bin", @"Bin\**\.*\**\*.so;Bin\Windows\lib\**\*.so"),
                NewFile(@"Bin\**\*.ssdeps", "Bin", @"Bin\**\.*\**\*.ssdeps"),
                NewFile(@"Bin\**\*.a", "Bin", @"Bin\**\.*\**\*.a"),
                NewFile(@"Bin\**\*.md", "Bin", @"Bin\**\.*\**\*.md"),
                NewFile(@"Bin\**\*.html", "Bin", @"Bin\**\.*\**\*.html"),
                NewFile(@"Bin\**\*.config", "Bin", @"Bin\**\.*\**\*.config"),
                NewFile(@"Bin\**\*.dll", "Bin", @"Bin\**\.*\**\*.dll;Bin\Windows\lib\**\*.dll"),
                NewFile(@"Bin\**\*.xml", "Bin", @"Bin\**\.*\**\*.xml"),
                NewFile(@"Bin\**\*.usrdoc", "Bin", @"Bin\**\.*\**\*.usrdoc"),
                NewFile(@"Bin\**\*.winmd", "Bin", @"Bin\**\.*\**\*.winmd"),
                NewFile(@"Bin\**\*.sh", "Bin", @"Bin\**\.*\**\*.sh"),
                NewFile(@"Bin\**\*.json", "Bin", @"Bin\**\.*\**\*.json"),
                NewFile(@"deps\AssemblyProcessor\*.exe", @"deps/AssemblyProcessor"),
                NewFile(@"deps\AssemblyProcessor\*.dll", @"deps/AssemblyProcessor"),
                NewFile(@"deps\CoreFX\**\*.*", @"deps\CoreFX"),
                NewFile($@"Bin\{mainPlatformDirectory}\ios-tcprelay\*.py", $@"Bin\{mainPlatformDirectory}\ios-tcprelay"),
                NewFile(@"Targets\*.targets", "Targets"),
                NewFile($@"Bin\{mainPlatformDirectory}\SiliconStudio.*.pdb", $@"Bin\{mainPlatformDirectory}", @"Bin\**\SiliconStudio.Xenko.Importer*.pdb;Bin\**\SiliconStudio.Xenko.Assimp.Translation.pdb"),
            };

            // Handle Assets
            var rootDir = package.RootDirectory;


            var newPackage = new Package {
                Meta = package.Meta
            };

            foreach (var profile in package.Profiles)
            {
                var target = "Assets/" + profile.Name;
                foreach (var assetFolder in profile.AssetFolders)
                {
                    // TODO: handle exclude in asset folders
                    //files.Add(NewFile(source, target, @"**\*.cs;**\*.hlsl;**\*.csproj;**\*.csproj.user;**\obj\**"));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xksl", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfx", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkfnt", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xksheet", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkuilib", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xkgfxcomp", target));
                    files.Add(NewFile(assetFolder.Path.MakeRelative(rootDir) + "/**/*.xktex", target));
                    var resourceFolder = UPath.Combine(assetFolder.Path, new UDirectory("../../Resources"));
                    if (Directory.Exists(resourceFolder.ToWindowsPath()))
                    {
                        files.Add(NewFile(resourceFolder.MakeRelative(rootDir) + "/**/*.*", "Resources"));
                    }
                }
                var targetProfile = new PackageProfile(profile.Name);
                targetProfile.AssetFolders.Add(new AssetFolder(target));
                newPackage.Profiles.Add(targetProfile);
            }

            //Handle RootAssets
            foreach (var rootAsset in package.RootAssets)
            {
                newPackage.RootAssets.Add(rootAsset);
            }

            // Handle templates
            var targetFolder = new TemplateFolder("Templates");

            foreach (var templateFolder in package.TemplateFolders)
            {
                var        source = templateFolder.Path.MakeRelative(rootDir) + "/**";
                UDirectory target = targetFolder.Path;
                if (templateFolder.Group != null)
                {
                    target = UPath.Combine(target, templateFolder.Group);
                }

                var excludeFiles = templateFolder.Exclude;
                files.Add(NewFile(source, target, excludeFiles));

                // Add template files
                foreach (var templateFile in templateFolder.Files)
                {
                    var newTemplateFile = templateFile.MakeRelative(templateFolder.Path);
                    if (templateFolder.Group != null)
                    {
                        newTemplateFile = UPath.Combine(templateFolder.Group, newTemplateFile);
                    }

                    newTemplateFile = UPath.Combine(targetFolder.Path, newTemplateFile);
                    targetFolder.Files.Add(newTemplateFile);
                }
            }

            // Add files
            builder.PopulateFiles(package.RootDirectory, files);
            files.Clear();

            var dataFiles = builder.Files.ToList();

            builder.ClearFiles();

            // Create temp package for archive
            newPackage.TemplateFolders.Add(targetFolder);
            var newPackageFileName = "temp" + Guid.NewGuid() + ".xkpkg";

            newPackage.FullPath = package.RootDirectory + "/" + newPackageFileName;
            var result = new LoggerResult();

            newPackage.Save(result);
            if (result.HasErrors)
            {
                throw new InvalidOperationException(result.ToText());
                // TODO throw error
            }

            // Add the package file
            files.Add(NewFile(newPackageFileName, package.Meta.Name + Package.PackageFileExtension));
            // Add entry point to decompress LZMA
            files.Add(NewFile(@"tools\**\*.exe", "tools"));
            files.Add(NewFile(@"tools\**\*.dll", "tools"));
            // Add an empty .xz file so that it gets added to [Content_Types].xml
            // This file will be removed later
            files.Add(NewFile(@"tools\data_empty.xz", string.Empty));

            // Repopulate with .xkpkg file
            builder.PopulateFiles(package.RootDirectory, files);

            outputDirectory = outputDirectory ?? Environment.CurrentDirectory;

            // Save the nupkg
            var  outputPath        = GetOutputPath(builder, outputDirectory);
            bool isExistingPackage = File.Exists(outputPath);

            if (isExistingPackage)
            {
                File.Delete(outputPath);
            }
            try
            {
                using (Stream stream = File.Create(outputPath))
                {
                    builder.Save(stream);

                    stream.Position = 0;

                    // Add LZMA file as update so that it is stored without compression
                    using (var archive = new ZipArchive(stream, ZipArchiveMode.Update, true))
                    {
                        // Delete data_empty.xz
                        var dataEntry = archive.GetEntry("data_empty.xz");
                        dataEntry.Delete();

                        // Create data.xz (no compression since .xz is already compressed)
                        dataEntry = archive.CreateEntry("data.xz", CompressionLevel.NoCompression);
                        using (var dataStream = dataEntry.Open())
                        {
                            // Generate LZMA
                            using (var indexedArchive = new IndexedArchive())
                            {
                                foreach (var file in dataFiles)
                                {
                                    indexedArchive.AddFile(Path.Combine(package.RootDirectory, file.SourcePath), file.Path);
                                }
                                indexedArchive.Save(dataStream, new ConsoleProgressReport());
                            }
                        }
                    }
                }
            }
            catch
            {
                if (!isExistingPackage && File.Exists(outputPath))
                {
                    File.Delete(outputPath);
                }
                throw;
            }

            File.Delete(newPackage.FullPath);
        }
 public Manifest()
 {
     Metadata = new ManifestMetadata();
 }
Exemple #26
0
		private static void ReadMetadataValue(ManifestMetadata manifestMetadata, XElement element, HashSet<string> allElements)
		{
			if (element.Value != null)
			{
				allElements.Add(element.Name.LocalName);
				string s = element.Value.SafeTrim();
				switch (element.Name.LocalName)
				{
					case "id":
						manifestMetadata.Id = s;
						return;

					case "version":
						manifestMetadata.Version = s;
						return;

					case "authors":
						manifestMetadata.Authors = s;
						return;

					case "owners":
						manifestMetadata.Owners = s;
						return;

					case "licenseUrl":
						manifestMetadata.LicenseUrl = s;
						return;

					case "projectUrl":
						manifestMetadata.ProjectUrl = s;
						return;

					case "iconUrl":
						manifestMetadata.IconUrl = s;
						return;

					case "requireLicenseAcceptance":
						manifestMetadata.RequireLicenseAcceptance = XmlConvert.ToBoolean(s);
						return;

					case "developmentDependency":
						manifestMetadata.DevelopmentDependency = XmlConvert.ToBoolean(s);
						return;

					case "description":
						manifestMetadata.Description = s;
						return;

					case "summary":
						manifestMetadata.Summary = s;
						return;

					case "releaseNotes":
						manifestMetadata.ReleaseNotes = s;
						return;

					case "copyright":
						manifestMetadata.Copyright = s;
						return;

					case "language":
						manifestMetadata.Language = s;
						return;

					case "title":
						manifestMetadata.Title = s;
						return;

					case "tags":
						manifestMetadata.Tags = s;
						return;

					case "dependencies":
						//manifestMetadata.DependencySets = ReadDependencySets(element);
						return;

					case "frameworkAssemblies":
						//manifestMetadata.FrameworkAssemblies = ReadFrameworkAssemblies(element);
						return;

					case "references":
						//manifestMetadata.ReferenceSets = ReadReferenceSets(element);
						return;
				}
			}
		}
Exemple #27
0
        public Task Execute(string[] commandLineArguments)
        {
            return Task.Run(() =>
            {
                optionGroups.Parse(commandLineArguments);

                if (string.IsNullOrWhiteSpace(id))
                    throw new CommandException("An ID is required");

                if (includes.All(string.IsNullOrWhiteSpace))
                    includes.Add("**");

                if (string.IsNullOrWhiteSpace(basePath))
                    basePath = Path.GetFullPath(Directory.GetCurrentDirectory());

                if (string.IsNullOrWhiteSpace(outFolder))
                    outFolder = Path.GetFullPath(Directory.GetCurrentDirectory());

                if (version == null)
                {
                    var now = DateTime.Now;
                    version = SemanticVersion.Parse($"{now.Year}.{now.Month}.{now.Day}.{now.Hour*10000 + now.Minute*100 + now.Second}");
                }

                if (authors.All(string.IsNullOrWhiteSpace))
                    authors.Add(Environment.GetEnvironmentVariable("USERNAME") + "@" + Environment.GetEnvironmentVariable("USERDOMAIN"));

                if (string.IsNullOrWhiteSpace(description))
                    description = "A deployment package created from files on disk.";

                string allReleaseNotes = null;
                if (!string.IsNullOrWhiteSpace(releaseNotesFile))
                {
                    if (!File.Exists(releaseNotesFile))
                        log.Warning("The release notes file '{Path:l}' could not be found", releaseNotesFile);
                    else
                        allReleaseNotes = fileSystem.ReadFile(releaseNotesFile);
                }

                if (!string.IsNullOrWhiteSpace(releaseNotes))
                {
                    if (allReleaseNotes != null)
                        allReleaseNotes += Environment.NewLine + releaseNotes;
                    else
                        allReleaseNotes = releaseNotes;
                }

                if (string.IsNullOrWhiteSpace(version.OriginalString))
                {
                    throw new Exception("Somehow we created a SemanticVersion without the OriginalString value being preserved. We want to use the OriginalString so we can preserve the version as intended by the caller.");
                }

                var metadata = new ManifestMetadata
                {
                    Id = id,
                    Authors = authors,
                    Description = description,
                    Version = NuGetVersion.Parse(version.OriginalString)
                };

                if (!string.IsNullOrWhiteSpace(allReleaseNotes))
                    metadata.ReleaseNotes = allReleaseNotes;

                if (!string.IsNullOrWhiteSpace(title))
                    metadata.Title = title;

                log.Information("Packing {PackageId:l} version {Version}...", id, version);

                packageBuilder.BuildPackage(basePath, includes, metadata, outFolder, overwrite);

                log.Information("Done.");
            });
        }
        public void GetManifestVersionConsidersEmptyLists()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                FrameworkAssemblies = new List<ManifestFrameworkAssembly>
                {
                },
                References = new List<ManifestReference>
                {
                }
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(2, version);
        }
        public void GetManifestVersionReturns2IfReleaseNotesIsPresent()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0",
                Authors = "A, B",
                Description = "Description",
                ReleaseNotes = "Notes.txt"
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(2, version);
        }
Exemple #30
0
        public void Execute(string[] commandLineArguments)
        {
            options.Parse(commandLineArguments);

            if (string.IsNullOrWhiteSpace(id))
            {
                throw new CommandException("An ID is required");
            }

            if (includes.All(string.IsNullOrWhiteSpace))
            {
                includes.Add("**");
            }

            if (string.IsNullOrWhiteSpace(basePath))
            {
                basePath = Path.GetFullPath(Environment.CurrentDirectory);
            }

            if (string.IsNullOrWhiteSpace(outFolder))
            {
                outFolder = Path.GetFullPath(Environment.CurrentDirectory);
            }

            if (version == null)
            {
                var now = DateTime.Now;
                version = new SemanticVersion(now.Year, now.Month, now.Day, now.Hour * 10000 + now.Minute * 100 + now.Second);
            }
            else
            {
                // Make sure SpecialVersion has 20 characters maximum (Limit imposed by NuGet)
                // https://nuget.codeplex.com/workitem/3426

                const int nugetSpecialVersionMaxLength = 20;
                if (!string.IsNullOrWhiteSpace(version.SpecialVersion) && version.SpecialVersion.Length > nugetSpecialVersionMaxLength)
                {
                    log.WarnFormat("SpecialVersion '{0}' will be truncated to {1} characters (NuGet limit)",
                                   version.SpecialVersion, nugetSpecialVersionMaxLength);

                    var specialVersion = version.SpecialVersion;
                    specialVersion = specialVersion.Substring(0, Math.Min(nugetSpecialVersionMaxLength, specialVersion.Length));

                    version = new SemanticVersion(version.Version, specialVersion);
                }
            }

            if (authors.All(string.IsNullOrWhiteSpace))
            {
                authors.Add(Environment.UserName + "@" + Environment.UserDomainName);
            }

            if (string.IsNullOrWhiteSpace(description))
            {
                description = "A deployment package created from files on disk.";
            }

            string allReleaseNotes = null;

            if (!string.IsNullOrWhiteSpace(releaseNotesFile))
            {
                if (!File.Exists(releaseNotesFile))
                {
                    log.WarnFormat("The release notes file '{0}' could not be found", releaseNotesFile);
                }
                else
                {
                    allReleaseNotes = fileSystem.ReadFile(releaseNotesFile);
                }
            }

            if (!string.IsNullOrWhiteSpace(releaseNotes))
            {
                if (allReleaseNotes != null)
                {
                    allReleaseNotes += Environment.NewLine + releaseNotes;
                }
                else
                {
                    allReleaseNotes = releaseNotes;
                }
            }

            var metadata = new ManifestMetadata
            {
                Id          = id,
                Authors     = string.Join(", ", authors),
                Description = description,
                Version     = version.ToString(),
            };

            if (!string.IsNullOrWhiteSpace(allReleaseNotes))
            {
                metadata.ReleaseNotes = allReleaseNotes;
            }

            if (!string.IsNullOrWhiteSpace(title))
            {
                metadata.Title = title;
            }

            log.InfoFormat("Packing {0} version {1}...", id, version);

            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);

            log.InfoFormat("Done.");
        }
        public void GetManifestVersionReturns3IfUsingSemanticVersioning()
        {
            // Arrange
            var metadata = new ManifestMetadata
            {
                Id = "Foo",
                Version = "1.0.0-alpha",
                Authors = "A, B",
                Description = "Description"
            };

            // Act
            var version = ManifestVersionUtility.GetManifestVersion(metadata);

            // Assert
            Assert.Equal(3, version);
        }
        public Task Execute(string[] commandLineArguments)
        {
            return(Task.Run(() =>
            {
                Options.Parse(commandLineArguments);

                if (printHelp)
                {
                    this.GetHelp(Console.Out, commandLineArguments);
                    return;
                }

                commandOutputProvider.PrintMessages = this.OutputFormat == OutputFormat.Default || this.verbose;

                if (string.IsNullOrWhiteSpace(id))
                {
                    throw new CommandException("An ID is required");
                }

                if (includes.All(string.IsNullOrWhiteSpace))
                {
                    includes.Add("**");
                }

                if (string.IsNullOrWhiteSpace(basePath))
                {
                    basePath = Path.GetFullPath(Directory.GetCurrentDirectory());
                }

                if (string.IsNullOrWhiteSpace(outFolder))
                {
                    outFolder = Path.GetFullPath(Directory.GetCurrentDirectory());
                }

                if (version == null)
                {
                    var now = DateTime.Now;
                    version = SemanticVersion.Parse($"{now.Year}.{now.Month}.{now.Day}.{now.Hour*10000 + now.Minute*100 + now.Second}");
                }

                if (authors.All(string.IsNullOrWhiteSpace))
                {
                    authors.Add(System.Environment.GetEnvironmentVariable("USERNAME") + "@" + System.Environment.GetEnvironmentVariable("USERDOMAIN"));
                }

                if (string.IsNullOrWhiteSpace(description))
                {
                    description = "A deployment package created from files on disk.";
                }

                allReleaseNotes = null;
                if (!string.IsNullOrWhiteSpace(releaseNotesFile))
                {
                    if (!File.Exists(releaseNotesFile))
                    {
                        commandOutputProvider.Warning("The release notes file '{Path:l}' could not be found", releaseNotesFile);
                    }
                    else
                    {
                        allReleaseNotes = fileSystem.ReadFile(releaseNotesFile);
                    }
                }

                if (!string.IsNullOrWhiteSpace(releaseNotes))
                {
                    if (allReleaseNotes != null)
                    {
                        allReleaseNotes += System.Environment.NewLine + releaseNotes;
                    }
                    else
                    {
                        allReleaseNotes = releaseNotes;
                    }
                }

                if (string.IsNullOrWhiteSpace(version.OriginalString))
                {
                    throw new Exception("Somehow we created a SemanticVersion without the OriginalString value being preserved. We want to use the OriginalString so we can preserve the version as intended by the caller.");
                }

                var metadata = new ManifestMetadata
                {
                    Id = id,
                    Authors = authors,
                    Description = description,
                    Version = NuGetVersion.Parse(version.OriginalString)
                };

                if (!string.IsNullOrWhiteSpace(allReleaseNotes))
                {
                    metadata.ReleaseNotes = allReleaseNotes;
                }

                if (!string.IsNullOrWhiteSpace(title))
                {
                    metadata.Title = title;
                }

                packageBuilder.SetCompression(compressionLevel);
                if (verbose)
                {
                    commandOutputProvider.Information("Verbose logging");
                }
                commandOutputProvider.Information("Packing {id:l} version {Version}...", id, version);

                packageBuilder.BuildPackage(basePath, includes, metadata, outFolder, overwrite, verbose);

                if (OutputFormat == OutputFormat.Json)
                {
                    PrintJsonOutput();
                }
                else
                {
                    PrintDefaultOutput();
                }
            }));
        }
        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
            {
                SourcePath = contentFilePath,
                TargetPath = Path.GetFileName(contentFilePath)
            };

            builder.Files.Add(file);

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

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

            // Retrieve and return the newly-created package
            IPackage package = FakeRemoteRepo.FindPackage(packageId, new SemanticVersion(packageVersion));

            package.Should().NotBeNull("Test setup error: failed to create and retrieve a test package");

            return(package);
        }
Exemple #34
0
        internal static async Task <OperationResult> GenerateNugetPackage(
            string resultFile,
            string packageId,
            string version,
            string authors,
            string owners,
            string description,
            string outputFolder)
        {
            Directory.CreateDirectory(outputFolder);
            var tempDirectoryPath = Path.GetTempPath();

            Directory.CreateDirectory(tempDirectoryPath);
            var    resultFileName  = Path.GetFileName(resultFile);
            string targetsFile     = Path.Combine(tempDirectoryPath, $"{packageId}.targets");
            var    targetsContents = $@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
  <ItemGroup>
    <LarnacaFiles Include=""$(MSBuildThisFileDirectory)..\contentFiles\**\{resultFileName}"">
        <Version>{version}</Version>
        <PackageIdentity>{packageId}</PackageIdentity>
    </LarnacaFiles>
  </ItemGroup>
</Project>
";

            File.WriteAllText(targetsFile, targetsContents);
            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors      = new string[] { authors },
                Owners       = new string[] { owners },
                Version      = new NuGetVersion(version),
                Id           = packageId,
                Description  = description,
                ContentFiles = new List <ManifestContentFiles>()
                {
                    new ManifestContentFiles()
                    {
                        Include     = "**/obj/*.*",
                        BuildAction = "none"
                    }
                },
                DependencyGroups = new PackageDependencyGroup[] { new PackageDependencyGroup(NuGet.Frameworks.NuGetFramework.AnyFramework, new PackageDependency[] { new PackageDependency("protobuf-net", new VersionRange(new NuGetVersion("2.4.2"))) }) }
            };

            PackageBuilder builder = new PackageBuilder();

            builder.PopulateFiles("", new ManifestFile[]
            {
                new ManifestFile()
                {
                    Source = resultFile,
                    Target = Path.Combine("contentFiles", "any", "any", "obj", resultFileName)
                },
                new ManifestFile()
                {
                    Source = targetsFile,
                    Target = Path.Combine("build", $"{packageId}.targets")
                }
            });
            builder.Populate(metadata);

            var    nugetFileName    = $"{packageId}.{version}.nupkg";
            string nugetPackageFile = Path.Combine(tempDirectoryPath, nugetFileName);

            // not deleting the file and overwriting it results in a corrupted archive
            if (File.Exists(nugetPackageFile))
            {
                File.Delete(nugetPackageFile);
            }

            using (FileStream stream = File.Open(nugetPackageFile, FileMode.CreateNew))
            {
                builder.Save(stream);
                stream.Flush();
            }

            File.Delete(targetsFile);
            File.Move(nugetPackageFile, Path.Combine(outputFolder, nugetFileName));
            return(new OperationResult());
        }
Exemple #35
0
        static private void Create(string solution, string project, string configuration, string plateform, string assembly)
        {
            var _assembly      = AssemblyDefinition.ReadAssembly(assembly);
            var _name          = _assembly.Name.Name;
            var _version       = _assembly.Metadata <AssemblyFileVersionAttribute>();
            var _directory     = Path.GetDirectoryName(assembly);
            var _dependencies  = new PackageReferenceFile(string.Concat(Path.GetDirectoryName(project), @"\packages.config")).GetPackageReferences().Where(_Package => _Package.Id != "NuPack").ToArray();
            var _extension     = _dependencies.Any(_Dependency => _Dependency.Id == "NuPack.Extension");
            var _setting       = new Setting(solution, project, configuration, plateform, assembly);
            var _specification = Program.Specification(project);

            if (_specification == null)
            {
                var _builder  = typeof(PackageBuilder).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(bool) }, null).Invoke(new object[] { true }) as PackageBuilder;
                var _metadata = new ManifestMetadata()
                {
                    Id          = _name,
                    Title       = _assembly.Metadata <AssemblyProductAttribute>() ?? _name,
                    Authors     = _assembly.Metadata <AssemblyCompanyAttribute>() ?? "-",
                    Version     = _version,
                    Summary     = _assembly.Metadata <AssemblyDescriptionAttribute>() ?? (_assembly.Metadata <AssemblyProductAttribute>() ?? "-"),
                    Description = _assembly.Metadata <AssemblyDescriptionAttribute>() ?? "-",
                    Copyright   = _assembly.Metadata <AssemblyCopyrightAttribute>() ?? "-"
                };
                _builder.Populate(_metadata);
                if (assembly.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (_extension)
                    {
                        throw new NotSupportedException();
                    }
                    var _targets = string.Concat(assembly.Substring(0, assembly.Length - 4), ".targets");
                    _builder.PopulateFiles(null, Program.Bin(_directory).Select(_Filename => new ManifestFile()
                    {
                        Source = _Filename, Target = "build"
                    }));
                    var _plugins = Program.Extends(_dependencies, _setting, ref _builder);
                    Program.Try(() => { if (File.Exists(_targets))
                                        {
                                            File.Delete(_targets);
                                        }
                                });
                    using (var _stream = typeof(Program).Assembly.GetManifestResourceStream("NuPack.Template")) { File.WriteAllText(_targets, new StreamReader(_stream).ReadToEnd().Replace("[name]", _name).Replace("[version]", _builder.Version.ToOriginalString()), Encoding.UTF8); }
                    var _filename = Program.Save(_directory, _builder);
                    Program.Try(() => { if (File.Exists(_targets))
                                        {
                                            File.Delete(_targets);
                                        }
                                });
                    Console.WriteLine($"{ _name } -> { _filename }");
                    foreach (var _plugin in _plugins)
                    {
                        _plugin.Dispose();
                    }
                }
                else
                {
                    if (_extension)
                    {
                        _builder.Files.AddRange(Program.Template().GetContentFiles());
                        _builder.PopulateFiles(null, Program.Bin(_directory, "Microsoft.Web.XmlTransform.dll", "NuGet.Core.dll", "NuPack.Extension.dll", "NuPack.Extension.xml").Select(_Filename => new ManifestFile()
                        {
                            Source = _Filename, Target = $"NuPack"
                        }));
                        var _plugins = Program.Extends(_dependencies, _setting, ref _builder);
                        Console.WriteLine($"{ _name } -> { Program.Save(_directory, _builder) }");
                        foreach (var _plugin in _plugins)
                        {
                            _plugin.Dispose();
                        }
                    }
                    else
                    {
                        var _dictionary = _dependencies.Select(_Dependency => string.Concat(solution, @"packages\", _Dependency.Id, ".", _Dependency.Version, @"\lib")).Where(_Library => Directory.Exists(_Library)).SelectMany(_Library => Directory.EnumerateFiles(_Library, "*", SearchOption.AllDirectories)).ToArray();
                        foreach (var _dependency in _dependencies.GroupBy(_Package => _Package.TargetFramework))
                        {
                            _builder.DependencySets.Add(new PackageDependencySet(_dependency.Key, _dependency.Select(_Package => new PackageDependency(_Package.Id, _Package.VersionConstraint, null, null))));
                        }
                        var _targets = string.Concat(assembly.Substring(0, assembly.Length - 4), ".targets");
                        if (_dictionary.Any(_Resource => !_Resource.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase)))
                        {
                            using (var _stream = typeof(Program).Assembly.GetManifestResourceStream("NuPack.Template"))
                            {
                                var _document  = XDocument.Parse(new StreamReader(_stream).ReadToEnd().Replace("[name]", _name), LoadOptions.PreserveWhitespace);
                                var _namespace = _document.Root.Name.Namespace;
                                var _sequence  = _document.Descendants(_namespace.GetName("Target")).Single();
                                _sequence.RemoveNodes();
                                foreach (var _dependency in _dependencies)
                                {
                                    var _library = string.Concat(solution, @"packages\", _dependency.Id, ".", _dependency.Version.ToOriginalString(), @"\lib");
                                    if (Directory.Exists(_library))
                                    {
                                        foreach (var _resource in Directory.EnumerateFiles(_library).Select(_Filename => Path.GetFileName(_Filename)))
                                        {
                                            if (_resource.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
                                            {
                                                continue;
                                            }
                                            _sequence.Add(new XElement(_namespace.GetName("Exec"), new XAttribute("Command", $"xcopy /f /q /y \"$(SolutionDir)packages\\{ _dependency.Id }.{ _dependency.Version }\\lib\\{ _resource }\" \"$(ProjectDir)$(OutDir)*\" > nul")));
                                        }
                                    }
                                }
                                File.WriteAllText(_targets, _document.ToString(), Encoding.UTF8);
                                _builder.PopulateFiles(null, new ManifestFile[] { new ManifestFile()
                                                                                  {
                                                                                      Source = _targets, Target = $"build"
                                                                                  } });
                            }
                        }
                        var _framework = $"lib/net{ _assembly.MainModule.RuntimeVersion[1] }{ _assembly.MainModule.RuntimeVersion[3] }/";
                        var _resources = _dictionary.Select(_Resource => Path.GetFileName(_Resource)).Concat(Program.Resources(project, configuration, false)).Select(_Resource => _Resource.ToLower()).Distinct().ToArray();
                        _builder.PopulateFiles(null, Program.Bin(_directory, Path.GetFileName(_targets)).Where(_Resource => !_resources.Contains(Path.GetFileName(_Resource).ToLower())).Select(_Resource => new ManifestFile()
                        {
                            Source = _Resource, Target = _framework
                        }));
                        var _plugins  = Program.Extends(_dependencies, _setting, ref _builder);
                        var _filename = Program.Save(_directory, _builder);
                        Program.Try(() => { if (File.Exists(_targets))
                                            {
                                                File.Delete(_targets);
                                            }
                                    });
                        Console.WriteLine($"{ _name } -> { _filename }");
                        foreach (var _plugin in _plugins)
                        {
                            _plugin.Dispose();
                        }
                    }
                }
            }
            else
            {
                var _builder  = new PackageBuilder();
                var _manifest = Program.Open(_specification);
                _builder.Populate(_manifest.Metadata);
                _builder.PopulateFiles(null, _manifest.Files);
                var _plugins = Program.Extends(_dependencies, _setting, ref _builder);
                Console.WriteLine($"{ _name } -> { Program.Save(_directory, _builder) }");
                foreach (var _plugin in _plugins)
                {
                    _plugin.Dispose();
                }
            }
        }
Exemple #36
0
        private static void Main(string[] args)
        {
            var options = new Options();
            var result  = Parser.Default.ParseArguments(args, options);

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

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

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

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

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

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

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

            var newVersion = match.Value;

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

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

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

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

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

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

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

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

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

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

            Console.WriteLine("Succesfully promoted package");
        }
Exemple #37
0
		private void AssertMetadata(ManifestMetadata metadata)
		{
			var package = GetPkg();

			Assert.IsNotNull(package);
			Assert.AreEqual(metadata.Id, package.Id);
			Assert.AreEqual(metadata.Version, package.Version.ToString());
			Assert.AreEqual(metadata.Title, package.Title);
			CollectionAssert.AreEqual(metadata.Authors.Split(new[] { ',' }), package.Authors);
			CollectionAssert.AreEqual(metadata.Owners.Split(new[] { ',' }), package.Owners);
			Assert.AreEqual(metadata.Description, package.Description);
			Assert.AreEqual(metadata.ReleaseNotes, package.ReleaseNotes);
			Assert.AreEqual(metadata.Summary, package.Summary);
			Assert.AreEqual(metadata.Language, package.Language);
			Assert.AreEqual(metadata.ProjectUrl, package.ProjectUrl.ToString());
			Assert.AreEqual(metadata.IconUrl, package.IconUrl.ToString());
			Assert.AreEqual(metadata.LicenseUrl, package.LicenseUrl.ToString());
			Assert.AreEqual(metadata.Copyright, package.Copyright);
			Assert.AreEqual(metadata.RequireLicenseAcceptance, package.RequireLicenseAcceptance);
			//dependencies
			//references
			//frameworkAssemblies
			Assert.AreEqual(metadata.Tags, package.Tags.SafeTrim());
			Assert.AreEqual(metadata.DevelopmentDependency, package.DevelopmentDependency);
		}
Exemple #38
0
        public void Execute(string[] commandLineArguments)
        {
            optionGroups.Parse(commandLineArguments);

            if (string.IsNullOrWhiteSpace(id))
            {
                throw new CommandException("An ID is required");
            }

            if (includes.All(string.IsNullOrWhiteSpace))
            {
                includes.Add("**");
            }

            if (string.IsNullOrWhiteSpace(basePath))
            {
                basePath = Path.GetFullPath(Environment.CurrentDirectory);
            }

            if (string.IsNullOrWhiteSpace(outFolder))
            {
                outFolder = Path.GetFullPath(Environment.CurrentDirectory);
            }

            if (version == null)
            {
                var now = DateTime.Now;
                version = new SemanticVersion(now.Year, now.Month, now.Day, now.Hour * 10000 + now.Minute * 100 + now.Second);
            }

            if (authors.All(string.IsNullOrWhiteSpace))
            {
                authors.Add(Environment.UserName + "@" + Environment.UserDomainName);
            }

            if (string.IsNullOrWhiteSpace(description))
            {
                description = "A deployment package created from files on disk.";
            }

            string allReleaseNotes = null;

            if (!string.IsNullOrWhiteSpace(releaseNotesFile))
            {
                if (!File.Exists(releaseNotesFile))
                {
                    log.Warning("The release notes file '{0}' could not be found", releaseNotesFile);
                }
                else
                {
                    allReleaseNotes = fileSystem.ReadFile(releaseNotesFile);
                }
            }

            if (!string.IsNullOrWhiteSpace(releaseNotes))
            {
                if (allReleaseNotes != null)
                {
                    allReleaseNotes += Environment.NewLine + releaseNotes;
                }
                else
                {
                    allReleaseNotes = releaseNotes;
                }
            }

            var metadata = new ManifestMetadata
            {
                Id          = id,
                Authors     = authors,
                Description = description,
                Version     = version.ToNuGetVersion(),
            };

            if (!string.IsNullOrWhiteSpace(allReleaseNotes))
            {
                metadata.ReleaseNotes = allReleaseNotes;
            }

            if (!string.IsNullOrWhiteSpace(title))
            {
                metadata.Title = title;
            }

            log.Information("Packing {0} version {1}...", id, version);

            packageBuilder.BuildPackage(basePath, includes, metadata, outFolder, overwrite);

            log.Information("Done.");
        }