示例#1
0
        private static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var builder = AppBuilder.Configure <App>().UseReactiveUI().AvalonStudioPlatformDetect().AfterSetup(async _ =>
            {
                Platform.Initialise();

                PackageSources.InitialisePackageSources();

                ExtensionManager.Initialise();

                var extensionManager = IoC.Get <ExtensionManager>();
                var extensions       = extensionManager.GetInstalledExtensions();
                var container        = CompositionRoot.CreateContainer(extensions);

                ShellViewModel.Instance = container.GetExport <ShellViewModel>();

                await PackageManager.LoadAssetsAsync();
            });

            InitializeLogging();

            builder.Start <MainWindow>();
        }
示例#2
0
        private static int Main(string[] args)
        {
            Platform.Initialise();

            PackageSources.InitialisePackageSources();

            var container = CompositionRoot.CreateContainer();

            MinimalShell.Instance = container.GetExportedValue <IShell>();

            Console.WriteLine("Avalon Build - {0} - {1}  - {2}", releaseName, version, Platform.PlatformIdentifier);

            var result = Parser.Default.ParseArguments
                         <AddOptions, RemoveOptions, AddReferenceOptions, BuildOptions, CleanOptions, CreateOptions, PackageOptions, TestOptions>(args).MapResult(
                (BuildOptions opts) => RunBuild(opts),
                (AddOptions opts) => RunAdd(opts),
                (AddReferenceOptions opts) => RunAddReference(opts),
                (PackageOptions opts) => RunInstallPackage(opts),
                (CleanOptions opts) => RunClean(opts),
                (CreateOptions opts) => RunCreate(opts),
                (RemoveOptions opts) => RunRemove(opts),
                (TestOptions opts) => RunTest(opts),
                errs => 1);

            return(result - 1);
        }
示例#3
0
        /// <summary>
        /// Returns updates for packages from the repository
        /// </summary>
        /// <param name="packageName">Package to look for updates</param>
        /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
        /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns></returns>
        public async Task <IEnumerable <NugetPackage> > GetUpdates(PackageName packageName, bool includePrerelease, bool includeAllVersions, CancellationToken cancellationToken)
        {
            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrerelease,
                true,
                includeAllVersions ? VersionConstraints.None : VersionConstraints.ExactMajor | VersionConstraints.ExactMinor);

            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

            var res = new List <NugetPackage>();

            using (var context = new SourceCacheContext())
            {
                foreach (var repo in repositories)
                {
                    try
                    {
                        var metadataResource = await repo.GetResourceAsync <PackageMetadataResource>(cancellationToken);

                        var metadataList = await metadataResource.GetMetadataAsync(packageName.Id, includePrerelease, includeAllVersions, context, NativeLogger, cancellationToken);

                        foreach (var metadata in metadataList)
                        {
                            res.Add(new NugetServerPackage(metadata, repo.PackageSource.Source));
                        }
                    }
                    catch (FatalProtocolException)
                    {
                        // Ignore 404/403 etc... (invalid sources)
                    }
                }
            }
            return(res);
        }
示例#4
0
        void UpdateActivePackageSource()
        {
            if (activePackageSource == null)
            {
                return;
            }

            if (activePackageSource.IsAggregate())
            {
                if (!HasMultiplePackageSources)
                {
                    ActivePackageSource = null;
                }
            }
            else
            {
                PackageSource matchedPackageSource = PackageSources
                                                     .GetEnabledPackageSources()
                                                     .FirstOrDefault(packageSource => packageSource.Equals(activePackageSource));

                if (matchedPackageSource == null)
                {
                    ActivePackageSource = null;
                }
            }
        }
示例#5
0
        /// <summary>
        /// Look for available packages from source containing <paramref name="searchTerm"/> in either the Id or description of the package.
        /// </summary>
        /// <param name="searchTerm">Term used for search.</param>
        /// <param name="allowPrereleaseVersions">Are we looking in pre-release versions too?</param>
        /// <returns>A list of packages matching <paramref name="searchTerm"/>.</returns>
        public async Task <IQueryable <NugetPackage> > SourceSearch(string searchTerm, bool allowPrereleaseVersions)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetPackage>();

            foreach (var repo in repositories)
            {
                try
                {
                    var searchResource = await repo.GetResourceAsync <PackageSearchResource>(CancellationToken.None);

                    if (searchResource != null)
                    {
                        var searchResults = await searchResource.SearchAsync(searchTerm, new SearchFilter(includePrerelease : false), 0, 0, NativeLogger, CancellationToken.None);

                        if (searchResults != null)
                        {
                            var packages = searchResults.ToArray();

                            foreach (var package in packages)
                            {
                                res.Add(new NugetServerPackage(package, repo.PackageSource.Source));
                            }
                        }
                    }
                }
                catch (FatalProtocolException)
                {
                    // Ignore 404/403 etc... (invalid sources)
                }
            }
            return(res.AsQueryable());
        }
