Ejemplo n.º 1
0
 private static void EnsurePackageFileExists(string packagePath, IEnumerable <string> packagesToPush)
 {
     if (!packagesToPush.Any())
     {
         throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("UnableToFindFile"), packagePath));
     }
 }
Ejemplo n.º 2
0
        private void InstallPackage(
            IFileSystem fileSystem,
            string packageId,
            SemanticVersion version)
        {
            if (version == null)
            {
                NoCache = true;
            }
            var packageManager = CreatePackageManager(fileSystem, AllowMultipleVersions);

            if (!PackageInstallNeeded(packageManager, packageId, version))
            {
                Console.WriteLine(LocalizedResourceManager.GetString("InstallCommandPackageAlreadyExists"), packageId);
                return;
            }

            if (version == null)
            {
                var latestVersion = GetLastestPackageVersion(
                    packageManager.SourceRepository,
                    packageId,
                    allowPrereleaseVersions: Prerelease);
                if (latestVersion != null)
                {
                    version = latestVersion.Version;
                }
            }

            using (packageManager.SourceRepository.StartOperation(
                       RepositoryOperationNames.Install,
                       packageId,
                       version == null ? null : version.ToString()))
            {
                var resolver = new ActionResolver()
                {
                    Logger = Console,
                    AllowPrereleaseVersions = Prerelease
                };

                // Resolve the package to install
                IPackage package = PackageRepositoryHelper.ResolvePackage(
                    packageManager.SourceRepository,
                    packageManager.LocalRepository,
                    packageId,
                    version,
                    Prerelease);

                // Resolve operations. Note that we only care about AddToPackagesFolder actions
                resolver.AddOperation(
                    PackageAction.Install,
                    package,
                    new NullProjectManager(packageManager));
                var actions = resolver.ResolveActions()
                              .Where(action => action.ActionType == PackageActionType.AddToPackagesFolder);

                if (actions.Any())
                {
                    var executor = new ActionExecutor()
                    {
                        Logger = Console
                    };
                    executor.Execute(actions);
                }
                else if (packageManager.LocalRepository.Exists(package))
                {
                    // If the package wasn't installed by our set of operations, notify the user.
                    Console.Log(
                        MessageLevel.Info,
                        NuGet.Resources.NuGetResources.Log_PackageAlreadyInstalled,
                        package.GetFullName());
                }
            }
        }
Ejemplo n.º 3
0
        public override void ExecuteCommand()
        {
            if (Verbose)
            {
                Console.WriteWarning(LocalizedResourceManager.GetString("Option_VerboseDeprecated"));
                Verbosity = Verbosity.Detailed;
            }

            IEnumerable <IPackage> packages = GetPackages();

            bool hasPackages = false;

            if (packages != null)
            {
                if (Verbosity == Verbosity.Detailed)
                {
                    /***********************************************
                    * Package-Name
                    *  1.0.0.2010
                    *  This is the package Description
                    *
                    * Package-Name-Two
                    *  2.0.0.2010
                    *  This is the second package Description
                    ***********************************************/
                    foreach (var p in packages)
                    {
                        Console.PrintJustified(0, p.Id);
                        Console.PrintJustified(1, p.Version.ToString());
                        Console.PrintJustified(1, p.Description);
                        if (p.LicenseUrl != null && !string.IsNullOrEmpty(p.LicenseUrl.OriginalString))
                        {
                            Console.PrintJustified(1,
                                                   String.Format(CultureInfo.InvariantCulture, LocalizedResourceManager.GetString("ListCommand_LicenseUrl"), p.LicenseUrl.OriginalString));
                        }
                        Console.WriteLine();
                        hasPackages = true;
                    }
                }
                else
                {
                    /***********************************************
                    * Package-Name 1.0.0.2010
                    * Package-Name-Two 2.0.0.2010
                    ***********************************************/
                    foreach (var p in packages)
                    {
                        Console.PrintJustified(0, p.GetFullName());
                        hasPackages = true;
                    }
                }
            }

            if (!hasPackages)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("ListCommandNoPackages"));
            }
        }
