/// <summary>
        ///     Deletes all files from a package
        /// </summary>
        /// <param name="installed">Insyalled package</param>
        /// <param name="repositories">Repositories where to find the package</param>
        private void DeleteFiles(PackageInfo installed, ICollection<string> repositories)
        {
            Logger.Log("Deleting installed files... ");

            var factory = new PackageRepositoryFactory();

            IPackage package;

            var globalRepo = new AggregateRepository(factory, repositories, true);

            package = globalRepo.FindPackage(installed.Name, SemanticVersion.Parse(installed.Version), true, true);

            if (package == null)
            {
                throw new InexistentPackageException(string.Format("Unable to find package {0} version {1}", installed.Name, installed.Version));
            }

            var fylesystem = new PhysicalFileSystem(installed.InstallationDirectory);

            fylesystem.DeleteFiles(package.GetFiles(), installed.InstallationDirectory);

            File.Delete(Path.Combine(installed.InstallationDirectory, installed.Name + "." + installed.Version + ".nupkg"));

            foreach (var config in Directory.GetFiles(installed.InstallationDirectory, "*.config"))
            {
                File.Delete(config);
            }

            Logger.Log("Installed files deleted");
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="settings"></param>
        /// <param name="mapPath">A delegate method used to perform a Server.MapPath operation</param>
        public DefaultPackageContext(RebelSettings settings, Func<string, string> mapPath)
        {
            _settings = settings;

            _pluginInstallFolderPath = mapPath(_settings.PluginConfig.PluginsPath + "/Packages");
            _localPackageRepoFolderPath = mapPath(_settings.RebelFolders.LocalPackageRepositoryFolder);

            //create lazy instances of each
            _localPackageRepository = new Lazy<IPackageRepository>(
                () =>
                    {
                        //create a new path resolver with false as 'useSideBySidePaths' so that it doesn't install with version numbers.
                        var packageFileSys = new PhysicalFileSystem(_localPackageRepoFolderPath);
                        var packagePathResolver = new DefaultPackagePathResolver(packageFileSys, false);
                        return new LocalPackageRepository(packagePathResolver, packageFileSys, true);
                    });

            _localPackageManager = new Lazy<IPackageManager>(
                () =>
                    {
                        //create a new path resolver with false as 'useSideBySidePaths' so that it doesn't install with version numbers.
                        var packageFileSys = new PhysicalFileSystem(_pluginInstallFolderPath);
                        var packagePathResolver = new DefaultPackagePathResolver(packageFileSys, false);
                        return new PackageManager(_localPackageRepository.Value, packagePathResolver, packageFileSys);
                    });
            
            // Public packages
            _publicPackageRepository = new Lazy<IPackageRepository>(
                () => PackageRepositoryFactory.Default.CreateRepository(_settings.PublicPackageRepository.RepositoryAddress));
            
            _publicPackageManager = new Lazy<IPackageManager>(
                () => new PackageManager(_publicPackageRepository.Value, mapPath(_settings.PluginConfig.PluginsPath + "/Packages")));

        }
Exemple #3
0
 private static PackageManager CreatePackageManager(DirectoryPath packagePath)
 {
     var repository = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
     var resolver = new PackagePathResolver(packagePath);
     var fileSystem = new PhysicalFileSystem(packagePath.FullPath);
     return new PackageManager(repository, resolver, fileSystem);
 }
 public static PackageReferenceFile CreateFromProject(string projectFileFullPath)
 {
     var fileSystem = new PhysicalFileSystem(Path.GetDirectoryName(projectFileFullPath));
     string projectName = Path.GetFileNameWithoutExtension(projectFileFullPath);
     var file = new PackageReferenceFile(fileSystem, Constants.PackageReferenceFile, projectName);
     return file;
 }
        public IEnumerable<string> GetRepositorySources(string path)
        {
            var configFileSystem = new PhysicalFileSystem(path);

            ISettings settings;
            if (_fileSystem.FileExists(Path.Combine(_fileSystem.CurrentDirectory, Constants.NugetFile)))
            {
                settings = new Settings(configFileSystem, Constants.NugetFile);
            }
            else
            {
                settings = Settings.LoadDefaultSettings(configFileSystem, null, new NugetMachineWideSettings());
            }

            if (settings == null)
            {
                return new[] { Constants.DefaultRepositoryUrl };
            }

            var sourceProvider = new PackageSourceProvider(settings);
            var sources = sourceProvider.LoadPackageSources().Where(i => i.IsEnabled == true);

            if (sources == null || !sources.Any())
            {
                return new[] { Constants.DefaultRepositoryUrl };
            }

            return sources.Select(i => i.Source);
        }
Exemple #6
0
        public NugetService(Solution solution)
        {
            //_defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);

            var factory = new PackageRepositoryFactory();

            _remoteRepository = factory.CreateRepository(GalleryUrl);
            _localRepository = factory.CreateRepository(solution.PackagesFolder());

            _sourceRepository = new AggregateRepository(new[] { _remoteRepository, _localRepository });

            _fileSystem = new PhysicalFileSystem(solution.PackagesFolder());
            _pathResolver = new DefaultPackagePathResolver(_fileSystem);

            _console = new Console();
            _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){
                Logger = _console
            };

            _packages = new Cache<NugetDependency, IPackage>(dep =>
            {
                Install(dep);
                return _sourceRepository.FindPackage(dep.Name, dep.Version);
            });
        }