示例#6
0
 protected AbstractPackage(PackageSources source, string packageID, string name, string version, string path, string compilerDefine)
     : base(source, MakePackageSpec(source, packageID, version))
 {
     Name           = name ?? throw new ArgumentNullException(nameof(name));
     ContentPath    = path;
     CompilerDefine = compilerDefine ?? throw new ArgumentNullException(nameof(compilerDefine));
 }
示例#7
0
        private static void Main(string[] args)
        {
            try
            {
                if (args == null)
                {
                    throw new ArgumentNullException(nameof(args));
                }

                var builder = BuildAvaloniaApp().AfterSetup(async _ =>
                {
                    Platform.Initialise();
                    PackageSources.InitialisePackageSources();

                    var extensionManager = new ExtensionManager();
                    var container        = CompositionRoot.CreateContainer(extensionManager);

                    var shellExportFactory  = container.GetExport <ExportFactory <ShellViewModel> >();
                    ShellViewModel.Instance = shellExportFactory.CreateExport().Value;

                    await PackageManager.LoadAssetsAsync().ConfigureAwait(false);
                });

                InitializeLogging();

                builder.Start <MainWindow>();
            }
            catch (Exception e)
            {
                Print(e);
            }
        }
 IEnumerable <IPackageRepository> CreateAllEnabledRepositories()
 {
     foreach (PackageSource source in PackageSources.GetEnabledPackageSources())
     {
         yield return(CreateRepository(source.Source));
     }
 }
示例#9
0
        public void Startup()
        {
            var progressBar = this.FindControl <ProgressBar>("StatusProgressBar");

            Platform.Initialise();

            PackageSources.InitialisePackageSources();

            var container = CompositionRoot.CreateContainer();

            ShellViewModel.Instance = container.GetExport <ShellViewModel>();

            var main = new MainWindow();

            main.WindowState = WindowState.Minimized;

            this.Hide();

            Dispatcher.UIThread.InvokeAsync(() => {
                main.WindowState = WindowState.Maximized;
            });

            main.Show();

            ShellViewModel.Instance.Cleanup();
        }
示例#10
0
        /// <summary>
        /// Returns updates for packages from the repository
        /// </summary>
        /// <param name="packageName">Package to look for updates</param>
        /// <param name="includePrerelease">Indicates whether to consider prerelease updates.</param>
        /// <param name="includeAllVersions">Indicates whether to include all versions of an update as opposed to only including the latest version.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns></returns>
        public async Task <IEnumerable <NugetPackage> > GetUpdates(PackageName packageName, bool includePrerelease, bool includeAllVersions, CancellationToken cancellationToken)
        {
            var resolutionContext = new ResolutionContext(
                DependencyBehavior.Lowest,
                includePrerelease,
                true,
                includeAllVersions ? VersionConstraints.None : VersionConstraints.ExactMajor | VersionConstraints.ExactMinor);

            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

            var res          = new List <NugetPackage>();
            var foundPackage = await NuGetPackageManager.GetLatestVersionAsync(packageName.Id, NuGetFramework.AgnosticFramework, resolutionContext, repositories, NativeLogger, cancellationToken);

            if (packageName.Version.ToNuGetVersion() <= foundPackage.LatestVersion)
            {
                foreach (var repo in repositories)
                {
                    var metadataResource = await repo.GetResourceAsync <PackageMetadataResource>(cancellationToken);

                    var metadataList = await metadataResource.GetMetadataAsync(packageName.Id, includePrerelease, includeAllVersions, NativeLogger, cancellationToken);

                    foreach (var metadata in metadataList)
                    {
                        res.Add(new NugetServerPackage(metadata, repo.PackageSource.Source));
                    }
                }
            }
            return(res);
        }
