Ejemplo n.º 1
0
        public PackArgs GetPackArgs(IPackTaskRequest <IMSBuildItem> request)
        {
            var packArgs = new PackArgs
            {
                Logger            = request.Logger,
                OutputDirectory   = request.PackageOutputPath,
                Serviceable       = request.Serviceable,
                Tool              = request.IsTool,
                Symbols           = request.IncludeSymbols,
                BasePath          = request.NuspecBasePath,
                NoPackageAnalysis = request.NoPackageAnalysis,
                PackTargetArgs    = new MSBuildPackTargetArgs
                {
                    AllowedOutputExtensionsInPackageBuildOutputFolder        = InitOutputExtensions(request.AllowedOutputExtensionsInPackageBuildOutputFolder),
                    AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder = InitOutputExtensions(request.AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder),
                    TargetPathsToAssemblies = InitLibFiles(request.BuildOutputInPackage),
                    TargetPathsToSymbols    = InitLibFiles(request.TargetPathsToSymbols),
                    AssemblyName            = request.AssemblyName,
                    IncludeBuildOutput      = request.IncludeBuildOutput,
                    BuildOutputFolder       = request.BuildOutputFolder,
                    TargetFrameworks        = ParseFrameworks(request)
                }
            };

            if (request.MinClientVersion != null)
            {
                Version version;
                if (!Version.TryParse(request.MinClientVersion, out version))
                {
                    throw new ArgumentException(string.Format(
                                                    CultureInfo.CurrentCulture,
                                                    Strings.InvalidMinClientVersion,
                                                    request.MinClientVersion));
                }

                packArgs.MinClientVersion = version;
            }

            if (request.NuspecProperties != null && request.NuspecProperties.Any())
            {
                packArgs.Properties.AddRange(ParsePropertiesAsDictionary(request.NuspecProperties));
                if (packArgs.Properties.ContainsKey("version"))
                {
                    packArgs.Version = packArgs.Properties["version"];
                }
            }

            InitCurrentDirectoryAndFileName(request, packArgs);
            InitNuspecOutputPath(request, packArgs);

            if (request.IncludeSource)
            {
                packArgs.PackTargetArgs.SourceFiles = GetSourceFiles(request, packArgs.CurrentDirectory);
                packArgs.Symbols = request.IncludeSource;
            }

            PackCommandRunner.SetupCurrentDirectory(packArgs);

            var contentFiles = ProcessContentToIncludeInPackage(request, packArgs);

            packArgs.PackTargetArgs.ContentFiles = contentFiles;

            return(packArgs);
        }
Ejemplo n.º 2
0
 public void BuildPackage(PackCommandRunner runner)
 {
     runner.BuildPackage();
 }
Ejemplo n.º 3
0
        private static void InitializeProjectDependencies(
            LockFile assetsFile,
            Dictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework)
        {
            // From the package spec, all we know is each absolute path to the project reference the the target
            // framework that project reference applies to.

            if (assetsFile.PackageSpec.RestoreMetadata == null)
            {
                return;
            }

            // Using the libraries section of the assets file, the library name and version for the project path.
            var projectPathToLibraryIdentities = assetsFile
                                                 .Libraries
                                                 .Where(library => library.MSBuildProject != null)
                                                 .ToLookup(
                library => Path.GetFullPath(Path.Combine(
                                                Path.GetDirectoryName(assetsFile.PackageSpec.RestoreMetadata.ProjectPath),
                                                PathUtility.GetPathWithDirectorySeparator(library.MSBuildProject))),
                library => new PackageIdentity(library.Name, library.Version));

            // Consider all of the project references, grouped by target framework.
            foreach (var framework in assetsFile.PackageSpec.RestoreMetadata.TargetFrameworks)
            {
                var target = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                if (target == null)
                {
                    continue;
                }

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // For the current target framework, create a map from library identity to library model. This allows
                // us to be sure we have picked the correct library (name and version) for this target framework.
                var libraryIdentityToTargetLibrary = target
                                                     .Libraries
                                                     .ToLookup(library => new PackageIdentity(library.Name, library.Version));

                foreach (var projectReference in framework.ProjectReferences)
                {
                    var libraryIdentities = projectPathToLibraryIdentities[projectReference.ProjectPath];

                    var targetLibrary = libraryIdentities
                                        .Select(identity => libraryIdentityToTargetLibrary[identity].FirstOrDefault())
                                        .FirstOrDefault(library => library != null);

                    if (targetLibrary == null)
                    {
                        continue;
                    }

                    // TODO: Implement <TreatAsPackageReference>false</TreatAsPackageReference>
                    //   https://github.com/NuGet/Home/issues/3891
                    //
                    // For now, assume the project reference is a package dependency.
                    var projectDependency = new LibraryDependency
                    {
                        LibraryRange = new LibraryRange(
                            targetLibrary.Name,
                            new VersionRange(targetLibrary.Version),
                            LibraryDependencyTarget.All),
                        IncludeType    = projectReference.IncludeAssets & ~projectReference.ExcludeAssets,
                        SuppressParent = projectReference.PrivateAssets
                    };

                    PackCommandRunner.AddLibraryDependency(projectDependency, dependencies);
                }
            }
        }
