public async override Task ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            string installPath = ResolveInstallPath();

            var packageSourceProvider = new NuGet.Configuration.PackageSourceProvider(Settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);

            IEnumerable<SourceRepository> primarySources;
            IEnumerable<SourceRepository> secondarySources;
            GetEffectiveSources(sourceRepositoryProvider, out primarySources, out secondarySources);

            if(Arguments.Count == 0)
            {
                throw new InvalidOperationException(NuGetResources.InstallCommandPackageIdMustBeProvided);
            }
            string packageId = Arguments[0];
            NuGetPackageManager packageManager = new NuGetPackageManager(sourceRepositoryProvider, installPath);
            ResolutionContext resolutionContext = new ResolutionContext(dependencyBehavior: DependencyBehavior, includePrelease: Prerelease);
            FolderNuGetProject nugetProject = new FolderNuGetProject(installPath);
            nugetProject.PackageSaveMode = EffectivePackageSaveMode;

            if (Version == null)
            {
                await packageManager.InstallPackageAsync(nugetProject, packageId, resolutionContext, new Common.Console(),
                    primarySources, secondarySources, CancellationToken.None);
            }
            else
            {
                await packageManager.InstallPackageAsync(nugetProject, new PackageIdentity(packageId, new NuGetVersion(Version)), resolutionContext,
                    new Common.Console(), primarySources, secondarySources, CancellationToken.None);
            }           
        }
        /// <summary>
        /// Determine if active package source is http source
        /// </summary>
        /// <param name="packageSourceProvider"></param>
        /// <returns></returns>
        public static bool IsHttpSource(PackageSourceProvider packageSourceProvider)
        {
            // TODO: Fix the logic here
            var packageSources = packageSourceProvider.LoadPackageSources();
            var activeSource = packageSources.FirstOrDefault();
            if (activeSource == null)
            {
                return false;
            }

            //if (activeSource.IsAggregate())
            if (activeSource.IsEnabled)
            {
                return packageSourceProvider.LoadPackageSources().Any(s => IsHttpSource(s.Source));
            }
            // For API V3, the source could be a local .json file.
            else if (activeSource.Source.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
            else
            {
                return IsHttpSource(activeSource.Source);
            }
        }
Example #3
0
        public async override Task ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            string installPath = ResolveInstallPath();

            var packageSourceProvider    = new NuGet.Configuration.PackageSourceProvider(Settings);
            var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);

            IEnumerable <SourceRepository> primarySources;
            IEnumerable <SourceRepository> secondarySources;

            GetEffectiveSources(sourceRepositoryProvider, out primarySources, out secondarySources);

            if (Arguments.Count == 0)
            {
                throw new InvalidOperationException(NuGetResources.InstallCommandPackageIdMustBeProvided);
            }
            string packageId = Arguments[0];
            NuGetPackageManager packageManager    = new NuGetPackageManager(sourceRepositoryProvider, installPath);
            ResolutionContext   resolutionContext = new ResolutionContext(dependencyBehavior: DependencyBehavior, includePrelease: Prerelease);
            FolderNuGetProject  nugetProject      = new FolderNuGetProject(installPath);

            nugetProject.PackageSaveMode = EffectivePackageSaveMode;

            if (Version == null)
            {
                await packageManager.InstallPackageAsync(nugetProject, packageId, resolutionContext, new Common.Console(),
                                                         primarySources, secondarySources, CancellationToken.None);
            }
            else
            {
                await packageManager.InstallPackageAsync(nugetProject, new PackageIdentity(packageId, new NuGetVersion(Version)), resolutionContext,
                                                         new Common.Console(), primarySources, secondarySources, CancellationToken.None);
            }
        }
Example #4
0
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // Used only for versions before 3.0
            this.oldRootDirectory = oldRootDirectory;

            settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);

            // Remove obsolete sources
            RemoveDeletedSources(settings, "Xenko Dev");
            // Note the space: we want to keep "Stride Dev" but not "Stride Dev {PATH}\bin\packages" anymore
            RemoveSources(settings, "Stride Dev ");

            settings.SaveToDisk();

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext.UserPackageFolder, oldRootDirectory != null ? pathContext.FallbackPackageFolders.Concat(new[] { oldRootDirectory }) : pathContext.FallbackPackageFolders);
            var packageSourceProvider = new PackageSourceProvider(settings);

            var availableSources = packageSourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <PackageSource>();

            packageSources.AddRange(availableSources);
            PackageSources = packageSources;

            // Setup source provider as a V3 only.
            sourceRepositoryProvider = new NugetSourceRepositoryProvider(packageSourceProvider, this);
        }