示例#11
0
        /// <summary>
        /// Find available packages from source with Id matching <paramref name="packageId"/>.
        /// </summary>
        /// <param name="packageId">Id of package we are looking for.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A list of packages matching <paramref name="packageId"/> or an empty list if none is found.</returns>
        public async Task <IEnumerable <NugetServerPackage> > FindSourcePackagesById(string packageId, CancellationToken cancellationToken)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetServerPackage>();

            await FindSourcePackagesByIdHelper(packageId, res, repositories, cancellationToken);

            return(res);
        }
        public void UpdatePackageSources(IEnumerable <PackageSource> updatedPackageSources)
        {
            PackageSources.Clear();
            foreach (PackageSource updatedPackageSource in updatedPackageSources)
            {
                PackageSources.Add(updatedPackageSource);
            }

            UpdateActivePackageSource();
        }
示例#13
0
        /// <summary>
        /// Find available packages from source ith Ids matching <paramref name="packageIds"/>.
        /// </summary>
        /// <param name="packageIds">List of package Ids we are looking for.</param>
        /// <param name="cancellationToken">A cancellation token.</param>
        /// <returns>A list of packages matching <paramref name="packageIds"/> or an empty list if none is found.</returns>
        public async Task <IEnumerable <NugetServerPackage> > FindSourcePackages(IReadOnlyCollection <string> packageIds, CancellationToken cancellationToken)
        {
            var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();
            var res          = new List <NugetServerPackage>();

            foreach (var packageId in packageIds)
            {
                await FindSourcePackagesByIdHelper(packageId, res, repositories, cancellationToken);
            }
            return(res);
        }
        public ServiceClient(PackageSources sources)
        {
            _initialized = new TaskCompletionSource<bool>();
            Initialized = _initialized.Task;

            _serviceBase = new Uri(sources.Sources().First().Url);
            _services = new Dictionary<string, List<JObject>>();

            WebRequest wr = HttpWebRequest.Create(_serviceBase);
            wr.BeginGetResponse(GetServiceIndex, wr);
        }
示例#15
0
        public void Startup()
        {
            var progressBar = this.FindControl <ProgressBar>("StatusProgressBar");

            if (progressBar == null)
            {
                throw new ApplicationException("Unable to locate progressbar");
            }

            Platform.Initialise();
            progressBar.Value += 5;

            PackageSources.InitialisePackageSources();
            progressBar.Value += 5;

            var container = CompositionRoot.CreateContainer();

            progressBar.Value += 50;

            var commandService = container.GetExportedValue <ICommandService>();

            IoC.RegisterConstant(commandService, typeof(ICommandService));
            progressBar.Value += 10;

            var keyGestureService = container.GetExportedValue <ICommandKeyGestureService>();

            IoC.RegisterConstant(keyGestureService, typeof(ICommandKeyGestureService));
            progressBar.Value += 10;

            var toolBarBuilder = container.GetExportedValue <IToolBarBuilder>();

            IoC.RegisterConstant(toolBarBuilder, typeof(IToolBarBuilder));
            progressBar.Value += 10;

            ShellViewModel.Instance = container.GetExportedValue <ShellViewModel>();

            var main = new MainWindow();

            main.WindowState = WindowState.Minimized;

            this.Hide();

            Dispatcher.UIThread.InvokeAsync(() => {
                main.WindowState = WindowState.Maximized;
            });

            main.Show();

            ShellViewModel.Instance.Cleanup();
        }
示例#16
0
        public PackageSource GetPackageSourceFor(DeployUnit deployUnit)
        {
            var matchingPackageSources = PackageSources.Where(x => x.Name == deployUnit.PackageInfo.Source).ToList();

            if (matchingPackageSources.Count == 0)
            {
                throw new ConfigurationErrorsException($"The package source {deployUnit.PackageInfo.Source}, used by the deploy unit {deployUnit.Name}, does not exist");
            }
            if (matchingPackageSources.Count > 1)
            {
                throw new ConfigurationErrorsException($"The package source {deployUnit.PackageInfo.Source}, used by the deploy unit {deployUnit.Name}, is declared more than once.");
            }
            return(matchingPackageSources.Single());
        }
示例#17
0
        private static string MakePackageSpec(PackageSources source, string packageID, string version)
        {
            if (packageID is null)
            {
                throw new ArgumentNullException(nameof(packageID));
            }

            if (source == PackageSources.UnityPackageManager && version is null)
            {
                throw new ArgumentNullException(nameof(version));
            }

            return(source == PackageSources.UnityPackageManager
                ? FormatUnityPackageManagerSpec(packageID, version)
                : packageID);
        }