Ejemplo n.º 4
0
        private static void InitializePackageDependencies(
            LockFile assetsFile,
            Dictionary <NuGetFramework, HashSet <LibraryDependency> > dependenciesByFramework,
            ISet <NuGetFramework> frameworkWithSuppressedDependencies)
        {
            // From the package spec, we know the direct package dependencies of this project.
            foreach (var framework in assetsFile.PackageSpec.TargetFrameworks)
            {
                if (frameworkWithSuppressedDependencies.Contains(framework.FrameworkName))
                {
                    continue;
                }

                IEnumerable <LibraryDependency> centralTransitiveDependencies = assetsFile
                                                                                .CentralTransitiveDependencyGroups
                                                                                .Where(centralTDG => centralTDG.FrameworkName.Equals(framework.FrameworkName.ToString(), StringComparison.OrdinalIgnoreCase))
                                                                                .SelectMany(centralTDG => centralTDG.TransitiveDependencies);

                // First, add each of the generic package dependencies to the framework-specific list.
                var packageDependencies = assetsFile
                                          .PackageSpec
                                          .Dependencies
                                          .Concat(framework.Dependencies)
                                          .Concat(centralTransitiveDependencies);

                HashSet <LibraryDependency> dependencies;
                if (!dependenciesByFramework.TryGetValue(framework.FrameworkName, out dependencies))
                {
                    dependencies = new HashSet <LibraryDependency>();
                    dependenciesByFramework[framework.FrameworkName] = dependencies;
                }

                // Add each package dependency.
                foreach (var packageDependency in packageDependencies)
                {
                    // If we have a floating package dependency like 1.2.3-xyz-*, we
                    // use the version of the package that restore resolved it to.
                    if (packageDependency.LibraryRange.VersionRange.IsFloating)
                    {
                        var lockFileTarget = assetsFile.GetTarget(framework.FrameworkName, runtimeIdentifier: null);
                        var package        = lockFileTarget.Libraries.First(
                            library =>
                            string.Equals(library.Name, packageDependency.Name, StringComparison.OrdinalIgnoreCase));
                        if (package != null)
                        {
                            if (packageDependency.LibraryRange.VersionRange.HasUpperBound)
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive,
                                    maxVersion: packageDependency.LibraryRange.VersionRange.MaxVersion,
                                    includeMaxVersion: packageDependency.LibraryRange.VersionRange.IsMaxInclusive);
                            }
                            else
                            {
                                packageDependency.LibraryRange.VersionRange = new VersionRange(
                                    minVersion: package.Version,
                                    includeMinVersion: packageDependency.LibraryRange.VersionRange.IsMinInclusive);
                            }
                        }
                    }

                    PackCommandRunner.AddLibraryDependency(packageDependency, dependencies);
                }
            }
        }