Ejemplo n.º 4
0
        private void AddFiles(PackageBuilder builder, string itemType, string targetFolder)
        {
            // Skip files that are added by dependency packages
            var references = PackageReferenceFile.CreateFromProject(_project.FullPath).GetPackageReferences();
            IPackageRepository repository  = GetPackagesRepository();
            string             projectName = Path.GetFileNameWithoutExtension(_project.FullPath);

            var contentFilesInDependencies = new List <IPackageFile>();

            if (references.Any() && repository != null)
            {
                contentFilesInDependencies = references.Select(reference => repository.FindPackage(reference.Id, reference.Version))
                                             .Where(a => a != null)
                                             .SelectMany(a => a.GetContentFiles())
                                             .ToList();
            }

            // Get the content files from the project
            foreach (var item in _project.GetItems(itemType))
            {
                string fullPath = item.GetMetadataValue("FullPath");
                if (_excludeFiles.Contains(Path.GetFileName(fullPath)))
                {
                    continue;
                }

                string targetFilePath = GetTargetPath(item);

                if (!File.Exists(fullPath))
                {
                    Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_FileDoesNotExist"), targetFilePath);
                    continue;
                }

                // Skip target file paths containing msbuild variables since we do not offer a way to install files with variable paths.
                // These are show up in shared files found in universal apps.
                if (targetFilePath.IndexOf("$(MSBuild", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_UnresolvedFilePath"), targetFilePath);
                    continue;
                }

                // if IncludeReferencedProjects is true and we are adding source files,
                // add projectName as part of the target to avoid file conflicts.
                string targetPath = IncludeReferencedProjects && itemType == SourcesItemType?
                                    Path.Combine(targetFolder, projectName, targetFilePath) :
                                        Path.Combine(targetFolder, targetFilePath);

                // Check that file is added by dependency
                IPackageFile targetFile = contentFilesInDependencies.Find(a => a.Path.Equals(targetPath, StringComparison.OrdinalIgnoreCase));
                if (targetFile != null)
                {
                    // Compare contents as well
                    var isEqual = ContentEquals(targetFile, fullPath);
                    if (isEqual)
                    {
                        Logger.Log(MessageLevel.Info, LocalizedResourceManager.GetString("PackageCommandFileFromDependencyIsNotChanged"), targetFilePath);
                        continue;
                    }

                    Logger.Log(MessageLevel.Info, LocalizedResourceManager.GetString("PackageCommandFileFromDependencyIsChanged"), targetFilePath);
                }

                var packageFile = new PhysicalPackageFile
                {
                    SourcePath = fullPath,
                    TargetPath = targetPath
                };
                AddFileToBuilder(builder, packageFile);
            }
        }
Ejemplo n.º 5
0
 public void Initialize()
 {
     LocalizedResourceManager.Reset(TimeSpan.FromSeconds(5));
 }
Ejemplo n.º 6
0
        private bool RestorePackage(
            IFileSystem packagesFolderFileSystem,
            PackageIdentity packageIdentity,
            bool packageRestoreConsent,
            ConcurrentQueue <JObject> satellitePackages)
        {
            // BUGBUG: Looks like we are creating PackageManager for every single restore. This is likely done to support execution in parallel
            var packageManager = CreatePackageManager(packagesFolderFileSystem, useSideBySidePaths: true);

            if (IsPackageInstalled(packageManager.LocalRepository, packagesFolderFileSystem, packageIdentity))
            {
                return(false);
            }

            // BUGBUG: Investigate if the following lock is needed
            EnsurePackageRestoreConsent(packageRestoreConsent);
            if (RequireConsent && _outputOptOutMessage)
            {
                lock (_outputOptOutMessageLock)
                {
                    if (_outputOptOutMessage)
                    {
                        string message = String.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("RestoreCommandPackageRestoreOptOutMessage"),
                            NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                        Console.WriteLine(message);
                        _outputOptOutMessage = false;
                    }
                }
            }

            SourceRepository = SourceRepositoryHelper.CreateSourceRepository(SourceProvider, Source);

            // BUGBUG: TO BE REMOVED AFTER INVESTIGATION
            using (packageManager.SourceRepository.StartOperation(
                       RepositoryOperationNames.Restore,
                       packageIdentity.Id,
                       packageIdentity.Version == null ? null : packageIdentity.Version.ToString()))
            {
                // BUGBUG: Satellite packages should only be restored at the end. Find out Why first??
                //         And, then, handle it here


                var filesystemInstallationTarget = new FilesystemInstallationTarget(packageManager);

                // BUGBUG: Should consider using async method and await
                var task = SourceRepository.GetPackageMetadata(packageIdentity.Id, packageIdentity.Version);
                task.Wait();
                var packageJSON = task.Result;

                if (IsSatellitePackage(packageJSON))
                {
                    // Satellite packages would necessarily have to be installed later than the corresponding package.
                    // We'll collect them in a list to keep track and then install them later.
                    satellitePackages.Enqueue(packageJSON);
                    return(true);
                }

                var packageAction = new NewPackageAction(NuGet.Client.PackageActionType.Download,
                                                         packageIdentity, packageJSON, filesystemInstallationTarget, SourceRepository, null);

                // BUGBUG: See PackageExtractor.cs for locking mechanism used to handle concurrency
                NuGet.Client.Installation.ActionExecutor actionExecutor = new Client.Installation.ActionExecutor();

                // BUGBUG: This is likely inefficient. Consider collecting all actions first and executing them in 1 shot
                var packageActions = new List <NewPackageAction>()
                {
                    packageAction
                };
                actionExecutor.ExecuteActions(packageActions, Console);
                return(true);
            }
        }
Ejemplo n.º 7
0
        public PackageBuilder CreateBuilder(string basePath)
        {
            BuildProject();

            Logger.Log(MessageLevel.Info, LocalizedResourceManager.GetString("PackagingFilesFromOutputPath"), Path.GetDirectoryName(TargetPath));

            var builder = new PackageBuilder();

            try
            {
                // Populate the package builder with initial metadata from the assembly/exe
                AssemblyMetadataExtractor.ExtractMetadata(builder, TargetPath);
            }
            catch (Exception ex)
            {
                Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("UnableToExtractAssemblyMetadata"), Path.GetFileName(TargetPath));
                IConsole console = Logger as IConsole;
                if (console != null && console.Verbosity == Verbosity.Detailed)
                {
                    console.Log(MessageLevel.Warning, ex.ToString());
                }

                ExtractMetadataFromProject(builder);
            }

            var projectAuthor = InitializeProperties(builder);

            // If the package contains a nuspec file then use it for metadata
            Manifest manifest = ProcessNuspec(builder, basePath);

            // Remove the extra author
            if (builder.Authors.Count > 1)
            {
                builder.Authors.Remove(projectAuthor);
            }

            // Add output files
            ApplyAction(p => p.AddOutputFiles(builder));

            // if there is a .nuspec file, only add content files if the <files /> element is not empty.
            if (manifest == null || manifest.Files == null || manifest.Files.Count > 0)
            {
                // Add content files
                ApplyAction(p => p.AddFiles(builder, ContentItemType, ContentFolder));
            }

            // Add sources if this is a symbol package
            if (IncludeSymbols)
            {
                ApplyAction(p => p.AddFiles(builder, SourcesItemType, SourcesFolder));
            }

            ProcessDependencies(builder);

            // Set defaults if some required fields are missing
            if (String.IsNullOrEmpty(builder.Description))
            {
                builder.Description = "Description";
                Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_UnspecifiedField"), "Description", "Description");
            }

            if (!builder.Authors.Any())
            {
                builder.Authors.Add(Environment.UserName);
                Logger.Log(MessageLevel.Warning, LocalizedResourceManager.GetString("Warning_UnspecifiedField"), "Author", Environment.UserName);
            }

            return(builder);
        }