示例#18
0
        private static void Main(string[] args)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var builder = AppBuilder.Configure <App>();

            if (args.Length >= 1 && args[0] == "--skia")
            {
                builder.UseSkia();

                if (Platform.OSDescription == "Windows")
                {
                    builder.UseWin32();
                }
                else
                {
                    builder.UseGtk3();
                }
            }
            else if (Platform.PlatformIdentifier == Platforms.PlatformID.Win32NT)
            {
                builder.UsePlatformDetect().UseSkia();
            }
            else
            {
                builder.UseGtk3().UseSkia();
            }

            builder.UseReactiveUI();

            builder.SetupWithoutStarting();

            Platform.Initialise();

            PackageSources.InitialisePackageSources();

            var container = CompositionRoot.CreateContainer();

            ShellViewModel.Instance = container.GetExport <ShellViewModel>();

            builder.Start <MainWindow>();
        }
示例#19
0
        public void UpdatePackageSources(IEnumerable <PackageSource> updatedPackageSources)
        {
            List <PackageSource> packageSourcesBackup = PackageSources.ToList();

            try {
                PackageSources.Clear();
                foreach (PackageSource updatedPackageSource in updatedPackageSources)
                {
                    PackageSources.Add(updatedPackageSource);
                }

                UpdateActivePackageSource();
            } catch (Exception) {
                PackageSources.AddRange(packageSourcesBackup);
                UpdateActivePackageSource();

                throw;
            }
        }
示例#20
0
        protected void InitializePackageSources()
        {
            var settings = Settings.LoadDefaultSettings(new PhysicalFileSystem("C:\\"), null, null);
            var packageSourceProvider = new PackageSourceProvider(settings);
            var packageSources        = packageSourceProvider.GetEnabledPackageSources().ToList();

            HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new DotPeekCredentialProvider(), packageSourceProvider);

            if (!packageSources.Any())
            {
                packageSources.Add(PluginConstants.NuGetPackageSource);
            }

            foreach (var packageSource in packageSources)
            {
                PackageSources.Add(new Uri(packageSource.Source));
            }

            PackageSource = PackageSources.First();
        }
示例#21
0
        protected override void OnPropertyChanged(AdvancedPropertyChangedEventArgs e)
        {
            if (IsSaving)
            {
                return;
            }

            if (string.Equals(e.PropertyName, nameof(PackageSources)) && PackageSources is not null)
            {
                var storedPackageSources = PackageSources.OfType <NuGetFeed>().ToList();
                SettingsFeeds.AddRange(storedPackageSources);
                Feeds.AddRange(storedPackageSources);

                // Validate items on first initialization
                SupressFeedVerificationOnCollectionChanged = false;
                Feeds.ForEach(async x => await VerifyFeedAsync(x));
            }

            base.OnPropertyChanged(e);
        }
        public PackageSourceMoniker(string sourceName, IEnumerable <PackageSourceContextInfo> packageSources)
        {
            SourceName = sourceName;

            if (packageSources == null)
            {
                throw new ArgumentNullException(nameof(packageSources));
            }
            if (!packageSources.Any())
            {
                throw new ArgumentException("List of sources cannot be empty", nameof(packageSources));
            }

            PackageSources     = packageSources.ToArray();
            PackageSourceNames = PackageSources.Select(s => s.Name).ToList();

            _stringRepresentation = $"{SourceName}: [{string.Join("; ", PackageSourceNames)}]";
            _tooltip = PackageSources.Count() == 1
                ? GetTooltip(PackageSources.First())
                : string.Join("; ", PackageSourceNames);
        }
示例#23
0
        private static void Main(string[] args)
        {
#if !DEBUG
            try
            {
#endif
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            BuildAvaloniaApp().BeforeStarting(_ =>
            {
                var studio = IoC.Get <IStudio>();

                InitializeLogging();

                Platform.Initialise();

                PackageSources.InitialisePackageSources();

                Dispatcher.UIThread.Post(async() =>
                {
                    await PackageManager.LoadAssetsAsync().ConfigureAwait(false);
                });
            })
            .StartShellApp <AppBuilder, MainWindow>("AvalonStudio", null, () => new MainWindowViewModel());
#if !DEBUG
        }

        catch (Exception e)
        {
            Print(e);
        }
        finally
#endif
            {
                Application.Current.Exit();
            }
        }