Example #5
0
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // Used only for versions before 3.0
            this.oldRootDirectory = oldRootDirectory;

            settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);

            // Add dev source
            CheckPackageSource("Xenko", DefaultPackageSource);

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext.UserPackageFolder, oldRootDirectory != null ? pathContext.FallbackPackageFolders.Concat(new[] { oldRootDirectory }) : pathContext.FallbackPackageFolders);
            var packageSourceProvider = new PackageSourceProvider(settings);

            var availableSources = packageSourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <PackageSource>();

            packageSources.AddRange(availableSources);
            PackageSources = packageSources;

            // Setup source provider as a V3 only.
            sourceRepositoryProvider = new NugetSourceRepositoryProvider(packageSourceProvider, this);
        }
        private void RunScript(string scriptText, params string[] parameters)
        {
            ISettings settings = Settings.LoadDefaultSettings(Environment.ExpandEnvironmentVariables("%systemdrive%"), null, null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var packageSources = packageSourceProvider.LoadPackageSources();
            SourceRepositoryProvider provider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);

            PowerShell ps = PowerShell.Create();
            ps.Runspace = _runSpace;
            ps.Commands.AddCommand(scriptText);

            // Run the scriptText
            var testCommand = ps.Commands.Commands[0];
            testCommand.Parameters.Add("Id", parameters[0]);
            testCommand.Parameters.Add("Version", parameters[1]);
            // Add as a test hook to pass in the provider
            testCommand.Parameters.Add("SourceRepositoryProvider", provider);
            testCommand.Parameters.Add("VsSolutionManager", new TestSolutionManager());

            // Add out-string
            ps.Commands.AddCommand("Out-String");

            // execute the script
            foreach (PSObject result in ps.Invoke())
            {
                Console.WriteLine(result.ToString());
            }

            // close the runspace
            _runSpace.Close();
        }
        public async override Task ExecuteCommand()
        {
            IEnumerable<SourceRepository> sourceRepository;
            if (Source.Any())
            {
                List<SourceRepository> sourceList = new List<SourceRepository>();
                foreach (var source in Source)
                {
                    sourceList.Add(new SourceRepository(new PackageSource(source), ResourceProviders));
                }
                sourceRepository = sourceList;
            }
            else
            {
                var packageSourceProvider = new PackageSourceProvider(Settings);
                var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);
                sourceRepository = sourceRepositoryProvider.GetRepositories();
            }

            var selfUpdater = new SelfUpdater(sourceRepository.FirstOrDefault())
            {
                Console = Console
            };

            await selfUpdater.UpdateSelf();
        }
        public void TestSourceRepoPackageSourcesChanged2()
        {
            // Arrange
            var settingsPath = TestPackageSourceSettings.CreateAndGetSettingFilePath();
            var settings = new Settings(settingsPath);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(packageSourceProvider);

            // Act
            var oldEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Assert
            Assert.Equal(1, oldEffectivePackageSources.Count);
            Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, oldEffectivePackageSources[0].PackageSource.Source);

            // Main Act
            var newPackageSources = new List<PackageSource>() { TestSourceRepositoryUtility.V3PackageSource,
                TestSourceRepositoryUtility.V2PackageSource };
            packageSourceProvider.SavePackageSources(newPackageSources);

            var newEffectivePackageSources = sourceRepositoryProvider.GetRepositories().ToList();

            // Main Assert
            Assert.Equal(2, newEffectivePackageSources.Count);
            Assert.Equal(TestSourceRepositoryUtility.V3PackageSource.Source, newEffectivePackageSources[0].PackageSource.Source);
            Assert.Equal(TestSourceRepositoryUtility.V2PackageSource.Source, newEffectivePackageSources[1].PackageSource.Source);

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(settingsPath);
        }
            public NuGetProject(List <string> packagesList, string packagesPath, ProjectFile projectFile, ILog log)
            {
                this.log          = log;
                this.packagesList = packagesList;
                this.projectFile  = projectFile;
                installedPackages = new HashSet <PackageIdentity>();
                var sourceProvider           = new PackageSourceProvider(Settings.LoadDefaultSettings(null));
                var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);

                repositories = sourceProvider.LoadPackageSources().Select(sourceRepositoryProvider.CreateRepository)
                               .ToList();
                logger = new Console();

                var projectFilePath = projectFile.FilePath;

                var msbuildDirectory =
                    Path.GetDirectoryName(ModuleBuilderHelper.FindMsBuild(null, "Cement NuGet Package Installer"));

                projectContext = new ConsoleProjectContext(logger);
                projectSystem  = new MSBuildProjectSystem(
                    msbuildDirectory,
                    projectFilePath,
                    projectContext);
                var projectFolder = Path.GetDirectoryName(projectFilePath);

                project = new MSBuildNuGetProject(projectSystem, packagesPath, projectFolder);
            }