Exemple #7
0
 public static async void DoWorkInWriterLock(EnvDTE.Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
 {
     await DoWorkInWriterLock((IVsProject)hierarchy, action);
     var fileSystem = new PhysicalFileSystem(@"c:\");
     fileSystem.MakeFileWritable(project.FullName);
     project.Save();
 }
Exemple #8
0
        public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig)
        {
            if (rootDirectory == null) throw new ArgumentNullException(nameof(rootDirectory));
            if (configFile == null) throw new ArgumentNullException(nameof(configFile));
            if (overrideFile == null) throw new ArgumentNullException(nameof(overrideFile));

            // First try the override file with custom settings
            var configFileName = overrideFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (!File.Exists(configFilePath))
            {
                // Override file does not exist, fallback to default config file
                configFileName = configFile;
                configFilePath = Path.Combine(rootDirectory, configFileName);

                if (!File.Exists(configFilePath))
                {
                    throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile));
                }
            }

            rootFileSystem = new PhysicalFileSystem(rootDirectory);
            Settings = NuGet.Settings.LoadDefaultSettings(rootFileSystem, configFileName, null);

            string installPath = Settings.GetRepositoryPath();
            packagesFileSystem = new PhysicalFileSystem(installPath);
            packageSourceProvider = new PackageSourceProvider(Settings);

            repositoryFactory = new PackageRepositoryFactory();
            SourceRepository = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true);

            pathResolver = new DefaultPackagePathResolver(packagesFileSystem);

            Manager = new PackageManager(SourceRepository, pathResolver, packagesFileSystem);

            var mainPackageList = Settings.GetConfigValue(MainPackagesKey);
            if (string.IsNullOrWhiteSpace(mainPackageList))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config");
            }
            MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            VSIXPluginId = Settings.GetConfigValue(VsixPluginKey);
            if (string.IsNullOrWhiteSpace(VSIXPluginId))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config");
            }

            RepositoryPath = Settings.GetConfigValue(RepositoryPathKey);
            if (string.IsNullOrWhiteSpace(RepositoryPath))
            {
                RepositoryPath = DefaultGamePackagesDirectory;
            }

            // Setup NugetCachePath in the cache folder
            Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath));
        }
Exemple #9
0
        public static int Main(string[] args)
        {
            var console = new Common.Console();
            var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies  
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(NuGetResources.InvalidArguments, commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                if (ExceptionUtility.Unwrap(exception) == exception)
                {
                    // If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
                    var messages = exception.InnerExceptions.Select(ex => ex.Message)
                                                            .Distinct(StringComparer.CurrentCulture);
                    console.WriteError(String.Join("\n", messages));
                }
            }
            catch (Exception e)
            {
                console.WriteError(ExceptionUtility.Unwrap(e).Message);
                return 1;
            }
            return 0;
        }