示例#24
0
        protected PackageReference(PackageSources source, string packageSpec)
        {
            if (packageSpec is null)
            {
                throw new ArgumentNullException(nameof(packageSpec));
            }

            var parts = packageSpec.SplitX('@');

            if (parts.Length == 0)
            {
                throw new ArgumentException("Value must not be empty string", nameof(packageSpec));
            }
            else if (parts.Length == 1)
            {
                Source      = source;
                PackageID   = parts[0];
                VersionSpec = null;
            }
            else if (parts.Length == 2)
            {
                Source      = source;
                PackageID   = parts[0];
                VersionSpec = parts[1];
                var     versionStr = VersionSpec;
                Version v          = null;
                while (versionStr.Length > 0 &&
                       !Version.TryParse(versionStr, out v))
                {
                    versionStr = versionStr.Substring(0, versionStr.Length - 1);
                }

                Version = v;
            }
            else
            {
                throw new ArgumentException("Value can only contain one @ symbol", nameof(packageSpec));
            }
        }
示例#25
0
        private static int Main(string[] args)
        {
            if (args.Length >= 1 && args[0] == "debug")
            {
                Console.WriteLine("Waiting for debugger to attach.");

                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(100);
                }

                Debugger.Break();

                args = args.ToList().Skip(1).ToArray();
            }

            Platform.Initialise();

            PackageSources.InitialisePackageSources();

            var container = CompositionRoot.CreateContainer();

            var studio = container.GetExport <IStudio>();

            Console.WriteLine("Avalon Build - {0} - {1}  - {2}", releaseName, version, Platform.PlatformIdentifier);

            var result = Parser.Default.ParseArguments <AddOptions, RemoveOptions, AddReferenceOptions, BuildOptions, CleanOptions, CreateOptions, PackageOptions, TestOptions>(args)
                         .MapResult((BuildOptions opts) => RunBuild(opts),
                                    (AddOptions opts) => RunAdd(opts),
                                    (AddReferenceOptions opts) => RunAddReference(opts),
                                    (PackageOptions opts) => RunInstallPackage(opts),
                                    (CleanOptions opts) => RunClean(opts),
                                    (CreateOptions opts) => RunCreate(opts),
                                    (RemoveOptions opts) => RunRemove(opts),
                                    (TestOptions opts) => RunTest(opts),
                                    errs => 1);

            return(result - 1);
        }
示例#26
0
        public void SetPackages(PackageSources packageSource, IEnumerable <PackageInfo> packages)
        {
            switch (packageSource)
            {
            case PackageSources.Microsoft:
                _microsoftPackages = packages.ToArray();
                break;

            case PackageSources.ThirdParty:
                _thirdPartyPackages = packages.ToArray();
                break;
            }

            foreach (var package in packages)
            {
                package.PropertyChanged += (sender, e) =>
                {
                    TriggerPropertyChanged(nameof(Packages), nameof(SelectButtonText));
                };
            }

            SetActivePackages();
            TriggerPropertyChanged(nameof(Packages), nameof(SelectButtonText));
        }
 static Program()
 {
     _sources = new PackageSources();
     _sources.Initialize();
 }
示例#28
0
 public IEnumerable <string> PackageSources( )
 {
     CheckDisposed();
     return((_PackageSources ?? (_PackageSources = (_callback.Resolve <PackageSources>() ?? (() => default(IEnumerable <string>)))))());
 }