Example #10
0
        public static IEnumerable <PackageSource> GetEnabledSources(ISettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            return(PackageSourceProvider.LoadPackageSources(settings).Where(e => e.IsEnabled == true).ToList());
        }
Example #11
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>
        public NugetStore(string rootDirectory, string configFile = DefaultConfig)
        {
            RootDirectory = rootDirectory ?? throw new ArgumentNullException(nameof(rootDirectory));

            settings = NuGet.Configuration.Settings.LoadDefaultSettings(rootDirectory);

            // Add dev source
            Directory.CreateDirectory(Environment.ExpandEnvironmentVariables(DevSource));
            CheckPackageSource("Xenko Dev", DevSource);
            CheckPackageSource("Xenko", DefaultPackageSource);

            // Override file does not exist, fallback to default config file
            var configFileName = configFile;
            var configFilePath = Path.Combine(rootDirectory, configFileName);

            if (File.Exists(configFilePath))
            {
                localSettings = NuGet.Configuration.Settings.LoadDefaultSettings(rootDirectory, configFileName, machineWideSettings: null);

                // Replicate packageSources in user config so that NuGet restore can find them as well
                foreach (var x in localSettings.GetSettingValues("packageSources", true))
                {
                    CheckPackageSource(x.Key, x.Value);
                }
            }

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext);
            var packageSourceProvider = new PackageSourceProvider(settings);

            var availableSources = packageSourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <PackageSource>();

            packageSources.AddRange(availableSources);
            PackageSources = packageSources;

            // Setup source provider as a V3 only.
            sourceRepositoryProvider = new NugetSourceRepositoryProvider(packageSourceProvider, this);

            manager = new NuGetPackageManager(sourceRepositoryProvider, settings, InstallPath);
            // Override PackagePathResolver
            // Workaround for https://github.com/NuGet/Home/issues/6639
            manager.PackagesFolderNuGetProject.GetType().GetProperty("PackagePathResolver", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(manager.PackagesFolderNuGetProject, new PackagePathResolverV3(InstallPath));

            // Obsolete (Xenko 2.x support)
            InstallPathV2  = Path.Combine(RootDirectory, DefaultGamePackagesDirectory);
            managerV2      = new NuGetPackageManager(sourceRepositoryProvider, settings, InstallPathV2);
            PathResolverV2 = new PackagePathResolver(InstallPathV2);
        }
Example #12
0
        /// <summary>
        /// Create a source provider for the given sources and with the extra providers.
        /// </summary>
        public static ISourceRepositoryProvider CreateProvider(IEnumerable<INuGetResourceProvider> resourceProviders, IEnumerable<PackageSource> sources)
        {
            if (sources == null)
            {
                throw new ArgumentNullException("sources");
            }

            if (resourceProviders == null)
            {
                throw new ArgumentNullException("resourceProviders");
            }

            PackageSourceProvider sourceProvider = new PackageSourceProvider(NullSettings.Instance, sources, Enumerable.Empty<PackageSource>());

            return new SourceRepositoryProvider(sourceProvider, CreateLazy(resourceProviders));
        }
Example #13
0
        public SourceRepositoryProvider(ISettings settings)
        {
            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Create the set of default v2 and v3 resource providers
            _resourceProviders = new List<Lazy<INuGetResourceProvider>>();
            _resourceProviders.AddRange(global::NuGet.Protocol.Core.v2.FactoryExtensionsV2.GetCoreV2(Repository.Provider));
            _resourceProviders.AddRange(global::NuGet.Protocol.Core.v3.FactoryExtensionsV2.GetCoreV3(Repository.Provider));

            // Add the default sources
            foreach (string defaultSource in DefaultSources)
            {
                AddDefaultRepository(defaultSource);
            }
        }