Exemple #10
0
 public RestoreCommand(IApplicationEnvironment env)
 {
     ApplicationEnvironment = env;
     FileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
     MachineWideSettings = new CommandLineMachineWideSettings();
     Sources = Enumerable.Empty<string>();
     FallbackSources = Enumerable.Empty<string>();
     ScriptExecutor = new ScriptExecutor();
 }
        protected PackageManagerService()
        {
            var repo        = PackageRepositoryFactory.Default.CreateRepository(MyGetRepoUrl);
            var path        = new DefaultPackagePathResolver(MyGetRepoUrl);
            var fileSystem  = new PhysicalFileSystem(HostingEnvironment.MapPath("~/App_Plugins/Packages"));
            var localRepo   = PackageRepositoryFactory.Default.CreateRepository(HostingEnvironment.MapPath("~/App_Plugins/Packages"));

            //Create a NuGet Package Manager
            PackageManager = new PackageManager(repo, path, fileSystem, localRepo);
        }
Exemple #12
0
 public WebProjectManager(string remoteSource, string siteRoot)
 {
     string webRepositoryDirectory = GetWebRepositoryDirectory(siteRoot);
     var fileSystem = new PhysicalFileSystem(webRepositoryDirectory);
     var packagePathResolver = new SubtextPackagePathResolver(fileSystem);
     _projectManager = new ProjectManager(sourceRepository: PackageRepositoryFactory.Default.CreateRepository(remoteSource),
                                pathResolver: packagePathResolver,
                                localRepository: new LocalPackageRepository(packagePathResolver, fileSystem),
                                project: new WebProjectSystem(siteRoot));
 }
 /// <summary>
 /// Returns the settings loaded from the user- and machine-wide config files
 /// </summary>
 /// <param name="configDirectory">Optional. Specifies an additional directory in which to look for a NuGet.config file</param>
 public static ISettings GetSettingsFromConfigFiles(string configDirectory)
 {
     IFileSystem fileSystem = null;
     if (configDirectory != null)
     {
         fileSystem = new PhysicalFileSystem(configDirectory);
     }
     NuGetMachineWideSettings machineSettings = new NuGetMachineWideSettings();
     ISettings settings = Settings.LoadDefaultSettings(fileSystem, null, machineSettings);
     return settings;
 }
		public bool AnyMissingPackages ()
		{
			var packagesPath = new SolutionPackageRepositoryPath (Project);
			var fileSystem = new PhysicalFileSystem (packagesPath.PackageRepositoryPath);
			foreach (PackageReference packageReference in GetPackageReferences ()) {
				if (!packageReference.IsPackageInstalled (fileSystem)) {
					return true;
				}
			}
			return false;
		}
		public static bool IsPackageInstalled (this PackageReference packageReference, PhysicalFileSystem fileSystem)
		{
			if (packageReference.Version == null) {
				return false;
			}

			var repository = new LocalPackageRepository (new DefaultPackagePathResolver (fileSystem), fileSystem);
			return repository
				.GetPackageLookupPaths (packageReference.Id, packageReference.Version)
				.Any ();
		}
        /// <summary>
        /// Creates a WebProjectManager service.
        /// </summary>
        /// <param name="remoteSource">URL of the NuGet server API (ex, http://nuget.org/api/v2 ).</param>
        /// <param name="siteRoot">The physical path to the web root.</param>
        public WebProjectManager( string remoteSource, string siteRoot )
        {
            string webRepositoryDirectory = GetWebRepositoryDirectory( siteRoot );
            var fileSystem = new PhysicalFileSystem( webRepositoryDirectory );
            var packagePathResolver = new RockPackagePathResolver( fileSystem );
            _projectManager = new RockProjectManager( sourceRepository: PackageRepositoryFactory.Default.CreateRepository( remoteSource ),
                                       pathResolver: packagePathResolver,
                                       localRepository: new LocalPackageRepository( packagePathResolver, fileSystem ),
                                       project: new WebProjectSystem( siteRoot ) );

            // Add event for reference files added (See note below)
            _projectManager.PackageReferenceAdded += ProjectManager_PackageReferenceAdded;
        }