Ejemplo n.º 8
0
        private void PushSymbols(string packagePath, TimeSpan timeout)
        {
            // Get the symbol package for this package
            string symbolPackagePath = GetSymbolsPath(packagePath);

            // Push the symbols package if it exists
            if (File.Exists(symbolPackagePath))
            {
                string source = NuGetConstants.DefaultSymbolServerUrl;

                // See if the api key exists
                string apiKey = GetApiKey(source);

                if (String.IsNullOrEmpty(apiKey))
                {
                    Console.WriteWarning(LocalizedResourceManager.GetString("Warning_SymbolServerNotConfigured"), Path.GetFileName(symbolPackagePath), LocalizedResourceManager.GetString("DefaultSymbolServer"));
                }
                PushPackage(symbolPackagePath, source, apiKey, timeout);
            }
        }
Ejemplo n.º 9
0
        private void BuildSymbolsPackage(string path)
        {
            PackageBuilder symbolsBuilder = CreatePackageBuilderFromNuspec(path);

            // remove unnecessary files when building the symbols package
            ExcludeFilesForSymbolPackage(symbolsBuilder.Files);

            if (!symbolsBuilder.Files.Any())
            {
                throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForSymbolsPackage"),
                                                             path, CommandLineConstants.NuGetDocs));
            }

            string outputPath = GetOutputPath(symbolsBuilder, symbols: true);

            BuildPackage(symbolsBuilder, outputPath);
        }
