private static void Main(string[] args) { bool removeDirectory; string temporaryDirectory = GetTemporaryDirectory(out removeDirectory); Console.WriteLine("Working directory: {0}", temporaryDirectory); try { IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2/"); PackageManager packageManager = new PackageManager(sourceRepository, temporaryDirectory); packageManager.PackageInstalled += HandlePackageInstalled; packageManager.InstallPackage("Microsoft.Bcl.Immutable", SemanticVersion.Parse("1.0.34")); packageManager.InstallPackage("System.Collections.Immutable", SemanticVersion.Parse("1.1.33-beta")); using (PEReader referenceAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "Microsoft.Bcl.Immutable.1.0.34", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll")))) { using (PEReader newAssembly = new PEReader(File.OpenRead(Path.Combine(temporaryDirectory, "System.Collections.Immutable.1.1.33-beta", "lib", "portable-net45+win8+wp8+wpa81", "System.Collections.Immutable.dll")))) { Analyzer analyzer = new Analyzer(referenceAssembly, newAssembly, null); analyzer.Run(); } } } finally { if (removeDirectory) Directory.Delete(temporaryDirectory, true); } }
private IPackageManager CreatePackageManager(string rootDir) { IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository(rootDir); PackageManager mgr = new PackageManager(repo, rootDir); return mgr; }
/// <summary> /// Install package /// </summary> /// <param name="pkgId"></param> public static JsonResponse InstallPackage(string pkgId) { try { var packageManager = new NuGet.PackageManager( _repository, new DefaultPackagePathResolver(_feedUrl), new PhysicalFileSystem(HttpContext.Current.Server.MapPath(Utils.ApplicationRelativeWebRoot + "App_Data/packages")) ); var package = _repository.FindPackage(pkgId); packageManager.InstallPackage(package, false); FileSystem.CopyPackageFiles(package.Id, package.Version.ToString()); // reset cache Blog.CurrentInstance.Cache.Remove("Installed-Themes"); } catch (Exception ex) { Utils.Log("PackageManager.InstallPackage", ex); return(new JsonResponse { Success = false, Message = "Error installing package, see logs for details" }); } return(new JsonResponse { Success = true, Message = "Package successfully installed" }); }
public HomePackageManager() { IPackageRepository repository = PackageRepositoryFactory.Default .CreateRepository(AppSettings.PluginsRepository); pManager = new PackageManager(repository, AppSettings.PluginsFolder); }
public IEnumerable<string> GetCompatibleAssemblyPaths() { List<string> assemblyPaths = new List<string>(); FrameworkReducer reducer = new FrameworkReducer(); NuGetFramework targetFramework = new NuGetFramework(".NETFramework", Version.Parse("4.5")); // If alternate versions of Wyam are developed (I.e., for DNX), this will need to be switched NuGetFrameworkFullComparer frameworkComparer = new NuGetFrameworkFullComparer(); IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(Path); PackageManager packageManager = new PackageManager(packageRepository, Path); foreach (IPackage package in packageManager.LocalRepository.GetPackages()) { List<KeyValuePair<IPackageFile, NuGetFramework>> filesAndFrameworks = package.GetLibFiles() .Select(x => new KeyValuePair<IPackageFile, NuGetFramework>(x, new NuGetFramework(x.TargetFramework.Identifier, x.TargetFramework.Version, x.TargetFramework.Profile))) .ToList(); NuGetFramework targetPackageFramework = reducer.GetNearest(targetFramework, filesAndFrameworks.Select(x => x.Value)); if (targetPackageFramework != null) { assemblyPaths.AddRange(filesAndFrameworks .Where(x => frameworkComparer.Equals(targetPackageFramework, x.Value)) .Select(x => System.IO.Path.Combine(Path, String.Format(CultureInfo.InvariantCulture, "{0}.{1}", package.Id, package.Version), x.Key.Path)) .Where(x => System.IO.Path.GetExtension(x) == ".dll")); } } return assemblyPaths; }
public static async Task<string> Install(this IPackage package, string source, string dest) { IPackageRepository packageRepository = new LocalPackageRepository(source); IPackageManager packageManager = new PackageManager(packageRepository, dest); var tcs = new TaskCompletionSource<string>(); var handler = new EventHandler<PackageOperationEventArgs>((sender, args) => tcs.SetResult(args.InstallPath)); packageManager.PackageInstalled += handler; packageManager.InstallPackage(package, true, true); packageManager.PackageInstalled -= handler; if (await Task.WhenAny(tcs.Task, Task.Delay(5000)) == tcs.Task) { await tcs.Task; return tcs.Task.Result; } else { throw new TimeoutException("Package install timeout"); } }
public void Initialize() { var path = Path.Combine(_fileSystem.CurrentDirectory, Constants.PackagesFolder); _repositoryUrls = GetRepositorySources(path); var remoteRepository = new AggregateRepository(PackageRepositoryFactory.Default, _repositoryUrls, true); _manager = new PackageManager(remoteRepository, path); }
public NugetService(Solution solution) { //_defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl); var factory = new PackageRepositoryFactory(); _remoteRepository = factory.CreateRepository(GalleryUrl); _localRepository = factory.CreateRepository(solution.PackagesFolder()); _sourceRepository = new AggregateRepository(new[] { _remoteRepository, _localRepository }); _fileSystem = new PhysicalFileSystem(solution.PackagesFolder()); _pathResolver = new DefaultPackagePathResolver(_fileSystem); _console = new Console(); _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){ Logger = _console }; _packages = new Cache<NugetDependency, IPackage>(dep => { Install(dep); return _sourceRepository.FindPackage(dep.Name, dep.Version); }); }
static void Install(string pkgName, SemanticVersion version) { //Initialize the package manager var packageManager = new PackageManager(Repository, Path); //Download and unzip the package packageManager.InstallPackage(pkgName, version); }
public NugetInstallationProvider(IFileSystem fileSystem) { _fileSystem = fileSystem; var path = Path.Combine(fileSystem.CurrentDirectory, Constants.PackagesFolder); _repositoryUrls = GetRepositorySources(path); var remoteRepository = new AggregateRepository(PackageRepositoryFactory.Default, _repositoryUrls, true); _manager = new PackageManager(remoteRepository, path); }
public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig) { if (rootDirectory == null) throw new ArgumentNullException(nameof(rootDirectory)); if (configFile == null) throw new ArgumentNullException(nameof(configFile)); if (overrideFile == null) throw new ArgumentNullException(nameof(overrideFile)); // First try the override file with custom settings var configFileName = overrideFile; var configFilePath = Path.Combine(rootDirectory, configFileName); if (!File.Exists(configFilePath)) { // Override file does not exist, fallback to default config file configFileName = configFile; configFilePath = Path.Combine(rootDirectory, configFileName); if (!File.Exists(configFilePath)) { throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile)); } } rootFileSystem = new PhysicalFileSystem(rootDirectory); Settings = NuGet.Settings.LoadDefaultSettings(rootFileSystem, configFileName, null); string installPath = Settings.GetRepositoryPath(); packagesFileSystem = new PhysicalFileSystem(installPath); packageSourceProvider = new PackageSourceProvider(Settings); repositoryFactory = new PackageRepositoryFactory(); SourceRepository = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true); pathResolver = new DefaultPackagePathResolver(packagesFileSystem); Manager = new PackageManager(SourceRepository, pathResolver, packagesFileSystem); var mainPackageList = Settings.GetConfigValue(MainPackagesKey); if (string.IsNullOrWhiteSpace(mainPackageList)) { throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config"); } MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); VSIXPluginId = Settings.GetConfigValue(VsixPluginKey); if (string.IsNullOrWhiteSpace(VSIXPluginId)) { throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config"); } RepositoryPath = Settings.GetConfigValue(RepositoryPathKey); if (string.IsNullOrWhiteSpace(RepositoryPath)) { RepositoryPath = DefaultGamePackagesDirectory; } // Setup NugetCachePath in the cache folder Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath)); }
public void EnsureNamespace(IAgora agora, string nsName, string package) { if (!agora.GetRegistrations ().Any (reg => reg.Namespace == nsName)) { //Connect to the official package repository var repo = PackageRepositoryFactory.Default.CreateRepository( //"https://packages.nuget.org/api/v2" "https://www.myget.org/F/castoriadis/" ); //Initialize the package manager var entryAssembly = Assembly.GetEntryAssembly (); var path = entryAssembly == null ? "." : Path.GetDirectoryName(entryAssembly.Location); path = Path.Combine (path, nsName); Directory.CreateDirectory (path); var packageManager = new PackageManager(repo, path); //Download and unzip the package packageManager.InstallPackage(package, null, false, true); // copy all EXEs and DLLs to the root install var di = new DirectoryInfo (path); new[]{"*.dll","*.exe"}.SelectMany(ext => di.GetFiles(ext, SearchOption.AllDirectories)) .ToList() .ForEach(fi => { var dest = Path.Combine(path, fi.Name); if (Path.GetFullPath(dest) != fi.FullName) { if (File.Exists(dest)) File.Delete(dest); fi.CopyTo(dest); } }); // find the EXE var exeFile = di.GetFiles ("*.exe").First (); #if __MonoCS__ var module = Assembly.Load("Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"); var type = module.GetType("Mono.Unix.Native.Syscall"); var chmodMI = type.GetMethod("chmod"); chmodMI.Invoke(null, new object[]{exeFile.FullName, 4095u}); #endif using (var proc = Process.Start(exeFile.FullName)) { if (proc == null) { // try to determine why... throw new Exception ("The process coulnd't start."); } int waitTimes = 0; for (var registered = agora.GetRegistrations ().Any (reg => reg.Namespace == nsName); !registered; registered = agora.GetRegistrations ().Any (reg => reg.Namespace == nsName)) { Thread.Sleep (100); if (++waitTimes > 50) { proc.Kill (); throw new Exception ("Couldn't register on time."); } } } } }
public SDKVersionManager(PackageManager manager, String packageName, String vsixPackageName) { Versions = new List<SDKVersion>(); RunnableVersions = new List<SDKVersion>(); VsixVersion = null; this.manager = manager; this.packageName = packageName; this.vsixPackageName = vsixPackageName; }
public static void AddPackage(this DotNetProject project, IPackage package, IPackageRepository repository) { var packageManager = new PackageManager(repository, project.BaseDirectory); packageManager.InstallPackage(package, false); var projectSystem = new ProjectSystemWrapper(project); var projectManager = new ProjectManager(repository, packageManager.PathResolver, projectSystem, packageManager.LocalRepository); projectManager.AddPackageReference(package.Id); project.NeedsReload = true; }
protected PackageManagerService() { var repo = PackageRepositoryFactory.Default.CreateRepository(MyGetRepoUrl); var path = new DefaultPackagePathResolver(MyGetRepoUrl); var fileSystem = new PhysicalFileSystem(HostingEnvironment.MapPath("~/App_Plugins/Packages")); var localRepo = PackageRepositoryFactory.Default.CreateRepository(HostingEnvironment.MapPath("~/App_Plugins/Packages")); //Create a NuGet Package Manager PackageManager = new PackageManager(repo, path, fileSystem, localRepo); }
public RemoteRepoBuilder(TestContext testContext) { if (testContext == null) { throw new ArgumentNullException("testContext"); } this.testContext = testContext; string packageSource = GetFakeRemoteNuGetSourceDir(); this.fakeRemoteRepo = PackageRepositoryFactory.Default.CreateRepository(packageSource); this.manager = new PackageManager(this.fakeRemoteRepo, packageSource); }
public PackageManager(PackageManagerEnvironment workEnvironment, PackageSetup packageSetup) { // If no external package setup is provided, load it from the config file if (packageSetup == null) { string configFilePath = workEnvironment.ConfigFilePath; if (!File.Exists(configFilePath)) { packageSetup = new PackageSetup(); packageSetup.Save(configFilePath); } else { try { packageSetup = PackageSetup.Load(configFilePath); } catch (Exception e) { Logs.Editor.WriteError( "Failed to load PackageManager config file '{0}': {1}", configFilePath, LogFormat.Exception(e)); } } } // Assign work environment and package setup to work with this.env = workEnvironment; this.setup = packageSetup; // Create internal package management objects IPackageRepository[] repositories = this.setup.RepositoryUrls .Select(x => this.CreateRepository(x)) .Where(x => x != null) .ToArray(); this.repository = new AggregateRepository(repositories); this.manager = new NuGet.PackageManager(this.repository, this.env.RepositoryPath); this.manager.PackageInstalling += this.manager_PackageInstalling; this.manager.PackageInstalled += this.manager_PackageInstalled; this.manager.PackageUninstalled += this.manager_PackageUninstalled; this.cache = new PackageCache( this.repository, repositories.OfType <LocalPackageRepository>().Any()); this.logger = new PackageManagerLogger(); this.manager.Logger = this.logger; this.dependencyWalker = new PackageDependencyWalker(this.GetPackage); // Retrieve information about local packages this.RetrieveLocalPackageInfo(); }
public void InstallPackage(PackageManager packageManager, Engine engine, bool updatePackages) { engine.Trace.Verbose("Installing package {0}{1} from {2}...", _packageId, _versionSpec == null ? string.Empty : " " + _versionSpec, packageManager.SourceRepository.Source); // Find the local package IPackage localPackage = packageManager.LocalRepository.FindPackage(_packageId); // Check if we're up to date if (localPackage != null && _versionSpec.Satisfies(localPackage.Version) && !updatePackages) { engine.Trace.Verbose("Package {0}{1} is satisfied by version {2}, skipping.", _packageId, _versionSpec == null ? string.Empty : " " + _versionSpec, localPackage.Version); return; } // Find the source package IPackage sourcePackage = packageManager.SourceRepository .FindPackage(_packageId, _versionSpec, _allowPrereleaseVersions, _allowUnlisted); if (sourcePackage == null) { engine.Trace.Warning("Package {0} {1} could not be found at {2}.", _packageId, _versionSpec == null ? string.Empty : " " + _versionSpec, packageManager.SourceRepository.Source); return; } // Check if we're up to date if (localPackage != null && localPackage.Version >= sourcePackage.Version) { engine.Trace.Verbose("Package {0}{1} is up to date with version {2}, skipping.", _packageId, _versionSpec == null ? string.Empty : " " + _versionSpec, localPackage.Version); return; } // Uninstall the old package (removing any content files) if (localPackage != null) { int indent = engine.Trace.Indent(); engine.Trace.Verbose("Uninstalling package {0} {1}.", localPackage.Id, localPackage.Version); packageManager.UninstallPackage(localPackage, true); engine.Trace.IndentLevel = indent; } // Install it packageManager.InstallPackage(sourcePackage, false, _allowPrereleaseVersions); engine.Trace.Verbose("Installed package {0} {1}.", sourcePackage.Id, sourcePackage.Version); }
public XamForms() { var packageUnzipPath = Environment.CurrentDirectory; var retryPolicy = Policy .Handle<Exception>() .WaitAndRetry( 5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, timeSpan, context) => { Log.Warning( "An exception was thrown whilst retrieving or installing {packageName}: {exception}", _packageName, exception); }); retryPolicy.Execute(() => { var repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2"); var packageManager = new PackageManager(repo, packageUnzipPath); var package = repo.FindPackagesById(_packageName).Single(x => x.IsLatestVersion); packageManager.InstallPackage(package.Id); Log.Debug("Using Xamarin Forms {Version} released on {Published}", package.Version, package.Published); Log.Debug("{ReleaseNotes}", package.ReleaseNotes); }); var xamarinForms = Directory.GetFiles(packageUnzipPath, "Xamarin.Forms.Core.dll", SearchOption.AllDirectories); var latestVersion = xamarinForms.Last(); Assemblies.Add(latestVersion); if (PlatformHelper.IsRunningOnMono()) { CecilSearchDirectories.Add( @"/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/xbuild-frameworks/.NETPortable/v4.5/Profile/Profile111"); } else { CecilSearchDirectories.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile111"); } }
internal bool resolve(string packageName, string packageVersion, string remoteRepositoryUrl) { var repo = PackageRepositoryFactory.Default.CreateRepository(remoteRepositoryUrl); var packageManager = new PackageManager(repo, pluginPath); var package = repo.FindPackage(packageName, SemanticVersion.Parse(packageVersion), true, true); bool ret; if (package != null) { packageManager.InstallPackage(package, false, true); ret = true; } else { ret = false; } return ret; }
private void DoEnsurePackageLoaded(PackageMetadata packageInfo) { var packageRepository = PackageRepositoryFactory.Default.CreateRepository(packageSourcePath.AbsoluteUri); var packageManager = new NuGet.PackageManager(packageRepository, GetCacheFolderPath()); var packageId = packageInfo.PackageKey; var packageSemanticVersion = packageInfo.ToSemanticVersion(); var corrId = Guid.NewGuid(); this.LogPackageOperation(packageId, packageSemanticVersion, "Package needed", corrId); var currentPackages = packageManager.LocalRepository.GetPackages().Where(p => p.Id == packageId).ToList(); var installedPackage = EnsurePackageInstalled(currentPackages, packageManager, packageId, packageSemanticVersion, corrId); EnsureMultiplePackagesRespected(currentPackages, packageManager, packageId, packageSemanticVersion, corrId); EnsureMainAssemblyLoadedInAppDomain(packageManager.PathResolver, installedPackage, packageInfo, corrId); }
private IPackage EnsurePackageInstalled( IReadOnlyCollection <IPackage> localCacheInstalledPackages, NuGet.PackageManager currentPackageManager, string packageId, SemanticVersion packageSemanticVersion, Guid corrId) { if (localCacheInstalledPackages.All(p => p.Version != packageSemanticVersion)) { this.LogPackageOperation(packageId, packageSemanticVersion, "Install in local cache", corrId); currentPackageManager.InstallPackage(packageId, packageSemanticVersion); } else { this.LogPackageOperation(packageId, packageSemanticVersion, "Already in cache", corrId); } return(currentPackageManager.LocalRepository.FindPackage(packageId, packageSemanticVersion)); }
PackageManager GetPackageManager(string source) { if(_packageManagers.ContainsKey(source)) { return _packageManagers[source]; } IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(source); var packageManager = new PackageManager(packageRepository, new DefaultPackagePathResolver(_options.OutputDirectory, !_options.ExcludeVersion), new PhysicalFileSystem(_options.OutputDirectory)); packageManager.Logger = new ConsoleLogger(); _packageManagers.Add(source, packageManager); return packageManager; }
public PluginsChecker() { InitializeComponent(); // Initializing folders variables applicationDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "XrmToolBox"); nugetPluginsFolder = Path.Combine(applicationDataFolder, "Plugins"); applicationFolder = new FileInfo(Assembly.GetExecutingAssembly().FullName).DirectoryName; applicationPluginsFolder = Path.Combine(applicationFolder, "Plugins"); // Reading existing plugins files plugins = new DirectoryInfo(applicationPluginsFolder).GetFiles(); // Repository initialization var repository = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2"); manager = new PackageManager(repository, nugetPluginsFolder); }
/// <summary> /// Attempts to download a NuGet package with the specified id and optional version /// to the specified directory /// </summary> public NuGet.IPackage FetchPackage(string packageSource, string packageId, SemanticVersion version, string downloadDirectory) { if (string.IsNullOrWhiteSpace(packageSource)) { throw new ArgumentNullException("url"); } if (string.IsNullOrWhiteSpace(packageId)) { throw new ArgumentNullException("packageId"); } if (string.IsNullOrWhiteSpace(downloadDirectory)) { throw new ArgumentNullException("downloadDirectory"); } if (logger == null) { throw new ArgumentNullException("logger"); } logger.LogDebug(UIResources.NG_CreatingRepository, packageSource); IPackageRepository repository = PackageRepositoryFactory.Default.CreateRepository(packageSource); IPackage package = TryGetPackage(repository, packageId, version); if (package != null) { Directory.CreateDirectory(downloadDirectory); IPackageManager manager = new PackageManager(repository, downloadDirectory); manager.Logger = new NuGetLoggerAdapter(this.logger); try { manager.InstallPackage(package, false, false, false); } catch (InvalidOperationException e) { logger.LogError(UIResources.NG_ERROR_PackageInstallFail, e.Message); return null; } } return package; }
public void InstallPackages(string absolutePackagesPath, DirectoryPath contentPath, IConfigurableFileSystem fileSystem, bool updatePackages) { PackageManager packageManager = new PackageManager(_packageRepository, absolutePackagesPath); // On package install... packageManager.PackageInstalled += (sender, args) => { IDirectory packageContentDirectory = fileSystem.GetRootDirectory(contentPath.Combine(args.Package.Id)); // Copy all content files on install and add to input paths bool firstFile = true; foreach (IPackageFile packageFile in args.Package.GetContentFiles()) { if (firstFile) { // This package does have content files, so create the directory and add an input path packageContentDirectory.Create(); fileSystem.InputPaths.Insert(0, packageContentDirectory.Path); firstFile = false; } IFile file = packageContentDirectory.GetFile(packageFile.EffectivePath); file.Directory.Create(); using (var fileStream = file.Open(FileMode.Create)) { packageFile.GetStream().CopyTo(fileStream); } } }; // On package uninstall... packageManager.PackageUninstalling += (sender, args) => { IDirectory packageContentDirectory = fileSystem.GetRootDirectory(contentPath.Combine(args.Package.Id)); packageContentDirectory.Delete(true); }; // Install the packages foreach (Package package in _packages) { package.InstallPackage(packageManager, updatePackages); } }
internal PackageManager(string rootPath = null, string dataTargetDir = null, string pluginTargetDir = null) { // Setup base parameters this.rootPath = rootPath ?? Environment.CurrentDirectory; this.dataTargetDir = dataTargetDir ?? DualityApp.DataDirectory; this.pluginTargetDir = pluginTargetDir ?? DualityApp.PluginDirectory; // Load additional config parameters this.LoadConfig(); // Create internal package management objects this.repository = NuGet.PackageRepositoryFactory.Default.CreateRepository(this.repositoryUrl.AbsoluteUri); this.manager = new NuGet.PackageManager(this.repository, LocalPackageDir); this.manager.PackageInstalled += this.manager_PackageInstalled; this.manager.PackageUninstalled += this.manager_PackageUninstalled; // Update local repository file mappings this.UpdateFileMappings(); }
internal PackageManager(string rootPath = null, string dataTargetDir = null, string pluginTargetDir = null) { // Setup base parameters this.rootPath = rootPath ?? Environment.CurrentDirectory; this.dataTargetDir = dataTargetDir ?? DualityApp.DataDirectory; this.pluginTargetDir = pluginTargetDir ?? DualityApp.PluginDirectory; // Load additional config parameters this.LoadConfig(); // Create internal package management objects this.repository = NuGet.PackageRepositoryFactory.Default.CreateRepository(this.repositoryUrl.AbsoluteUri); this.manager = new NuGet.PackageManager(this.repository, LocalPackageDir); this.manager.PackageInstalled += this.manager_PackageInstalled; this.manager.PackageUninstalled += this.manager_PackageUninstalled; // Retrieve information about local packages this.RetrieveLocalPackageInfo(); }
private void FetchPackages() { if (Config.Packages != null) { IPackageRepository repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2"); PackageManager packageManager = new PackageManager(repo, Config.LibPath); try { foreach (var package in Config.Packages) { packageManager.InstallPackage(package.PackageId, SemanticVersion.Parse(package.Version)); } } catch (Exception ex) { throw new NewProjectException("Could not fetch pacakges",ex); } } }
public NuGetDownloader(string nugetName, IEnumerable<string> repositories) { package = nugetName; var nugetCacheDirectory = Path.Combine(AzureEnvironment.GetTempPath(), "packages"); var reposToUse = new List<IPackageRepository> { PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory) }; if (!AzureEnvironment.IsRunningInCloud()) { reposToUse.Add(MachineCache.Default); } reposToUse.AddRange(repositories.ToList().Select(r => PackageRepositoryFactory.Default.CreateRepository(r))); var repo = new AggregateRepository(reposToUse); packageManager = new PackageManager(repo, /*"packages"*/nugetCacheDirectory); }
public NugetService(Solution solution, IEnumerable<string> remoteFeeds) { var repoBuilder = new PackageRepositoryBuilder(); _remoteRepository = repoBuilder.BuildRemote(remoteFeeds); _localRepository = repoBuilder.BuildLocal(solution.PackagesFolder()); _sourceRepository = repoBuilder.BuildSource(_remoteRepository, _localRepository); _fileSystem = new PhysicalFileSystem(solution.PackagesFolder()); _pathResolver = new DefaultPackagePathResolver(_fileSystem); _console = new Console(); _packageManager = new PackageManager(_sourceRepository, _pathResolver, _fileSystem, _localRepository){ Logger = _console }; _packages = new Cache<NugetDependency, IPackage>(dep => { Install(dep); return _sourceRepository.FindPackage(dep.Name, new SemanticVersion(dep.Version)); }); }
public Form1() { InitializeComponent(); var kerbalPath = ConfigurationManager.AppSettings.Get("kerbalInstallPath"); var serverUrl = ConfigurationManager.AppSettings.Get("kerbalModServer"); txtKerbalPath.Text = kerbalPath; // var modCacheDirectory = kerbalPath + @"\ModCache"; var modCacheDirectory = @"ModCache"; Directory.SetCurrentDirectory(kerbalPath); _PackageRepository = PackageRepositoryFactory.Default.CreateRepository(serverUrl); var localPackageRepository = new LocalPackageRepository(modCacheDirectory); var project = new KerbalProjectSystem(""); _ProjectManager = new ProjectManager(_PackageRepository, new DefaultPackagePathResolver(serverUrl), project, localPackageRepository); _PackageManager = new PackageManager(_PackageRepository, new DefaultPackagePathResolver(serverUrl), project, localPackageRepository); if (!Directory.Exists(modCacheDirectory)) { Directory.CreateDirectory(modCacheDirectory); } lstAvailableMods.DisplayMember = "Description"; lstAvailableMods.ValueMember = "Id"; lstInstalledMods.DisplayMember = "Description"; lstInstalledMods.ValueMember = "Id"; RefreshModLists(); }
internal PackageManager(string rootPath = null, string dataTargetDir = null, string sourceTargetDir = null, string pluginTargetDir = null) { // Setup base parameters this.rootPath = rootPath ?? Environment.CurrentDirectory; this.dataTargetDir = dataTargetDir ?? DualityApp.DataDirectory; this.sourceTargetDir = sourceTargetDir ?? EditorHelper.SourceCodeDirectory; this.pluginTargetDir = pluginTargetDir ?? DualityApp.PluginDirectory; // Load additional config parameters this.LoadConfig(); // Create internal package management objects IPackageRepository[] repositories = this.repositoryUrls.Select(x => this.CreateRepository(x)).Where(x => x != null).ToArray(); this.hasLocalRepo = repositories.OfType <LocalPackageRepository>().Any(); this.repository = new AggregateRepository(repositories); this.manager = new NuGet.PackageManager(this.repository, LocalPackageDir); this.manager.PackageInstalled += this.manager_PackageInstalled; this.manager.PackageUninstalled += this.manager_PackageUninstalled; this.manager.PackageUninstalling += this.manager_PackageUninstalling; // Retrieve information about local packages this.RetrieveLocalPackageInfo(); }
public PackageInstaller() { // TODO:using nuget standard feed (it's a spike). In the future the urls must come from the configuration this.packageRepository = new AggregateRepository(new[] { PackageRepositoryFactory.Default.CreateRepository("https://nuget.org/api/v2/") }); this.themePackageManager = new PackageManager(this.packageRepository, PackageExtensions.ThemesFolder.FullName) { Logger = new NugetLogger() }; this.pluginPackageManager = new PackageManager(this.packageRepository, PackageExtensions.PluginFolder.FullName) { Logger = new NugetLogger() }; this.pluginPackageManager.PackageInstalling += this.PluginPackageManager_PackageInstalling; this.pluginPackageManager.PackageInstalled += this.PluginPackageManager_PackageInstalled; this.pluginPackageManager.PackageUninstalling += this.PluginPackageManager_PackageUninstalling; this.pluginPackageManager.PackageUninstalled += this.PluginPackageManager_PackageUninstalled; }
internal PackageManager(string rootPath = null, string dataTargetDir = null, string sourceTargetDir = null, string pluginTargetDir = null) { // Setup base parameters this.rootPath = rootPath ?? Environment.CurrentDirectory; this.dataTargetDir = dataTargetDir ?? DualityApp.DataDirectory; this.sourceTargetDir = sourceTargetDir ?? EditorHelper.SourceCodeDirectory; this.pluginTargetDir = pluginTargetDir ?? DualityApp.PluginDirectory; // Load additional config parameters this.LoadConfig(); // Create internal package management objects IPackageRepository[] repositories = this.repositoryUrls.Select(x => this.CreateRepository(x)).Where(x => x != null).ToArray(); this.hasLocalRepo = repositories.OfType<LocalPackageRepository>().Any(); this.repository = new AggregateRepository(repositories); this.manager = new NuGet.PackageManager(this.repository, LocalPackageDir); this.manager.PackageInstalled += this.manager_PackageInstalled; this.manager.PackageUninstalled += this.manager_PackageUninstalled; this.manager.PackageUninstalling += this.manager_PackageUninstalling; // Retrieve information about local packages this.RetrieveLocalPackageInfo(); }
public void InstallPackages(string path, Engine engine, bool updatePackages) { PackageManager packageManager = new PackageManager(_packageRepository, path); packageManager.PackageInstalled += (sender, args) => { // Copy all content files on install foreach (IPackageFile packageFile in args.Package.GetContentFiles()) { string filePath = Path.Combine(engine.InputFolder, packageFile.EffectivePath); string filePathDirectory = Path.GetDirectoryName(filePath); if (!Directory.Exists(filePathDirectory)) { Directory.CreateDirectory(filePathDirectory); } using (var fileStream = File.Create(filePath)) { packageFile.GetStream().CopyTo(fileStream); } } }; packageManager.PackageUninstalling += (sender, args) => { // Remove all content files on uninstall foreach (IPackageFile packageFile in args.Package.GetContentFiles()) { string filePath = Path.Combine(engine.InputFolder, packageFile.EffectivePath); if (File.Exists(filePath)) { File.Delete(filePath); } } }; foreach (Package package in _packages) { package.InstallPackage(packageManager, engine, updatePackages); } }
/// <summary> /// Initialize NugetStore using <paramref name="rootDirectory"/> as location of the local copies, /// and a configuration file <paramref name="configFile"/> as well as an override configuration /// file <paramref name="overrideFile"/> where all settings of <paramref name="overrideFile"/> also /// presents in <paramref name="configFile"/> take precedence. /// </summary> /// <param name="rootDirectory">The location of the Nuget store.</param> /// <param name="configFile">The configuration file name for the Nuget store, or <see cref="DefaultConfig"/> if not specified.</param> /// <param name="overrideFile">The override configuration file name for the Nuget store, or <see cref="OverrideConfig"/> if not specified.</param> public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig) { if (rootDirectory == null) { throw new ArgumentNullException(nameof(rootDirectory)); } if (configFile == null) { throw new ArgumentNullException(nameof(configFile)); } if (overrideFile == null) { throw new ArgumentNullException(nameof(overrideFile)); } // First try the override file with custom settings var configFileName = overrideFile; var configFilePath = Path.Combine(rootDirectory, configFileName); if (!File.Exists(configFilePath)) { // Override file does not exist, fallback to default config file configFileName = configFile; configFilePath = Path.Combine(rootDirectory, configFileName); if (!File.Exists(configFilePath)) { throw new ArgumentException($"Invalid installation. Configuration file [{configFile}] not found", nameof(configFile)); } } var rootFileSystem = new PhysicalFileSystem(rootDirectory); RootDirectory = rootFileSystem.Root; settings = new Settings(rootFileSystem, configFileName, false); InstallPath = settings.GetValue(ConfigurationConstants.Config, RepositoryPathKey, true); if (!string.IsNullOrEmpty(InstallPath)) { InstallPath = InstallPath.Replace('/', Path.DirectorySeparatorChar); } var mainPackageList = settings.GetValue(ConfigurationConstants.Config, MainPackagesKey, false); if (string.IsNullOrWhiteSpace(mainPackageList)) { throw new InvalidOperationException($"Invalid configuration. Expecting [{MainPackagesKey}] in config"); } MainPackageIds = mainPackageList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); VsixPluginId = settings.GetValue(ConfigurationConstants.Config, VsixPluginKey, false); if (string.IsNullOrWhiteSpace(VsixPluginId)) { throw new InvalidOperationException($"Invalid configuration. Expecting [{VsixPluginKey}] in config"); } RepositoryPath = settings.GetValue(ConfigurationConstants.Config, RepositoryPathKey, false); if (string.IsNullOrWhiteSpace(RepositoryPath)) { RepositoryPath = DefaultGamePackagesDirectory; } // Setup NugetCachePath in the cache folder CacheDirectory = Path.Combine(rootDirectory, "Cache"); Environment.SetEnvironmentVariable("NuGetCachePath", CacheDirectory); var packagesFileSystem = new PhysicalFileSystem(InstallPath); PathResolver = new PackagePathResolver(packagesFileSystem); var packageSourceProvider = new PackageSourceProvider(settings); SourceRepository = packageSourceProvider.CreateAggregateRepository(new PackageRepositoryFactory(), true); var localRepo = new SharedPackageRepository(PathResolver, packagesFileSystem, rootFileSystem); manager = new NuGet.PackageManager(SourceRepository, PathResolver, packagesFileSystem, localRepo); manager.PackageInstalling += OnPackageInstalling; manager.PackageInstalled += OnPackageInstalled; manager.PackageUninstalling += OnPackageUninstalling; manager.PackageUninstalled += OnPackageUninstalled; }
private void EnsureMultiplePackagesRespected(IReadOnlyCollection <IPackage> currentPackages, NuGet.PackageManager packageManager, string packageId, SemanticVersion packageSemanticVersion, Guid corrId) { if (this.allowMultipleVersionOfPackagesInCache) { return; } const string disallowMultipleVersion = "(Multiple version in cache disabled)"; var packagesToUninstall = currentPackages.Where(p => p.Version != packageSemanticVersion).ToList(); if (!packagesToUninstall.Any()) { return; } foreach (var existingPackage in packagesToUninstall) { this.LogPackageOperation(existingPackage.Id, existingPackage.Version, $"Uninstall from cache {disallowMultipleVersion}", corrId); packageManager.UninstallPackage(existingPackage); } }
/// <summary> /// Binds the repository and the packet manager to a new source. /// </summary> /// <param name="source">Source that gets set.</param> public void SetNewSource(string source) { Repo = PackageRepositoryFactory.Default.CreateRepository(source); _packageManager = new PackageManager(Repo, new DefaultPackagePathResolver(source), new PhysicalFileSystem(RepositoryLocation)); }
/// <summary> /// Uninstalls a package. /// </summary> /// <param name="packageId">The package identifier for the package to be uninstalled.</param> /// <param name="applicationPath">The application path.</param> public void Uninstall(string packageId, string applicationPath) { string solutionPath; string extensionFullPath = string.Empty; if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme))) { extensionFullPath = _virtualPathProvider.MapPath("~/Themes/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme).Length)); } else if (packageId.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module))) { extensionFullPath = _virtualPathProvider.MapPath("~/Modules/" + packageId.Substring(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Module).Length)); } if (string.IsNullOrEmpty(extensionFullPath) || !Directory.Exists(extensionFullPath)) { throw new OrchardException(T("Package not found: {0}", packageId)); } // if we can access the parent directory, and the solution is inside, NuGet-uninstall the package here if (TryGetSolutionPath(applicationPath, out solutionPath)) { // this logger is used to render NuGet's log on the notifier var logger = new NugetLogger(_notifier); var installedPackagesPath = Path.Combine(solutionPath, PackagesPath); var sourcePackageRepository = new LocalPackageRepository(installedPackagesPath); try { var project = new FileBasedProjectSystem(applicationPath) { Logger = logger }; var projectManager = new ProjectManager( sourcePackageRepository, new DefaultPackagePathResolver(installedPackagesPath), project, new ExtensionReferenceRepository(project, sourcePackageRepository, _extensionManager) ) { Logger = logger }; // add the package to the project projectManager.RemovePackageReference(packageId); } catch { // Uninstalling the package at the solution level failed } try { var packageManager = new NuGetPackageManager( sourcePackageRepository, new DefaultPackagePathResolver(applicationPath), new PhysicalFileSystem(installedPackagesPath) { Logger = logger } ) { Logger = logger }; packageManager.UninstallPackage(packageId); } catch { // Package doesnt exist anymore } } // If the package was not installed through nuget we still need to try to uninstall it by removing its directory if (Directory.Exists(extensionFullPath)) { Directory.Delete(extensionFullPath, true); } }
/// <summary> /// Executes a package installation. /// </summary> /// <param name="package">The package to install.</param> /// <param name="packageRepository">The repository for the package.</param> /// <param name="sourceLocation">The source location.</param> /// <param name="targetPath">The path where to install the package.</param> /// <returns>The package information.</returns> protected PackageInfo ExecuteInstall(IPackage package, IPackageRepository packageRepository, string sourceLocation, string targetPath) { // this logger is used to render NuGet's log on the notifier var logger = new NugetLogger(_notifier); bool installed = false; // if we can access the parent directory, and the solution is inside, NuGet-install the package here string solutionPath; var installedPackagesPath = String.Empty; if (TryGetSolutionPath(targetPath, out solutionPath)) { installedPackagesPath = Path.Combine(solutionPath, PackagesPath); try { var packageManager = new NuGetPackageManager( packageRepository, new DefaultPackagePathResolver(sourceLocation), new PhysicalFileSystem(installedPackagesPath) { Logger = logger } ) { Logger = logger }; packageManager.InstallPackage(package, true); installed = true; } catch { // installing the package at the solution level failed } } // if the package got installed successfully, use it, otherwise use the previous repository var sourceRepository = installed ? new LocalPackageRepository(installedPackagesPath) : packageRepository; var project = new FileBasedProjectSystem(targetPath) { Logger = logger }; var projectManager = new ProjectManager( sourceRepository, // source repository for the package to install new DefaultPackagePathResolver(targetPath), project, new ExtensionReferenceRepository(project, sourceRepository, _extensionManager) ) { Logger = logger }; // add the package to the project projectManager.AddPackageReference(package.Id, package.Version); return(new PackageInfo { ExtensionName = package.Title ?? package.Id, ExtensionVersion = package.Version.ToString(), ExtensionType = package.Id.StartsWith(PackagingSourceManager.GetExtensionPrefix(DefaultExtensionTypes.Theme)) ? DefaultExtensionTypes.Theme : DefaultExtensionTypes.Module, ExtensionPath = targetPath }); }
/// <summary> /// Initializes a new instance of the <see cref="Packages"/> class. /// </summary> public Packages() { Repo = PackageRepositoryFactory.Default.CreateRepository(PackageSourceUrl); RepositoryLocation = Path.Combine(AppManager.AbsolutePathToExtensions, AppManager.PackageDirectory); _packageManager = new PackageManager(Repo, new DefaultPackagePathResolver(PackageSourceUrl), new PhysicalFileSystem(RepositoryLocation)); }