Exemple #17
0
        public static int Main(string[] args)
        {
            var console = new NuGet.Common.Console();
            var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies  
                var p = new Program();
                p.Initialize(fileSystem);

                // Register an additional provider for the console specific application so that the user
                // will be prompted if a proxy is set and credentials are required
                HttpClient.DefaultCredentialProvider = new ConsoleCredentialProvider();

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    Console.WriteLine(NuGetResources.InvalidArguments, commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    command.Execute();
                }
            }
            catch (Exception e)
            {
                console.WriteError(e.Message);
                return 1;
            }
            return 0;
        }
        public IPackageManager CreatePackageManager(IEnumerable<string> remoteSources, string packagesPath)
        {
            if (remoteSources == null)
            {
                throw new ArgumentNullException("remoteSources");
            }
            if (!remoteSources.Any())
            {
                throw new ArgumentException("Must provide at least one remote source");
            }

            var sourceRepo = new AggregateRepository(PackageRepositoryFactory.Default, remoteSources, true);
            var pathResolver = new DefaultPackagePathResolver(packagesPath);
            var packageManagerFileSystem = new PhysicalFileSystem(packagesPath);

            return new PackageManager(sourceRepository: sourceRepo,
                                        pathResolver: pathResolver,
                                        fileSystem: packageManagerFileSystem);
        }
Exemple #19
0
        public static ISettings ReadSettings(string solutionDir, string nugetConfigFile, IFileSystem fileSystem,
            IMachineWideSettings machineWideSettings)
        {
            // Read the solution-level settings
            var solutionSettingsFile = Path.Combine(solutionDir, NuGetConstants.NuGetSolutionSettingsFolder);
            var fullPath = fileSystem.GetFullPath(solutionSettingsFile);
            var solutionSettingsFileSystem = new PhysicalFileSystem(fullPath);

            if (nugetConfigFile != null)
            {
                nugetConfigFile = fileSystem.GetFullPath(nugetConfigFile);
            }

            var settings = Settings.LoadDefaultSettings(
                fileSystem: solutionSettingsFileSystem,
                configFileName: nugetConfigFile,
                machineWideSettings: machineWideSettings);

            return settings;
        }
Exemple #20
0
        public static ISettings LoadDefaultSettings()
        {
            string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            if (!String.IsNullOrEmpty(appDataPath))
            {
                var defaultSettingsPath = Path.Combine(appDataPath, "NuGet");
                var fileSystem = new PhysicalFileSystem(defaultSettingsPath);
                try
                {
                    return new Settings(fileSystem);
                }
                catch (XmlException)
                {
                    // Work Item 1531: If the config file is malformed and the constructor throws, NuGet fails to load in VS. 
                    // Returning a null instance prevents us from silently failing.
                }
            }

            // If there is no AppData folder, use a null file system to make the Settings object do nothing
            return NullSettings.Instance;
        }