Ejemplo n.º 5
0
 public bool BuildPackage(PackCommandRunner runner)
 {
     return(runner.RunPackageBuild());
 }
Ejemplo n.º 6
0
        public PackArgs GetPackArgs(IPackTaskRequest <IMSBuildItem> request)
        {
            var packArgs = new PackArgs
            {
                InstallPackageToOutputPath    = request.InstallPackageToOutputPath,
                OutputFileNamesWithoutVersion = request.OutputFileNamesWithoutVersion,
                OutputDirectory     = request.PackageOutputPath,
                Serviceable         = request.Serviceable,
                Tool                = request.IsTool,
                Symbols             = request.IncludeSymbols,
                SymbolPackageFormat = PackArgs.GetSymbolPackageFormat(request.SymbolPackageFormat),
                BasePath            = request.NuspecBasePath,
                NoPackageAnalysis   = request.NoPackageAnalysis,
                NoDefaultExcludes   = request.NoDefaultExcludes,
                WarningProperties   = WarningProperties.GetWarningProperties(request.TreatWarningsAsErrors, request.WarningsAsErrors, request.NoWarn),
                PackTargetArgs      = new MSBuildPackTargetArgs()
            };

            packArgs.Logger = new PackCollectorLogger(request.Logger, packArgs.WarningProperties);

            if (request.MinClientVersion != null)
            {
                Version version;
                if (!Version.TryParse(request.MinClientVersion, out version))
                {
                    throw new PackagingException(NuGetLogCode.NU5022, string.Format(
                                                     CultureInfo.CurrentCulture,
                                                     Strings.InvalidMinClientVersion,
                                                     request.MinClientVersion));
                }

                packArgs.MinClientVersion = version;
            }

            LockFile assetsFile = GetAssetsFile(request);
            var      aliases    = new Dictionary <string, string>();

            foreach (var tfm in assetsFile.PackageSpec.TargetFrameworks)
            {
                aliases[tfm.TargetAlias] = tfm.FrameworkName.GetShortFolderName();
            }

            InitCurrentDirectoryAndFileName(request, packArgs);
            InitNuspecOutputPath(request, packArgs);
            PackCommandRunner.SetupCurrentDirectory(packArgs);

            if (!string.IsNullOrEmpty(request.NuspecFile))
            {
                if (request.NuspecProperties != null && request.NuspecProperties.Any())
                {
                    packArgs.Properties.AddRange(ParsePropertiesAsDictionary(request.NuspecProperties));
                    if (packArgs.Properties.ContainsKey("version"))
                    {
                        packArgs.Version = packArgs.Properties["version"];
                    }
                }
            }
            else
            {
                // This only needs to happen when packing via csproj, not nuspec.
                packArgs.PackTargetArgs.AllowedOutputExtensionsInPackageBuildOutputFolder        = InitOutputExtensions(request.AllowedOutputExtensionsInPackageBuildOutputFolder);
                packArgs.PackTargetArgs.AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder = InitOutputExtensions(request.AllowedOutputExtensionsInSymbolsPackageBuildOutputFolder);
                packArgs.PackTargetArgs.TargetPathsToAssemblies = InitLibFiles(request.BuildOutputInPackage, aliases);
                packArgs.PackTargetArgs.TargetPathsToSymbols    = InitLibFiles(request.TargetPathsToSymbols, aliases);
                packArgs.PackTargetArgs.AssemblyName            = request.AssemblyName;
                packArgs.PackTargetArgs.IncludeBuildOutput      = request.IncludeBuildOutput;
                packArgs.PackTargetArgs.BuildOutputFolder       = request.BuildOutputFolders;
                packArgs.PackTargetArgs.TargetFrameworks        = ParseFrameworks(request, aliases);

                if (request.IncludeSource)
                {
                    packArgs.PackTargetArgs.SourceFiles = GetSourceFiles(request, packArgs.CurrentDirectory);
                    packArgs.Symbols = request.IncludeSource;
                }

                var contentFiles = ProcessContentToIncludeInPackage(request, packArgs);
                packArgs.PackTargetArgs.ContentFiles = contentFiles;
            }

            return(packArgs);
        }