Example #14
0
        public NuGetViewModel()
        {
            _settings = Settings.LoadDefaultSettings(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                configFileName: null,
                machineWideSettings: new CommandLineMachineWideSettings());

            _sourceProvider = new PackageSourceProvider(_settings);

            GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);

            _packageSources = GetPackageSources();

            _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(_sourceProvider);

            _initializationTask = new Lazy <Task>(Initialize);
        }
Example #15
0
        public NuGetViewModel([Import(AllowDefault = true)] IExceptionManager?exceptionManager, IApplicationSettings appSettings)
        {
            try
            {
                var settings = LoadSettings();
                ConfigPath          = settings.GetConfigFilePaths().First();
                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance, nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
            }
            catch (Exception e)
            {
                _initializationException = ExceptionDispatchInfo.Capture(e);

                ConfigPath          = string.Empty;
                GlobalPackageFolder = string.Empty;
            }

            Settings LoadSettings()
            {
                Settings?settings = null;

                const int retries = 3;

                for (var i = 1; i <= retries; i++)
                {
                    try
                    {
                        settings = new Settings(appSettings.GetDefaultDocumentPath(), "RoslynPad.nuget.config");
                    }
                    catch (NuGetConfigurationException ex)
                    {
                        if (i == retries)
                        {
                            exceptionManager?.ReportError(ex);
                            throw;
                        }
                    }
                }

                return(settings !);
            }
        }