Exemple #21
0
        //download the specified version of the package and update project reference to it. The newly downloaded package
        //will be located in /packages folder. The updated project reference can be checked in corresponding .csproj file.
        public bool Execute(string packageid, string projectFile, SemanticVersion version, string packages)
        {
            try
            {
                System.Console.WriteLine("-------------------------------------");
                System.Console.WriteLine("Project File " + projectFile);
                System.Console.WriteLine("Package "+packageid);
                System.Console.WriteLine("Version "+version);

                IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
                var packagePathResolver = new DefaultPackagePathResolver(packages);
                var packagesFolderFileSystem = new PhysicalFileSystem(packages);
                var projectSystem = new MSBuildProjectSystem(projectFile);
                var localRepository = new LocalPackageRepository(packagePathResolver, packagesFolderFileSystem);
                var projectManager = new ProjectManager(repo, packagePathResolver, projectSystem, localRepository);

                projectManager.RemovePackageReference(packageid,true,false);
                projectManager.AddPackageReference(packageid, version, true, false);
                projectSystem.Save();

                string filename = packageid + "." + version;
                string[] s = Directory.GetFiles(packages+ @"\"+filename);
                if (s.IsEmpty()) { System.Console.WriteLine("empty"); }
                else
                {
                    var nupkgFile = new PhysicalFileSystem(s[0]);
                    ZipPackage z = new ZipPackage(s[0]);
                    z.ExtractContents(nupkgFile, packages + @"\" + filename);
                }
                System.Console.WriteLine("Successfully updated");
                return true;
            }
            catch (Exception e)
            {
                System.Console.Write("failure");
                System.Console.Write(e.StackTrace);
                return false;
            }
        }
Exemple #22
0
        public NugetService(Solution solution, IEnumerable<string> remoteFeeds)
        {
            var repoBuilder = new PackageRepositoryBuilder();

            _remoteRepository = repoBuilder.BuildRemote(remoteFeeds);
            _localRepository = repoBuilder.BuildLocal(solution.PackagesFolder());
            _sourceRepository = repoBuilder.BuildSource(_remoteRepository, _localRepository);

            _fileSystem = new PhysicalFileSystem(solution.PackagesFolder());
            _pathResolver = new DefaultPackagePathResolver(_fileSystem);

            _console = new Console();
            _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){
                Logger = _console
            };

            _packages = new Cache<NugetDependency, IPackage>(dep =>
            {
                Install(dep);
                return _sourceRepository.FindPackage(dep.Name, new SemanticVersion(dep.Version));
            });
        }
        private static async Task DoWorkInWriterLockInternal(Project project, IVsHierarchy hierarchy, Action<MsBuildProject> action)
        {
            UnconfiguredProject unconfiguredProject = GetUnconfiguredProject((IVsProject)hierarchy);
            if (unconfiguredProject != null)
            {
                var service = unconfiguredProject.ProjectService.Services.ProjectLockService;
                if (service != null)
                {
                    // WriteLockAsync will move us to a background thread.
                    using (ProjectWriteLockReleaser x = await service.WriteLockAsync())
                    {
                        await x.CheckoutAsync(unconfiguredProject.FullPath);
                        ConfiguredProject configuredProject = await unconfiguredProject.GetSuggestedConfiguredProjectAsync();
                        MsBuildProject buildProject = await x.GetProjectAsync(configuredProject);

                        if (buildProject != null)
                        {
                            action(buildProject);
                        }

                        await x.ReleaseAsync();
                    }

                    // perform the save synchronously
                    await Task.Run(() =>
                    {
                        // move to the UI thread for the rest of this method
                        unconfiguredProject.ProjectService.Services.ThreadingPolicy.SwitchToUIThread();

                        var fileSystem = new PhysicalFileSystem(@"c:\");
                        fileSystem.MakeFileWritable(project.FullName);
                        project.Save();
                    }
                    );
                }
            }
        }
Exemple #24
0
 /// <summary>
 /// Creates a Machine Cache instance, assigns it to the instance variable and returns it.
 /// </summary>
 internal static MachineCache CreateDefault(Func<string> getCachePath)
 {
     IFileSystem fileSystem;
     try
     {
         string path = getCachePath();
         if (String.IsNullOrEmpty(path))
         {
             // If we don't get a path, use a null file system to make the cache object do nothing
             // This can happen when there is no LocalApplicationData folder
             fileSystem = NullFileSystem.Instance;
         }
         else
         {
             fileSystem = new PhysicalFileSystem(path);
         }
     }
     catch (SecurityException)
     {
         // We are unable to access the special directory. Create a machine cache using an empty file system
         fileSystem = NullFileSystem.Instance;
     }
     return new MachineCache(fileSystem);
 }
Exemple #25
0
        /// <summary>
        /// Initialize NugetStore using <paramref name="rootDirectory"/> as location of the local copies,
        /// and a configuration file <paramref name="configFile"/> as well as an override configuration
        /// file <paramref name="overrideFile"/> where all settings of <paramref name="overrideFile"/> also
        /// presents in <paramref name="configFile"/> take precedence.
        /// </summary>
        /// <param name="rootDirectory">The location of the Nuget store.</param>
        /// <param name="configFile">The configuration file name for the Nuget store, or <see cref="DefaultConfig"/> if not specified.</param>
        /// <param name="overrideFile">The override configuration file name for the Nuget store, or <see cref="OverrideConfig"/> if not specified.</param>
        public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig)
        {
            if (rootDirectory == null)
            {
                throw new ArgumentNullException(nameof(rootDirectory));
            }
            if (configFile == null)
            {
                throw new ArgumentNullException(nameof(configFile));
            }
            if (overrideFile == null)
            {
                throw new ArgumentNullException(nameof(overrideFile));
            }

            // First try the override file with custom settings
            var configFileName = overrideFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (!File.Exists(configFilePath))
            {
                // Override file does not exist, fallback to default config file
                configFileName = configFile;
                configFilePath = Path.Combine(rootDirectory, configFileName);

                if (!File.Exists(configFilePath))
                {
                    throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile));
                }
            }

            var rootFileSystem = new PhysicalFileSystem(rootDirectory);

            RootDirectory = rootFileSystem.Root;
            settings      = new Settings(rootFileSystem, configFileName, false);

            InstallPath = settings.GetValue(ConfigurationConstants.Config, RepositoryPathKey, true);
            if (!string.IsNullOrEmpty(InstallPath))
            {
                InstallPath = InstallPath.Replace('/', Path.DirectorySeparatorChar);
            }

            var mainPackageList = settings.GetValue(ConfigurationConstants.Config, MainPackagesKey, false);

            if (string.IsNullOrWhiteSpace(mainPackageList))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config");
            }
            MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            VsixPluginId = settings.GetValue(ConfigurationConstants.Config, VsixPluginKey, false);
            if (string.IsNullOrWhiteSpace(VsixPluginId))
            {
                throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config");
            }

            RepositoryPath = settings.GetValue(ConfigurationConstants.Config, RepositoryPathKey, false);
            if (string.IsNullOrWhiteSpace(RepositoryPath))
            {
                RepositoryPath = DefaultGamePackagesDirectory;
            }

            // Setup NugetCachePath in the cache folder
            CacheDirectory = Path.Combine(rootDirectory, "Cache");
            Environment.SetEnvironmentVariable("NuGetCachePath", CacheDirectory);

            var packagesFileSystem = new PhysicalFileSystem(InstallPath);

            PathResolver = new PackagePathResolver(packagesFileSystem);

            var packageSourceProvider = new PackageSourceProvider(settings);

            SourceRepository = packageSourceProvider.CreateAggregateRepository(new PackageRepositoryFactory(), true);

            var localRepo = new SharedPackageRepository(PathResolver, packagesFileSystem, rootFileSystem);

            manager = new NuGet.PackageManager(SourceRepository, PathResolver, packagesFileSystem, localRepo);
            manager.PackageInstalling   += OnPackageInstalling;
            manager.PackageInstalled    += OnPackageInstalled;
            manager.PackageUninstalling += OnPackageUninstalling;
            manager.PackageUninstalled  += OnPackageUninstalled;
        }
		void CreateFileSystem()
		{
			fileSystem = new PhysicalFileSystem(repositoryPath.PackageRepositoryPath);
		}
		public static bool IsPackageInstalled (this PackageReference packageReference, DotNetProject project)
		{
			var packagesPath = new SolutionPackageRepositoryPath (project);
			var fileSystem = new PhysicalFileSystem (packagesPath.PackageRepositoryPath);
			return packageReference.IsPackageInstalled (fileSystem);
		}
 private static ConfigurationDefaults InitializeInstance()
 {
     #if ASPNET50
     var commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
     #else
     var commonAppData = Environment.GetEnvironmentVariable("ProgramData");
     #endif
     var baseDirectory = Path.Combine(commonAppData, "NuGet");
     PhysicalFileSystem fileSystem = new PhysicalFileSystem(baseDirectory);
     return new ConfigurationDefaults(fileSystem, ConfigurationDefaultsFile);
 }