Ejemplo n.º 7
0
        public override void ExecuteCommand()
        {
            PackArgs packArgs = new PackArgs();

            packArgs.Logger           = Console;
            packArgs.Arguments        = Arguments;
            packArgs.OutputDirectory  = OutputDirectory;
            packArgs.BasePath         = BasePath;
            packArgs.MsBuildDirectory = MsBuildUtility.GetMsBuildDirectoryFromMsBuildPath(MSBuildPath, MSBuildVersion, Console);

            // Get the input file
            packArgs.Path = PackCommandRunner.GetInputFile(packArgs);

            // Set the current directory if the files being packed are in a different directory
            PackCommandRunner.SetupCurrentDirectory(packArgs);

            Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(packArgs.Path));

            if (!String.IsNullOrEmpty(MinClientVersion))
            {
                if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue))
                {
                    throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion"));
                }
            }

            packArgs.Build   = Build;
            packArgs.Exclude = Exclude;
            packArgs.ExcludeEmptyDirectories   = ExcludeEmptyDirectories;
            packArgs.IncludeReferencedProjects = IncludeReferencedProjects;
            switch (Verbosity)
            {
            case Verbosity.Detailed:
            {
                packArgs.LogLevel = Common.LogLevel.Verbose;
                break;
            }

            case Verbosity.Normal:
            {
                packArgs.LogLevel = Common.LogLevel.Information;
                break;
            }

            case Verbosity.Quiet:
            {
                packArgs.LogLevel = Common.LogLevel.Minimal;
                break;
            }
            }
            packArgs.MinClientVersion  = _minClientVersionValue;
            packArgs.NoDefaultExcludes = NoDefaultExcludes;
            packArgs.NoPackageAnalysis = NoPackageAnalysis;
            if (Properties.Any())
            {
                packArgs.Properties.AddRange(Properties);
            }
            packArgs.Suffix  = Suffix;
            packArgs.Symbols = Symbols;
            packArgs.Tool    = Tool;

            if (!string.IsNullOrEmpty(Version))
            {
                NuGetVersion version;
                if (!NuGetVersion.TryParse(Version, out version))
                {
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, NuGetResources.InstallCommandPackageReferenceInvalidVersion, Version));
                }
                packArgs.Version = version.ToNormalizedString();
            }

            PackCommandRunner packCommandRunner = new PackCommandRunner(packArgs, ProjectFactory.ProjectCreator);

            packCommandRunner.BuildPackage();
        }