Ejemplo n.º 10
0
        private IPackage BuildFromNuspec(string path)
        {
            PackageBuilder packageBuilder = CreatePackageBuilderFromNuspec(path);

            if (Symbols)
            {
                // remove source related files when building the lib package
                ExcludeFilesForLibPackage(packageBuilder.Files);

                if (!packageBuilder.Files.Any())
                {
                    throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForLibPackage"),
                                                                 path, CommandLineConstants.NuGetDocs));
                }
            }

            IPackage package = BuildPackage(packageBuilder);

            if (Symbols)
            {
                BuildSymbolsPackage(path);
            }

            return(package);
        }
Ejemplo n.º 11
0
        public override void ExecuteCommand()
        {
            if (NoPrompt)
            {
                Console.WriteWarning(LocalizedResourceManager.GetString("Warning_NoPromptDeprecated"));
                NonInteractive = true;
            }

            //First argument should be the package ID
            string packageId = Arguments[0];
            //Second argument should be the package Version
            string packageVersion = Arguments[1];

            //If the user passed a source use it for the gallery location
            string source  = SourceProvider.ResolveAndValidateSource(Source) ?? NuGetConstants.DefaultGalleryServerUrl;
            var    gallery = new PackageServer(source, CommandLineConstants.UserAgent);

            gallery.SendingRequest += (sender, e) =>
            {
                if (Console.Verbosity == NuGet.Verbosity.Detailed)
                {
                    Console.WriteLine(ConsoleColor.Green, "{0} {1}", e.Request.Method, e.Request.RequestUri);
                }
            };

            //If the user did not pass an API Key look in the config file
            string apiKey            = GetApiKey(source);
            string sourceDisplayName = CommandLineUtility.GetSourceDisplayName(source);

            if (String.IsNullOrEmpty(apiKey))
            {
                Console.WriteWarning(LocalizedResourceManager.GetString("NoApiKeyFound"), sourceDisplayName);
            }

            if (NonInteractive || Console.Confirm(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("DeleteCommandConfirm"), packageId, packageVersion, sourceDisplayName)))
            {
                Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandDeletingPackage"), packageId, packageVersion, sourceDisplayName);
                gallery.DeletePackage(apiKey, packageId, packageVersion);
                Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandDeletedPackage"), packageId, packageVersion);
            }
            else
            {
                Console.WriteLine(LocalizedResourceManager.GetString("DeleteCommandCanceled"));
            }
        }
        /// <summary>
        /// Takes command line args and parses response files prefixed with the @ symbol.
        /// Response files are text files that contain command line switches.
        /// Each switch can be on a separate line or all switches can be on one line.
        /// Multiple response files can be defined in the args.
        /// Nested response files are supported, but limited to a depth of 3.
        /// A response file cannot be larger than 2mb.
        /// </summary>
        /// <param name="args">The args to parse which can contain response files</param>
        /// <returns></returns>
        public static string[] ParseArgsResponseFiles(string[] args)
        {
            if (args.Length == 0)
            {
                return(args);
            }

            // Response files are not supported on other platforms yet
            if (!RuntimeEnvironmentHelper.IsWindows && !RuntimeEnvironmentHelper.IsMono)
            {
                return(args);
            }

            const int MaxRecursionDepth = 3;
            var       parsedArgs        = new List <string>();

            foreach (var arg in args)
            {
                if (string.IsNullOrWhiteSpace(arg) || !arg.StartsWith("@", StringComparison.InvariantCultureIgnoreCase))
                {
                    parsedArgs.Add(arg);
                    continue;
                }

                // Response file
                if (arg.Length < 2)
                {
                    throw new ArgumentException(LocalizedResourceManager.GetString("Error_ResponseFileInvalid"));
                }

                // Remove '@' symbol
                var responseFileArg = arg.Substring(1, arg.Length - 1);

                // File could be full path or relative path to working directory
                var responseFilePath = responseFileArg.Contains(Path.DirectorySeparatorChar) ?
                                       responseFileArg :
                                       Path.Combine(Environment.CurrentDirectory, responseFileArg);

                if (!File.Exists(responseFilePath))
                {
                    throw new ArgumentException(string.Format(LocalizedResourceManager.GetString("Error_ResponseFileDoesNotExist")), arg);
                }

                var fileInfo = new FileInfo(responseFilePath);
                if (fileInfo.Length == 0)
                {
                    throw new ArgumentException(string.Format(LocalizedResourceManager.GetString("Error_ResponseFileNullOrEmpty"), arg));
                }

                const int TwoMegaBytesLength = 2048000;
                if (fileInfo.Length > TwoMegaBytesLength)
                {
                    throw new ArgumentException(string.Format(LocalizedResourceManager.GetString("Error_ResponseFileTooLarge"), arg, TwoMegaBytesLength / 1000000));
                }

                var responseFileContents = File.ReadAllText(responseFilePath);
                var responseFileArgs     = SplitArgs(responseFileContents);
                foreach (var a in responseFileArgs)
                {
                    if (string.IsNullOrWhiteSpace(a))
                    {
                        continue;
                    }

                    if (a.StartsWith("@", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (ParseArgsResponseFileRecursionDepth > MaxRecursionDepth)
                        {
                            throw new ArgumentException(string.Format(LocalizedResourceManager.GetString("Error_ResponseFileMaxRecursionDepth"), MaxRecursionDepth));
                        }

                        ParseArgsResponseFileRecursionDepth++;
                        var nestedResponseFileArgs = ParseArgsResponseFiles(new string[] { a });
                        if (nestedResponseFileArgs.Length != 0)
                        {
                            parsedArgs.AddRange(nestedResponseFileArgs);
                        }

                        continue;
                    }

                    var parsedResponseFileArg = a.Trim();
                    if (!string.IsNullOrWhiteSpace(parsedResponseFileArg))
                    {
                        parsedArgs.Add(parsedResponseFileArg);
                    }
                }
            }

            return(parsedArgs.ToArray());
        }