Exemple #29
0
        public static int Main(string[] args)
        {
            var console    = new Common.Console();
            var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(NuGetResources.InvalidArguments, commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);
                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                string    message;
                Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx == exception)
                {
                    // If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
                    message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(ex => ex.Message).Distinct(StringComparer.CurrentCulture));
                }
                else
                {
                    message = ExceptionUtility.Unwrap(exception).Message;
                }
                console.WriteError(message);
                return(1);
            }
            catch (Exception e)
            {
                console.WriteError(ExceptionUtility.Unwrap(e).Message);
                return(1);
            }
            return(0);
        }
Exemple #30
0
        public static int Main(string[] args)
        {
            DebugHelper.WaitForAttach(ref args);

            // This is to avoid applying weak event pattern usage, which breaks under Mono or restricted environments, e.g. Windows Azure Web Sites.
            EnvironmentUtility.SetRunningFromCommandLine();

            // Set output encoding to UTF8 if running on Unices. This is not needed on Windows.
            if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
            {
                System.Console.OutputEncoding = System.Text.Encoding.UTF8;
            }
            var console    = new Common.Console();
            var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());

            Func <Exception, string> getErrorMessage = e => e.Message;

            try
            {
                // Remove NuGet.exe.old
                RemoveOldFile(fileSystem);

                // Import Dependencies
                var p = new Program();
                p.Initialize(fileSystem, console);

                // Add commands to the manager
                foreach (ICommand cmd in p.Commands)
                {
                    p.Manager.RegisterCommand(cmd);
                }

                CommandLineParser parser = new CommandLineParser(p.Manager);

                // Parse the command
                ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;

                // Fallback on the help command if we failed to parse a valid command
                if (!ArgumentCountValid(command))
                {
                    // Get the command name and add it to the argument list of the help command
                    string commandName = command.CommandAttribute.CommandName;

                    // Print invalid command then show help
                    console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);

                    p.HelpCommand.ViewHelpForCommand(commandName);
                }
                else
                {
                    SetConsoleInteractivity(console, command as Command);

                    // When we're detailed, get the whole exception including the stack
                    // This is useful for debugging errors.
                    if (console.Verbosity == Verbosity.Detailed)
                    {
                        getErrorMessage = e => e.ToString();
                    }

                    command.Execute();
                }
            }
            catch (AggregateException exception)
            {
                string    message;
                Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
                if (unwrappedEx == exception)
                {
                    // If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
                    message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(getErrorMessage).Distinct(StringComparer.CurrentCulture));
                }
                else
                {
                    message = getErrorMessage(ExceptionUtility.Unwrap(exception));
                }
                console.WriteError(message);
                return(1);
            }
            catch (Exception e)
            {
                console.WriteError(getErrorMessage(ExceptionUtility.Unwrap(e)));
                return(1);
            }
            finally
            {
                OptimizedZipPackage.PurgeCache();
            }

            return(0);
        }
 private static ConfigurationDefaults InitializeInstance()
 {
     var baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "NuGet");
     PhysicalFileSystem fileSystem = new PhysicalFileSystem(baseDirectory);
     return new ConfigurationDefaults(fileSystem, ConfigurationDefaultsFile);
 }