示例#29
0
        public void Dispose()
        {
            // Clearing all of these ensures that the transient APIs
            // can't be called outside of the appropriate scope.

            #region dispose-dispatcher service-apis
            _GetNuGetExePath             = null;
            _GetNuGetDllPath             = null;
            _DownloadFile                = null;
            _AddPinnedItemToTaskbar      = null;
            _RemovePinnedItemFromTaskbar = null;
            _CreateShortcutLink          = null;
            _UnzipFileIncremental        = null;
            _UnzipFile                 = null;
            _AddFileAssociation        = null;
            _RemoveFileAssociation     = null;
            _AddExplorerMenuItem       = null;
            _RemoveExplorerMenuItem    = null;
            _SetEnvironmentVariable    = null;
            _RemoveEnvironmentVariable = null;
            _AddFolderToPath           = null;
            _RemoveFolderFromPath      = null;
            _InstallMSI                = null;
            _RemoveMSI                 = null;
            _StartProcess              = null;
            _InstallVSIX               = null;
            _UninstallVSIX             = null;
            _InstallPowershellScript   = null;
            _UninstallPowershellScript = null;
            _SearchForExecutable       = null;
            _GetUserBinFolder          = null;
            _GetSystemBinFolder        = null;
            _CopyFile                = null;
            _CopyFolder              = null;
            _Delete                  = null;
            _DeleteFolder            = null;
            _CreateFolder            = null;
            _DeleteFile              = null;
            _BeginTransaction        = null;
            _AbortTransaction        = null;
            _EndTransaction          = null;
            _GenerateUninstallScript = null;
            _GetKnownFolder          = null;
            _IsElevated              = null;
            #endregion

            #region dispose-dispatcher core-apis
            _Warning          = null;
            _Message          = null;
            _Error            = null;
            _Debug            = null;
            _Verbose          = null;
            _ExceptionThrown  = null;
            _Progress         = null;
            _ProgressComplete = null;
            _GetHostDelegate  = null;
            _IsCancelled      = null;
            #endregion

            #region dispose-dispatcher request-apis
            _OkToContinue                       = null;
            _YieldPackage                       = null;
            _YieldPackageDetails                = null;
            _YieldPackageSwidtag                = null;
            _YieldSource                        = null;
            _YieldMetadataDefinition            = null;
            _YieldInstallationOptionsDefinition = null;
            #endregion

            #region dispose-dispatcher host-apis
            _GetMetadataKeys             = null;
            _GetMetadataValues           = null;
            _GetInstallationOptionKeys   = null;
            _GetInstallationOptionValues = null;
            _PackageSources   = null;
            _GetConfiguration = null;
            _ShouldContinueWithUntrustedPackageSource = null;
            _ShouldProcessPackageInstall                = null;
            _ShouldProcessPackageUninstall              = null;
            _ShouldContinueAfterPackageInstallFailure   = null;
            _ShouldContinueAfterPackageUninstallFailure = null;
            _ShouldContinueRunningInstallScript         = null;
            _ShouldContinueRunningUninstallScript       = null;
            _AskPermission = null;
            _WhatIf        = null;
            #endregion

            #region dispose-dispatcher protocol-apis
            _ProtocolGetNames        = null;
            _ProtocolIsValidSource   = null;
            _ProtocolGetItemMetadata = null;
            _ProtocolDownloadItem    = null;
            _ProtocolUnpackItem      = null;
            _InstallItem             = null;
            #endregion

            _callback = null;
        }
        public static async Task Install(PackageSources sources, string packageId)
        {
            var storage = new ServiceClient(sources);

            // 1. Load package3.config
            JObject packageConfig;
            try
            {
                string packageConfigJson = File.ReadAllText("packages.config.json");
                packageConfig = PackageConfig.Load(packageConfigJson);

            }
            catch (FileNotFoundException)
            {
                packageConfig = JObject.Parse(@"{ ""packages"": [], ""@context"": { ""@vocab"": ""http://schema.nuget.org/packagesConfig#"",
    ""pc"": ""http://schema.nuget.org/packagesConfig#"",
    ""package"": ""@id"",
    ""packages"": {""@id"": ""pc:package"", ""@container"": ""@set"" },
    ""metadataSources"": {""@id"": ""pc:metadataSource"", ""@container"": ""@set"", ""@type"":  ""@id"" },
    ""downloadLocations"": {""@id"": ""pc:downloadLocation"", ""@container"": ""@set"", ""@type"": ""@id"" } } }
");
                File.WriteAllText("packages.config.json", packageConfig.ToString());
            }

            // 3. Resolve dependencies.
            List<string> installed = new List<string> { packageId };
            foreach (JObject package in packageConfig["packages"])
            {
                if (package["explicitlyInstalled"].ToObject<bool>())
                {
                    installed.Add(package["id"].ToObject<string>());
                }
            }

            IGallery gallery = storage.GetResolverClient().Gallery;

            IList<Package> solution = await Runner.ResolveDependencies(gallery, installed);

            // 4. Update packages.config.json.
            HttpClient hc = new HttpClient();

            foreach (Package item in solution)
            {
                string nupkgPath = (string)item.PackageJson["nupkgUrl"];

                string id = item.Id;
                string version = item.Version.ToString();
                string url = item.PackageJson["url"].ToObject<string>();

                bool alreadyPresent = false;
                foreach (JObject package in packageConfig["packages"])
                {
                    if (string.Compare(package["id"].ToObject<string>(), id, ignoreCase: true) == 0)
                    {
                        alreadyPresent = true;
                        package["package"] = url;
                        package["version"] = version;
                        package["explicitlyInstalled"] = installed.Where(i => string.Compare(id, i, ignoreCase: true) == 0).Any();
                        package["packageRestoreHints"]["downloadLocations"] = new JArray { nupkgPath };
                    }
                }
                if (!alreadyPresent)
                {
                    ((JArray)packageConfig["packages"]).Add(new JObject {
                    { "package", url},
                    { "id", id},
                    {"version", version},
                    {"explicitlyInstalled", installed.Where(i => string.Compare(id, i, ignoreCase: true) == 0).Any() },
                    {"packageRestoreHints", new JObject {
                        {"metadataSources", new JArray {"https://api.nuget.org/ver3/"} },
                        {"downloadLocations", new JArray { nupkgPath } },
                    }}});
                }
            }
            File.WriteAllText("packages.config.json", packageConfig.ToString());

            // 5. Download the dependencies.
            await Restore(sources);
        }
        public static async Task Restore(PackageSources sources)
        {
            var serviceClient = new ServiceClient(sources);

            if (!Directory.Exists(".nuget/packages"))
            {
                Directory.CreateDirectory(".nuget/packages");
            }

            JObject packageConfig;
            try
            {
                string packageConfigJson = File.ReadAllText("packages.config.json");
                packageConfig = PackageConfig.Load(packageConfigJson);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("No packages.config.json file.");
                return;
            }

            HttpClient hc = new HttpClient();
            foreach (JObject package in packageConfig["packages"])
            {
                string id = package["id"].ToObject<string>().ToLower();
                string version = package["version"].ToObject<string>();

                string downloadPath = package["packageRestoreHints"]["downloadLocations"][0].ToObject<string>();

                if (File.Exists(".nuget/packages/" + id + "." + version + ".nupkg"))
                {
                    continue;
                }

                Console.WriteLine("Downloading {0}...", downloadPath);

                using (Stream nupkg = await hc.GetStreamAsync(package["packageRestoreHints"]["downloadLocations"][0].ToObject<string>()))
                using (FileStream download = File.Create(".nuget/packages/" + id + "." + version + ".nupkg"))
                {
                    nupkg.CopyTo(download);
                }
            }
        }