Ejemplo n.º 8
0
        public static void Register(CommandLineApplication app, Func <ILogger> getLogger)
        {
            app.Command("pack", pack =>
            {
                pack.Description = Strings.PackCommand_Description;

                pack.Option(
                    CommandConstants.ForceEnglishOutputOption,
                    Strings.ForceEnglishOutput_Description,
                    CommandOptionType.NoValue);

                var basePath = pack.Option(
                    "-b|--base-path <basePath>",
                    Strings.BasePath_Description,
                    CommandOptionType.SingleValue);

                var build = pack.Option(
                    "--build",
                    Strings.Build_Description,
                    CommandOptionType.NoValue);

                var exclude = pack.Option(
                    "--exclude",
                    Strings.Exclude_Description,
                    CommandOptionType.MultipleValue);

                var excludeEmpty = pack.Option(
                    "-e|--exclude-empty-directories",
                    Strings.ExcludeEmptyDirectories_Description,
                    CommandOptionType.NoValue);

                var minClientVersion = pack.Option(
                    "--min-client-version <version>",
                    Strings.MinClientVersion_Description,
                    CommandOptionType.SingleValue);

                var noDefaultExcludes = pack.Option(
                    "--no-default-excludes",
                    Strings.NoDefaultExcludes_Description,
                    CommandOptionType.NoValue);

                var noPackageAnalysis = pack.Option(
                    "--no-package-analysis",
                    Strings.NoPackageAnalysis_Description,
                    CommandOptionType.NoValue);

                var outputDirectory = pack.Option(
                    "-o|--output-directory <outputDirectory>",
                    Strings.OutputDirectory_Description,
                    CommandOptionType.SingleValue);

                var properties = pack.Option(
                    "-p|--properties <properties>",
                    Strings.OutputDirectory_Description,
                    CommandOptionType.SingleValue);

                var serviceable = pack.Option(
                    "--serviceable",
                    Strings.Serviceable_Description,
                    CommandOptionType.NoValue);

                var suffix = pack.Option(
                    "--suffix <suffix>",
                    Strings.Suffix_Description,
                    CommandOptionType.SingleValue);

                var symbols = pack.Option(
                    "-s|--symbols",
                    Strings.Symbols_Description,
                    CommandOptionType.NoValue);

                var verbosity = pack.Option(
                    "--verbosity <level>",
                    Strings.Switch_Verbosity,
                    CommandOptionType.SingleValue);

                var versionOption = pack.Option(
                    "-v|--version <version>",
                    Strings.Version_Description,
                    CommandOptionType.SingleValue);

                var arguments = pack.Argument(
                    "nuspec or project.json file",
                    Strings.InputFile_Description,
                    multipleValues: true);

                pack.OnExecute(() =>
                {
                    var logger               = getLogger();
                    var packArgs             = new PackArgs();
                    packArgs.Logger          = logger;
                    packArgs.Arguments       = arguments.Values;
                    packArgs.Path            = PackCommandRunner.GetInputFile(packArgs);
                    packArgs.OutputDirectory = outputDirectory.Value();
                    packArgs.BasePath        = basePath.Value();

                    // Set the current directory if the files being packed are in a different directory
                    PackCommandRunner.SetupCurrentDirectory(packArgs);

                    logger.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.PackageCommandAttemptingToBuildPackage, Path.GetFileName(packArgs.Path)));

                    packArgs.Build   = build.HasValue();
                    packArgs.Exclude = exclude.Values;
                    packArgs.ExcludeEmptyDirectories = excludeEmpty.HasValue();
                    packArgs.LogLevel = XPlatUtility.GetLogLevel(verbosity);

                    if (minClientVersion.HasValue())
                    {
                        Version version;
                        if (!Version.TryParse(minClientVersion.Value(), out version))
                        {
                            throw new ArgumentException(Strings.PackageCommandInvalidMinClientVersion);
                        }
                        packArgs.MinClientVersion = version;
                    }

                    packArgs.MachineWideSettings = new XPlatMachineWideSetting();
                    packArgs.MsBuildDirectory    = new Lazy <string>(() => string.Empty);
                    packArgs.NoDefaultExcludes   = noDefaultExcludes.HasValue();
                    packArgs.NoPackageAnalysis   = noPackageAnalysis.HasValue();

                    if (properties.HasValue())
                    {
                        foreach (var property in properties.Value().Split(';'))
                        {
                            int index = property.IndexOf('=');
                            if (index > 0 && index < property.Length - 1)
                            {
                                packArgs.Properties.Add(property.Substring(0, index), property.Substring(index + 1));
                            }
                        }
                    }

                    packArgs.Serviceable = serviceable.HasValue();
                    packArgs.Suffix      = suffix.Value();
                    packArgs.Symbols     = symbols.HasValue();
                    if (versionOption.HasValue())
                    {
                        NuGetVersion version;
                        if (!NuGetVersion.TryParse(versionOption.Value(), out version))
                        {
                            throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.PackageVersionInvalid, versionOption.Value()));
                        }
                        packArgs.Version = version.ToNormalizedString();
                    }

                    PackCommandRunner packCommandRunner = new PackCommandRunner(packArgs, null);
                    packCommandRunner.BuildPackage();

                    return(0);
                });
            });
        }