Exemple #32
0
        void DownloadPackage(IPackage package, string fullPathToDownloadTo, NuGet.PackageDownloader directDownloader)
        {
            Log.VerboseFormat("Found package {0} version {1}", package.Id, package.Version);
            Log.Verbose("Downloading to: " + fullPathToDownloadTo);

            var dsp = package as DataServicePackage;
            if (dsp != null && directDownloader != null)
            {
                Log.Verbose("A direct download is possible; bypassing the NuGet machine cache");
                using (var targetFile = new FileStream(fullPathToDownloadTo, FileMode.CreateNew))
                    directDownloader.DownloadPackage(dsp.DownloadUrl, dsp, targetFile);
                return;
            }

            var physical = new PhysicalFileSystem(Path.GetDirectoryName(fullPathToDownloadTo));
            var local = new LocalPackageRepository(new FixedFilePathResolver(package.Id, fullPathToDownloadTo), physical);
            local.AddPackage(package);
        }
 private static ConfigurationDefaults InitializeInstance()
 {
     var machineWideSettingsDir = DnuEnvironment.GetFolderPath(DnuFolderPath.MachineWideSettingsBaseDirectory);
     PhysicalFileSystem fileSystem = new PhysicalFileSystem(machineWideSettingsDir);
     return new ConfigurationDefaults(fileSystem, ConfigurationDefaultsFile);
 }