Example #16
0
        public NuGetViewModel()
        {
            _settings = Settings.LoadDefaultSettings(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
                configFileName: null,
                machineWideSettings: new CommandLineMachineWideSettings());

            _sourceProvider = new PackageSourceProvider(_settings);

            GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);

            _packageSources = GetPackageSources();

            _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(_sourceProvider);

            _initializationTask = new Lazy<Task>(Initialize);

        }
        public void GetDefaultPackageSources_LocalizatedPackagesourceKeys_ConsideredDiffererent()
        {
            // Arrange
            using (var mockBaseDirectory = TestDirectory.CreateInTemp())
            {
                var configurationDefaultsContent = @"
<configuration>
    <packageSources>
        <add key='encyclopaedia' value='http://contoso.com/packages1/' />
        <add key='encyclopædia' value='http://contoso.com/packages2/' />
    </packageSources>
</configuration>";

                var config = @"
<configuration>
    <packageSources>
        <add key='v2' value='http://www.nuget.org/api/v2/' />
    </packageSources>
</configuration>";

                File.WriteAllText(Path.Combine(mockBaseDirectory, "NuGet.Config"), config);
                var settings = Settings.LoadSettings(mockBaseDirectory,
                                                     configFileName: null,
                                                     machineWideSettings: null,
                                                     loadUserWideSettings: false,
                                                     useTestingGlobalPath: false);
                ConfigurationDefaults ConfigurationDefaults = GetConfigurationDefaults(configurationDefaultsContent, mockBaseDirectory);

                List <PackageSource> defaultSources = ConfigurationDefaults.DefaultPackageSources.ToList();
                var packageSourceProvider           = new PackageSourceProvider(settings, ConfigurationDefaults.DefaultPackageSources);

                // Act
                List <PackageSource> packageSources = packageSourceProvider.LoadPackageSources().ToList();

                // Assert
                Assert.Equal(3, packageSources.Count());
                Assert.Equal(2, defaultSources.Count());
                Assert.Equal("v2", packageSources[0].Name);
                Assert.Equal("encyclopaedia", packageSources[1].Name);
                Assert.Equal("encyclopaedia", defaultSources[0].Name);
                Assert.Equal("encyclopædia", packageSources[2].Name);
                Assert.Equal("encyclopædia", defaultSources[1].Name);
            }
        }
        public void GetDefaultPackageSourcesFromSourceProvider()
        {
            // Arrange
            using (var mockBaseDirectory = TestDirectory.CreateInTemp())
            {
                var configurationDefaultsContent = @"
<configuration>
    <packageSources>
        <add key='Contoso Package Source' value='http://contoso.com/packages/' />
    </packageSources>
      <config>
        <add key='DefaultPushSource' value='http://contoso.com/packages/' />
    </config>
</configuration>";
                var config = @"
<configuration>
    <packageSources>
        <add key='v2' value='http://www.nuget.org/api/v2/' />
    </packageSources>
</configuration>";

                File.WriteAllText(Path.Combine(mockBaseDirectory, "NuGet.Config"), config);
                var settings = Settings.LoadSettings(mockBaseDirectory,
                                                     configFileName: null,
                                                     machineWideSettings: null,
                                                     loadUserWideSettings: false,
                                                     useTestingGlobalPath: false);
                ConfigurationDefaults ConfigurationDefaults = GetConfigurationDefaults(configurationDefaultsContent, mockBaseDirectory);

                var packageSourceProvider = new PackageSourceProvider(settings, ConfigurationDefaults.DefaultPackageSources);

                // Act
                List <PackageSource> packageSources = packageSourceProvider.LoadPackageSources().ToList();

                // Assert
                Assert.Equal("http://contoso.com/packages/", ConfigurationDefaults.DefaultPushSource);
                Assert.Equal(2, packageSources.Count());
                Assert.Equal("v2", packageSources[0].Name);
                Assert.Equal("Contoso Package Source", packageSources[1].Name);
            }
        }
        public async override Task ExecuteCommand()
        {
            IEnumerable<SourceRepository> sourceRepository;
            string searchTerm = Arguments != null ? Arguments.FirstOrDefault() : null;
            if (Source.Any())
            {
                List<SourceRepository> sourceList = new List<SourceRepository>();
                foreach (var source in Source)
                {
                    sourceList.Add(new SourceRepository(new PackageSource(source), ResourceProviders));
                }
                sourceRepository = sourceList;
            }
            else
            {
                var packageSourceProvider = new PackageSourceProvider(Settings);
                var sourceRepositoryProvider = new SourceRepositoryProvider(packageSourceProvider, ResourceProviders);
                sourceRepository = sourceRepositoryProvider.GetRepositories();
            }

            foreach (var eachRepository in sourceRepository)
            {
                var searchResource = await eachRepository.GetResourceAsync<SimpleSearchResource>();
                if (searchResource != null)
                {
                    int page = 100;
                    int skip = 0;

                    do
                    {
                        var packages = await searchResource.Search(searchTerm, new SearchFilter() { IncludePrerelease = Prerelease, SupportedFrameworks = new string[0] }, skip, page, CancellationToken.None);
                        skip += page;
                        if (!packages.Any()) break;
                        PrintPackages(packages);
                    }
                    while (true);

                }
            }
        }
        /// <summary>
        /// Initialize a new instance of <see cref="NugetStore"/>.
        /// </summary>
        /// <param name="oldRootDirectory">The location of the Nuget store.</param>
        public NugetStore(string oldRootDirectory)
        {
            // Workaround for https://github.com/NuGet/Home/issues/8120
            //  set timeout to something much higher than 100 sec
            var defaultRequestTimeoutField = typeof(HttpSourceRequest).GetField(nameof(HttpSourceRequest.DefaultRequestTimeout), BindingFlags.Static | BindingFlags.Public);

            if (defaultRequestTimeoutField != null)
            {
                defaultRequestTimeoutField.SetValue(null, TimeSpan.FromMinutes(60));
            }

            // Used only for versions before 3.0
            this.oldRootDirectory = oldRootDirectory;

            settings = NuGet.Configuration.Settings.LoadDefaultSettings(null);

            // Remove obsolete sources
            RemoveDeletedSources(settings, "Xenko Dev");
            // Note the space: we want to keep "Stride Dev" but not "Stride Dev {PATH}\bin\packages" anymore
            RemoveSources(settings, "Stride Dev ");
            // Add Stride package store (still used for Xenko up to 3.0)
            CheckPackageSource("Stride", DefaultPackageSource);
            settings.SaveToDisk();

            InstallPath = SettingsUtility.GetGlobalPackagesFolder(settings);

            var pathContext = NuGetPathContext.Create(settings);

            InstalledPathResolver = new FallbackPackagePathResolver(pathContext.UserPackageFolder, oldRootDirectory != null ? pathContext.FallbackPackageFolders.Concat(new[] { oldRootDirectory }) : pathContext.FallbackPackageFolders);
            var packageSourceProvider = new PackageSourceProvider(settings);

            var availableSources = packageSourceProvider.LoadPackageSources().Where(source => source.IsEnabled);
            var packageSources   = new List <PackageSource>();

            packageSources.AddRange(availableSources);
            PackageSources = packageSources;

            // Setup source provider as a V3 only.
            sourceRepositoryProvider = new NugetSourceRepositoryProvider(packageSourceProvider, this);
        }