示例#32
0
 public PackageSource GetPackageSourceFor(DeployUnit deployUnit)
 => PackageSources.Single(x => x.Name == deployUnit.PackageInfo.Source);
示例#33
0
        /// <summary>
        /// Fetch, if not already downloaded, and install the package represented by
        /// (<paramref name="packageId"/>, <paramref name="version"/>).
        /// </summary>
        /// <remarks>It is safe to call it concurrently be cause we operations are done using the FileLock.</remarks>
        /// <param name="packageId">Name of package to install.</param>
        /// <param name="version">Version of package to install.</param>
        public async Task <NugetLocalPackage> InstallPackage(string packageId, PackageVersion version, IEnumerable <string> targetFrameworks, ProgressReport progress)
        {
            using (GetLocalRepositoryLock())
            {
                currentProgressReport = progress;
                try
                {
                    var identity = new PackageIdentity(packageId, version.ToNuGetVersion());

                    var resolutionContext = new ResolutionContext(
                        DependencyBehavior.Lowest,
                        true,
                        true,
                        VersionConstraints.None);

                    var repositories = PackageSources.Select(sourceRepositoryProvider.CreateRepository).ToArray();

                    var projectContext = new EmptyNuGetProjectContext()
                    {
                        ActionType = NuGetActionType.Install,
                        PackageExtractionContext = new PackageExtractionContext(PackageSaveMode.Defaultv3, XmlDocFileSaveMode.Skip, null, NativeLogger),
                    };

                    ActivityCorrelationId.StartNew();

                    {
                        var installPath = SettingsUtility.GetGlobalPackagesFolder(settings);

                        // In case it's a package without any TFM (i.e. Visual Studio plugin), we still need to specify one
                        if (!targetFrameworks.Any())
                        {
                            targetFrameworks = new string[] { "net6.0" }
                        }
                        ;

                        // Old version expects to be installed in GamePackages
                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0) && oldRootDirectory != null)
                        {
                            installPath = oldRootDirectory;
                        }

                        var projectPath = Path.Combine("StrideLauncher.json");
                        var spec        = new PackageSpec()
                        {
                            Name         = Path.GetFileNameWithoutExtension(projectPath), // make sure this package never collides with a dependency
                            FilePath     = projectPath,
                            Dependencies = new List <LibraryDependency>()
                            {
                                new LibraryDependency
                                {
                                    LibraryRange = new LibraryRange(packageId, new VersionRange(version.ToNuGetVersion()), LibraryDependencyTarget.Package),
                                }
                            },
                            RestoreMetadata = new ProjectRestoreMetadata
                            {
                                ProjectPath              = projectPath,
                                ProjectName              = Path.GetFileNameWithoutExtension(projectPath),
                                ProjectStyle             = ProjectStyle.PackageReference,
                                ProjectUniqueName        = projectPath,
                                OutputPath               = Path.Combine(Path.GetTempPath(), $"StrideLauncher-{packageId}-{version.ToString()}"),
                                OriginalTargetFrameworks = targetFrameworks.ToList(),
                                ConfigFilePaths          = settings.GetConfigFilePaths(),
                                PackagesPath             = installPath,
                                Sources         = SettingsUtility.GetEnabledSources(settings).ToList(),
                                FallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToList()
                            },
                        };
                        foreach (var targetFramework in targetFrameworks)
                        {
                            spec.TargetFrameworks.Add(new TargetFrameworkInformation {
                                FrameworkName = NuGetFramework.Parse(targetFramework)
                            });
                        }

                        using (var context = new SourceCacheContext {
                            MaxAge = DateTimeOffset.UtcNow
                        })
                        {
                            context.IgnoreFailedSources = true;

                            var dependencyGraphSpec = new DependencyGraphSpec();

                            dependencyGraphSpec.AddProject(spec);

                            dependencyGraphSpec.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

                            IPreLoadedRestoreRequestProvider requestProvider = new DependencyGraphSpecRequestProvider(new RestoreCommandProvidersCache(), dependencyGraphSpec);

                            var restoreArgs = new RestoreArgs
                            {
                                AllowNoOp             = true,
                                CacheContext          = context,
                                CachingSourceProvider = new CachingSourceProvider(new PackageSourceProvider(settings)),
                                Log = NativeLogger,
                            };

                            // Create requests from the arguments
                            var requests = requestProvider.CreateRequests(restoreArgs).Result;

                            foreach (var request in requests)
                            {
                                // Limit concurrency to avoid timeout
                                request.Request.MaxDegreeOfConcurrency = 4;

                                var command = new RestoreCommand(request.Request);

                                // Act
                                var result = await command.ExecuteAsync();

                                if (!result.Success)
                                {
                                    throw new InvalidOperationException($"Could not restore package {packageId}");
                                }
                                foreach (var install in result.RestoreGraphs.Last().Install)
                                {
                                    var package = result.LockFile.Libraries.FirstOrDefault(x => x.Name == install.Library.Name && x.Version == install.Library.Version);
                                    if (package != null)
                                    {
                                        var packagePath = Path.Combine(installPath, package.Path);
                                        OnPackageInstalled(this, new PackageOperationEventArgs(new PackageName(install.Library.Name, install.Library.Version.ToPackageVersion()), packagePath));
                                    }
                                }
                            }
                        }

                        if (packageId == "Xenko" && version < new PackageVersion(3, 0, 0, 0))
                        {
                            UpdateTargetsHelper();
                        }
                    }

                    // Load the recently installed package
                    var installedPackages = GetPackagesInstalled(new[] { packageId });
                    return(installedPackages.FirstOrDefault(p => p.Version == version));
                }
                finally
                {
                    currentProgressReport = null;
                }
            }
        }
示例#34
0
        private void OnPackageSourcesChanged()
        {
            EditablePackageSources = new FastObservableCollection <EditablePackageSource>(PackageSources.Select(x =>
                                                                                                                new EditablePackageSource
            {
                IsEnabled = x.IsEnabled,
                Name      = x.Name,
                Source    = x.Source
            }));

            VerifyAll();
        }