Example #21
0
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
        public NuGetViewModel()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            try {
                var settings = Settings.LoadDefaultSettings(
                    root: null,
                    configFileName: null,
                    machineWideSettings: new XPlatMachineWideSetting());

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = settings.GetConfigFilePaths();
                _packageSources     = SettingsUtility.GetEnabledSources(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance, nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
            }
            catch (Exception e) {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Example #22
0
        public NuGetViewModel()
        {
            try
            {
                _settings = Settings.LoadDefaultSettings(
                    root: null,
                    configFileName: null,
                    machineWideSettings: new CommandLineMachineWideSettings());

                _sourceProvider = new PackageSourceProvider(_settings);

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(_settings);

                _packageSources = GetPackageSources();

                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(_sourceProvider);
            }
            catch (Exception e)
            {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
Example #23
0
        public NuGetViewModel(ITelemetryProvider telemetryProvider)
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
        {
            try
            {
                ISettings settings;

                try
                {
                    settings = Settings.LoadDefaultSettings(
                        root: null,
                        configFileName: null,
                        machineWideSettings: new XPlatMachineWideSetting());
                }
                catch (NuGetConfigurationException ex)
                {
                    telemetryProvider.ReportError(ex);

                    // create default settings using a non-existent config file
                    settings = new Settings(nameof(RoslynPad));
                }

                GlobalPackageFolder = SettingsUtility.GetGlobalPackagesFolder(settings);
                _configFilePaths    = SettingsUtility.GetConfigFilePaths(settings);
                _packageSources     = SettingsUtility.GetEnabledSources(settings);

                DefaultCredentialServiceUtility.SetupDefaultCredentialService(NullLogger.Instance, nonInteractive: false);

                var sourceProvider = new PackageSourceProvider(settings);
                _sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(sourceProvider);
            }
            catch (Exception e)
            {
                _initializationException = ExceptionDispatchInfo.Capture(e);
            }
        }
		public MonoDevelopPackageSourceProvider (ISettings settings)
		{
			packageSourceProvider = new PackageSourceProvider (settings);
		}
        /// <summary>
        /// Creates a repo provider for the given sources. If null is passed all sources will be returned.
        /// </summary>
        private ISourceRepositoryProvider GetSources(IEnumerable<string> sources)
        {
            PreinstalledRepositoryProvider provider = new PreinstalledRepositoryProvider(ErrorHandler, _sourceRepositoryProvider);

            IPackageSourceProvider sourceProvider = new PackageSourceProvider(_settings);

            PackageSource[] packageSources = sourceProvider.LoadPackageSources().ToArray();

            // add everything enabled if null
            if (sources == null)
            {
                foreach (var packageSource in packageSources)
                {
                    if (packageSource.IsEnabled)
                    {
                        foreach (string source in sources)
                        {
                            provider.AddFromSource(GetSource(source));
                        }
                    }
                }
            }
            else
            {
                // TODO: disallow disabled sources even if they were provided by the caller?
                foreach (string source in sources)
                {
                    provider.AddFromSource(GetSource(source));
                }
            }

            return provider;
        }
Example #26
0
        public int Main(string[] args)
        {
#if DEBUG
            if (args.Contains("--debug"))
            {
                args = args.Skip(1).ToArray();
                System.Diagnostics.Debugger.Launch();
            }
#endif

            // Set up logging
            _log = new CommandOutputLogger();

            var app = new CommandLineApplication();
            app.Name = "nuget3";
            app.FullName = ".NET Package Manager";
            app.HelpOption("-h|--help");
            app.VersionOption("--version", GetType().GetTypeInfo().Assembly.GetName().Version.ToString());

            app.Command("restore", restore =>
                {
                    restore.Description = "Restores packages for a project and writes a lock file";

                    var sources = restore.Option("-s|--source <source>", "Specifies a NuGet package source to use during the restore", CommandOptionType.MultipleValue);
                    var packagesDirectory = restore.Option("--packages <packagesDirectory>", "Directory to install packages in", CommandOptionType.SingleValue);
                    var parallel = restore.Option("-p|--parallel <noneOrNumberOfParallelTasks>", $"The number of concurrent tasks to use when restoring. Defaults to {RestoreRequest.DefaultDegreeOfConcurrency}; pass 'none' to run without concurrency.", CommandOptionType.SingleValue);
                    var projectFile = restore.Argument("[project file]", "The path to the project to restore for, either a project.json or the directory containing it. Defaults to the current directory");

                    restore.OnExecute(async () =>
                        {
                            // Figure out the project directory
                            IEnumerable<string> externalProjects = null;

                            PackageSpec project;
                            var projectPath = Path.GetFullPath(projectFile.Value ?? ".");
                            if (string.Equals(PackageSpec.PackageSpecFileName, Path.GetFileName(projectPath), StringComparison.OrdinalIgnoreCase))
                            {
                                _log.LogVerbose($"Reading project file {projectFile.Value}");
                                projectPath = Path.GetDirectoryName(projectPath);
                                project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(projectFile.Value), Path.GetFileName(projectPath), projectFile.Value);
                            }
                            else if (MsBuildUtility.IsMsBuildBasedProject(projectPath))
                            {
#if DNXCORE50
                                throw new NotSupportedException();
#else
                                externalProjects = MsBuildUtility.GetProjectReferences(projectPath);

                                projectPath = Path.GetDirectoryName(Path.GetFullPath(projectPath));
                                var packageSpecFile = Path.Combine(projectPath, PackageSpec.PackageSpecFileName);
                                project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(packageSpecFile), Path.GetFileName(projectPath), projectFile.Value);
                                _log.LogVerbose($"Reading project file {projectFile.Value}");
#endif
                            }
                            else
                            {
                                var file = Path.Combine(projectPath, PackageSpec.PackageSpecFileName);

                                _log.LogVerbose($"Reading project file {file}");
                                project = JsonPackageSpecReader.GetPackageSpec(File.ReadAllText(file), Path.GetFileName(projectPath), file);
                            }
                            _log.LogVerbose($"Loaded project {project.Name} from {project.FilePath}");

                            // Resolve the root directory
                            var rootDirectory = PackageSpecResolver.ResolveRootDirectory(projectPath);
                            _log.LogVerbose($"Found project root directory: {rootDirectory}");

                            // Resolve the packages directory
                            var packagesDir = packagesDirectory.HasValue() ?
                                packagesDirectory.Value() :
                                Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), ".nuget", "packages");
                            _log.LogVerbose($"Using packages directory: {packagesDir}");

                            var packageSources = sources.Values.Select(s => new PackageSource(s));
                            if (!packageSources.Any())
                            {
                                var settings = Settings.LoadDefaultSettings(projectPath,
                                    configFileName: null,
                                    machineWideSettings: null);
                                var packageSourceProvider = new PackageSourceProvider(settings);
                                packageSources = packageSourceProvider.LoadPackageSources();
                            }

                            var request = new RestoreRequest(
                                project,
                                packageSources,
                                packagesDir);

                            if (externalProjects != null)
                            {
                                foreach (var externalReference in externalProjects)
                                {
                                    request.ExternalProjects.Add(
                                        new ExternalProjectReference(
                                            externalReference,
                                            Path.Combine(Path.GetDirectoryName(externalReference), PackageSpec.PackageSpecFileName),
                                            projectReferences: Enumerable.Empty<string>()));
                                }
                            }


                            // Run the restore
                            if (parallel.HasValue())
                            {
                                int parallelDegree;
                                if (string.Equals(parallel.Value(), "none", StringComparison.OrdinalIgnoreCase))
                                {
                                    request.MaxDegreeOfConcurrency = 1;
                                }
                                else if (int.TryParse(parallel.Value(), out parallelDegree))
                                {
                                    request.MaxDegreeOfConcurrency = parallelDegree;
                                }
                            }
                            if (request.MaxDegreeOfConcurrency <= 1)
                            {
                                _log.LogInformation("Running non-parallel restore");
                            }
                            else
                            {
                                _log.LogInformation($"Running restore with {request.MaxDegreeOfConcurrency} concurrent jobs");
                            }
                            var command = new RestoreCommand(_log);
                            var sw = Stopwatch.StartNew();
                            var result = await command.ExecuteAsync(request);
                            sw.Stop();

                            _log.LogInformation($"Restore completed in {sw.ElapsedMilliseconds:0.00}ms!");

                            return 0;
                        });
                });

            app.Command("diag", diag =>
                {
                    diag.Description = "Diagnostic commands for debugging package dependency graphs";
                    diag.Command("lockfile", lockfile =>
                        {
                            lockfile.Description = "Dumps data from the project lock file";

                            var project = lockfile.Option("--project <project>", "Path containing the project lockfile, or the patht to the lockfile itself", CommandOptionType.SingleValue);
                            var target = lockfile.Option("--target <target>", "View information about a specific project target", CommandOptionType.SingleValue);
                            var library = lockfile.Argument("<library>", "Optionally, get detailed information about a specific library");

                            lockfile.OnExecute(() =>
                                {
                                    var diagnostics = new DiagnosticCommands(_log);
                                    var projectFile = project.HasValue() ? project.Value() : Path.GetFullPath(".");
                                    return diagnostics.Lockfile(projectFile, target.Value(), library.Value);
                                });
                        });
                    diag.OnExecute(() =>
                        {
                            diag.ShowHelp();
                            return 0;
                        });
                });

            app.OnExecute(() =>
                {
                    app.ShowHelp();
                    return 0;
                });

            return app.Execute(args);
        }
        /// <summary>
        /// Determine is any source is local source
        /// </summary>
        /// <param name="packageSourceProvider"></param>
        /// <param name="localSource"></param>
        /// <returns></returns>
        public static bool IsAnySourceLocal(PackageSourceProvider packageSourceProvider, out string localSource)
        {
            localSource = string.Empty;
            if (packageSourceProvider != null)
            {
                //If any of the active sources is local folder and is available, return true
                IEnumerable<PackageSource> sources = null;
                var packageSources = packageSourceProvider.LoadPackageSources();
                var activeSource = packageSources.FirstOrDefault();
                //PackageSource activeSource = packageSourceProvider.ActivePackageSource;

                //if (activeSource.IsAggregate())
                if (activeSource.IsEnabled)
                {
                    sources = packageSourceProvider.LoadPackageSources();
                    foreach (PackageSource s in sources)
                    {
                        if (IsLocal(s.Source))
                        {
                            localSource = s.Source;
                            return true;
                        }
                    }
                }
                else
                {
                    if (IsLocal(activeSource.Source)) return true;
                }
            }
            return false;
        }
        /// <summary>
        /// Determine if any source is available 
        /// </summary>
        /// <param name="packageSourceProvider"></param>
        /// <param name="checkHttp"></param>
        /// <returns></returns>
        public static bool IsAnySourceAvailable(PackageSourceProvider packageSourceProvider, bool checkHttp)
        {
            //If any of the enabled sources is http, return true
            if (checkHttp)
            {
                bool isHttpSource;
                isHttpSource = UriHelper.IsHttpSource(packageSourceProvider);
                if (isHttpSource)
                {
                    return true;
                }
            }

            if (packageSourceProvider != null)
            {
                //If any of the active sources is UNC share or local folder and is available, return true
                IEnumerable<PackageSource> sources = null;
                //PackageSource activeSource = packageSourceProvider.ActivePackageSource;
                var packageSources = packageSourceProvider.LoadPackageSources();
                var activeSource = packageSources.FirstOrDefault();

                //if (activeSource.IsAggregate())
                if (activeSource.IsEnabled)
                {
                    sources = packageSourceProvider.LoadPackageSources();
                    foreach (PackageSource s in sources)
                    {
                        if (IsLocal(s.Source) || IsUNC(s.Source)) return true;
                    }
                }
                else
                {
                    if (IsLocal(activeSource.Source) || IsUNC(activeSource.Source)) return true;
                }
            }

            //If none of the above matched, return false
            return false;
        }
        /// <summary>
        /// Determine if source is http source
        /// </summary>
        /// <param name="source"></param>
        /// <param name="packageSourceProvider"></param>
        /// <returns></returns>
        public static bool IsHttpSource(string source, PackageSourceProvider packageSourceProvider)
        {
            if (source != null)
            {
                if (IsHttpSource(source))
                {
                    return true;
                }

                var packageSource = packageSourceProvider.LoadPackageSources()
                                                          .FirstOrDefault(p => p.Name.Equals(source, StringComparison.CurrentCultureIgnoreCase));
                return (packageSource != null) && IsHttpSource(packageSource.Source);
            }

            return IsHttpSource(packageSourceProvider);
        }
Example #30
0
        public static IEnumerable <PackageSource> GetEnabledSources(ISettings settings)
        {
            var provider = new PackageSourceProvider(settings);

            return(provider.LoadPackageSources().Where(e => e.IsEnabled == true).ToList());
        }