Ejemplo n.º 1
0
        public NugetService(Solution solution)
        {
            //_defaultPackageSource = new PackageSource(NuGetConstants.DefaultFeedUrl);

            var factory = new PackageRepositoryFactory();

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

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

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

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

            _packages = new Cache<NugetDependency, IPackage>(dep =>
            {
                Install(dep);
                return _sourceRepository.FindPackage(dep.Name, dep.Version);
            });
        }
Ejemplo n.º 2
0
        public static IPackageRepository Create(IPackageRepositoryFactory factory, IList <PackageSource> sources, bool ignoreFailingRepositories)
        {
            if (sources.Count == 0)
            {
                return(null);
            }
            if (sources.Count == 1)
            {
                return(factory.CreateRepository(sources[0].Source));
            }
            Func <string, IPackageRepository> createRepository = new Func <string, IPackageRepository>(factory.CreateRepository);

            if (ignoreFailingRepositories)
            {
                createRepository = delegate(string source) {
                    try
                    {
                        return(factory.CreateRepository(source));
                    }
                    catch (InvalidOperationException)
                    {
                        return(null);
                    }
                };
            }
            AggregateRepository repository1 = new AggregateRepository(from source in sources
                                                                      let repository = createRepository(source.Source)
                                                                                       where repository != null
                                                                                       select repository);

            repository1.IgnoreFailingRepositories = ignoreFailingRepositories;
            return(repository1);
        }
Ejemplo n.º 3
0
 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);
 }
Ejemplo n.º 4
0
        /// <summary>
        ///     Deletes all files from a package
        /// </summary>
        /// <param name="installed">Insyalled package</param>
        /// <param name="repositories">Repositories where to find the package</param>
        private void DeleteFiles(PackageInfo installed, ICollection<string> repositories)
        {
            Logger.Log("Deleting installed files... ");

            var factory = new PackageRepositoryFactory();

            IPackage package;

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

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

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

            var fylesystem = new PhysicalFileSystem(installed.InstallationDirectory);

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

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

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

            Logger.Log("Installed files deleted");
        }
 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);
 }
Ejemplo n.º 6
0
 internal static IEnumerable <IPackageRepository> Flatten(IEnumerable <IPackageRepository> repositories) =>
 Enumerable.SelectMany <IPackageRepository, IPackageRepository>(repositories, delegate(IPackageRepository repository) {
     AggregateRepository repository2 = repository as AggregateRepository;
     if (repository2 != null)
     {
         return(repository2.Repositories.ToArray <IPackageRepository>());
     }
     return(new IPackageRepository[] { repository });
 });
Ejemplo n.º 7
0
        public NugetStore(string rootDirectory, string configFile = DefaultConfig, string overrideFile = OverrideConfig)
        {
            if (rootDirectory == null) throw new ArgumentNullException("rootDirectory");
            if (configFile == null) throw new ArgumentNullException("configFile");
            if (overrideFile == null) throw new ArgumentNullException("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(String.Format("Invalid installation. Configuration file [{0}] not found", configFile), "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();
            aggregateRepository = packageSourceProvider.CreateAggregateRepository(repositoryFactory, true);

            pathResolver = new DefaultPackagePathResolver(packagesFileSystem);

            manager = new PackageManager(aggregateRepository, pathResolver, packagesFileSystem);

            MainPackageId = Settings.GetConfigValue(MainPackageKey);
            if (string.IsNullOrWhiteSpace(MainPackageId))
            {
                throw new InvalidOperationException(string.Format("Invalid configuration. Expecting [{0}] in config", MainPackageKey));
            }

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

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

            // Setup NugetCachePath in the cache folder
            Environment.SetEnvironmentVariable("NuGetCachePath", Path.Combine(rootDirectory, "Cache", RepositoryPath));
        }
Ejemplo n.º 8
0
 public static IPackageRepository CreatePriorityPackageRepository(this IPackageSourceProvider provider, IPackageRepositoryFactory factory, IPackageRepository primaryRepository)
 {
     PackageSource[] sources = (from s in provider.GetEnabledPackageSources()
                                where !s.Source.Equals(primaryRepository.Source, StringComparison.OrdinalIgnoreCase)
                                select s).ToArray <PackageSource>();
     if (sources.Length == 0)
     {
         return(primaryRepository);
     }
     return(new PriorityPackageRepository(primaryRepository, AggregateRepository.Create(factory, sources, true)));
 }
Ejemplo n.º 9
0
 /// <summary>
 ///     Searches all available versions of a package in a list of repostiories
 /// </summary>
 /// <param name="repositories">Repositories to search</param>
 /// <param name="packageName">Pacakge identifier</param>
 /// <returns>List of available versions</returns>
 public static ICollection<string> Search(ICollection<string> repositories, string packageName)
 {
     var factory = new PackageRepositoryFactory();
     var globalRepo = new AggregateRepository(factory, repositories.Distinct(), true);
     var packages = globalRepo.FindPackagesById(packageName);
     return packages.Select(x => x.Version)
                    .OrderByDescending(x => x)
                    .Select(x => x.ToString())
                    .ToList()
                    .Distinct().ToList() ;
 }
Ejemplo n.º 10
0
        public static Stream DownloadDacpac(string packageName, string version, string repository)
        {
            var factory = new PackageRepositoryFactory();

            IPackage package;

            var globalRepo = new AggregateRepository(factory,new string[] { repository }, true);

            package = globalRepo.FindPackage(packageName, SemanticVersion.Parse(version), true, true);

            var files = package.GetFiles();

            return files.Single(x => x.Path.EndsWith(".dacpac")).GetStream();
        }
 /// <summary>
 ///     Enumerates the installed <see cref="SolutionPackage" />
 /// </summary>
 /// <returns>
 ///     An enumeration of <see cref="SolutionPackage" />.
 /// </returns>
 public IEnumerable<SolutionPackage> Installed()
 {
     var solutions = SPFarm.Local.Solutions.ToList();
     var repository = new AggregateRepository(this.solutionPackageSourceRepository.All().Where(source => source.IsEnabled).Select(source => PackageRepositoryFactory.Default.CreateRepository(source.Source)));
     var solutionPackageGroups = repository.QueryForAbsoluteLatestVersionOfSolutionPackages().ToList().GroupBy(package => package.Id);
     foreach (var solutionPackageGroup in solutionPackageGroups)
     {
         IPackage solutionPackage = solutionPackageGroup.FindByVersion(new VersionSpec(solutionPackageGroup.Max(p => p.Version))).First();
         var solution = solutions.Find(s => s.Name.ToLower().Equals(solutionPackage.Id.ToLower()));
         if (solution != null)
         {
             yield return new SolutionPackage(solutionPackage, solution.GetVersion());
         }
     }
 }
Ejemplo n.º 12
0
    public NuGetDownloader(string nugetName, IEnumerable<string> repositories)
    {
        package = nugetName;

        var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache");

        var reposToUse = new List<IPackageRepository>
        {
            PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory)
        };

        reposToUse.AddRange(repositories.ToList().Select(r => PackageRepositoryFactory.Default.CreateRepository(r)));
        var repo = new AggregateRepository(reposToUse);

        packageManager = new PackageManager(repo, "packages");
    }
        public static AggregateRepository CreateAggregateRepositoryFromSources(IPackageRepositoryFactory factory, IPackageSourceProvider sourceProvider, IEnumerable<string> sources)
        {
            AggregateRepository repository;
            if (sources != null && sources.Any())
            {
                var repositories = sources.Select(s => sourceProvider.ResolveSource(s))
                                             .Select(factory.CreateRepository)
                                             .ToList();
                repository = new AggregateRepository(repositories);
            }
            else
            {
                repository = sourceProvider.GetAggregate(factory, ignoreFailingRepositories: true);
            }

            return repository;
        }
        public static IPackageRepository CreatePriorityPackageRepository(
            this IPackageSourceProvider provider,
            IPackageRepositoryFactory factory,
            IPackageRepository primaryRepository)
        {
            var nonActivePackageSources = provider.GetEnabledPackageSources()
                                          .Where(s => !s.Source.Equals(primaryRepository.Source, StringComparison.OrdinalIgnoreCase))
                                          .ToArray();

            if (nonActivePackageSources.Length == 0)
            {
                return(primaryRepository);
            }

            var fallbackRepository = AggregateRepository.Create(factory, sources: nonActivePackageSources, ignoreFailingRepositories: true);

            return(new PriorityPackageRepository(primaryRepository, fallbackRepository));
        }
Ejemplo n.º 15
0
        public IPackageManager CreatePackageManager(IEnumerable<string> remoteSources, string packagesPath)
        {
            if (remoteSources == null)
            {
                throw new ArgumentNullException("remoteSources");
            }
            if (!remoteSources.Any())
            {
                throw new ArgumentException("Must provide at least one remote source");
            }

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

            return new PackageManager(sourceRepository: sourceRepo,
                                        pathResolver: pathResolver,
                                        fileSystem: packageManagerFileSystem);
        }
Ejemplo n.º 16
0
        public IProjectManager CreateProjectManager(IEnumerable<string> remoteSources, string packagesPath, IProjectSystem project)
        {
            if(remoteSources == null)
            {
                throw new ArgumentNullException("remoteSources");
            }
            if (!remoteSources.Any())
            {
                throw new ArgumentException("Must provide at least one remote source");
            }

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

            var packagesConfigRepo = new PackageReferenceRepository(project, project.ProjectName, new SharedPackageRepository(packagesPath));

            return new ProjectManager(sourceRepository: sourceRepo,
                                        pathResolver: pathResolver,
                                        localRepository: packagesConfigRepo,
                                        project: project);
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        public static IPackageRepository GetRemoteRepository(ChocolateyConfiguration configuration, ILogger nugetLogger)
        {
            IEnumerable<string> sources = configuration.Sources.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries);

            IList<IPackageRepository> repositories = new List<IPackageRepository>();

            // ensure credentials can be grabbed from configuration
            HttpClient.DefaultCredentialProvider = new ChocolateyNugetCredentialProvider(configuration);

            foreach (var source in sources.or_empty_list_if_null())
            {
                try
                {
                    var uri = new Uri(source);
                    if (uri.IsFile || uri.IsUnc)
                    {
                        repositories.Add(new ChocolateyLocalPackageRepository(uri.LocalPath));
                    }
                    else
                    {
                      repositories.Add(new DataServicePackageRepository(new RedirectedHttpClient(uri)));
                    }
                }
                catch (Exception)
                {
                    repositories.Add(new ChocolateyLocalPackageRepository(source));
                }
            }

            //todo well that didn't work on failing repos... grrr
            var repository = new AggregateRepository(repositories) {IgnoreFailingRepositories = true};
            repository.ResolveDependenciesVertically = true;
            if (configuration.Debug)
            {
                repository.Logger = nugetLogger;
            }

            return repository;
        }
    public void ApproveNServiceBus()
    {
        var packages = new[]
        {
            "4.6.4", "5.0.0-beta0004"
        };

        var nugetCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Cache");
        var repo = new AggregateRepository(new[]
        {
            PackageRepositoryFactory.Default.CreateRepository(nugetCacheDirectory),
            PackageRepositoryFactory.Default.CreateRepository("https://www.nuget.org/api/v2"),
            PackageRepositoryFactory.Default.CreateRepository("https://www.myget.org/F/particular/"),
        });

        var packageManager = new PackageManager(repo, "packages");

        foreach (var v in packages)
        {
            if (!Directory.Exists(Path.Combine("packages", "NServiceBus." + v)))
                packageManager.InstallPackage("NServiceBus", SemanticVersion.Parse(v));
        }

        var file1 = Path.Combine("packages", "NServiceBus." + packages[0], "lib", "net40", "NServiceBus.Core.dll");
        var file2 = Path.Combine("packages", "NServiceBus." + packages[1], "lib", "net45", "NServiceBus.Core.dll");

        var engine = new ComparerEngine();

        var diff = engine.CreateDiff(file1, file2);

        var stringBuilder = new StringWriter();
        var formatter = new APIUpgradeToMarkdownFormatter();
        formatter.WriteOut(diff, stringBuilder, new FormattingInfo(string.Empty, string.Empty));

        Approvals.Verify(stringBuilder.ToString());
    }
Ejemplo n.º 20
0
 public IRepository GetUpdateAggeregateRepository()
 {            
     return _repositoryCacheService.GetSerializableRepository(RepositoryName.All, "all", PackageOperationType.Update, () =>
     {
         var packageSources = GetPackageSources();
         var sourceRepository = new AggregateRepository(_repositoryFactory, packageSources.Select(x => x.Source), true);
         return new UpdateRepository(LocalNuGetRepository, sourceRepository);
     }, true);
 }
Ejemplo n.º 21
0
        public static IPackageRepository GetRemoteRepository(ChocolateyConfiguration configuration, ILogger nugetLogger)
        {
            IEnumerable<string> sources = configuration.Sources.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries);

            IList<IPackageRepository> repositories = new List<IPackageRepository>();

            // ensure credentials can be grabbed from configuration
            HttpClient.DefaultCredentialProvider = new ChocolateyNugetCredentialProvider(configuration);
            HttpClient.DefaultCertificateProvider = new ChocolateyClientCertificateProvider(configuration);
            if (!string.IsNullOrWhiteSpace(configuration.Proxy.Location))
            {
                "chocolatey".Log().Debug("Using proxy server '{0}'.".format_with(configuration.Proxy.Location));
                var proxy = new WebProxy(configuration.Proxy.Location, true);

                if (!String.IsNullOrWhiteSpace(configuration.Proxy.User) && !String.IsNullOrWhiteSpace(configuration.Proxy.EncryptedPassword))
                {
                    proxy.Credentials = new NetworkCredential(configuration.Proxy.User, NugetEncryptionUtility.DecryptString(configuration.Proxy.EncryptedPassword));
                }

                ProxyCache.Instance.Override(proxy);
            }

            var updatedSources = new StringBuilder();
            foreach (var sourceValue in sources.or_empty_list_if_null())
            {

                var source = sourceValue;
                if (configuration.MachineSources.Any(m => m.Name.is_equal_to(source)))
                {
                    "chocolatey".Log().Debug("Switching source name {0} to actual source value.".format_with(sourceValue));
                    try
                    {
                        source = configuration.MachineSources.FirstOrDefault(m => m.Name.is_equal_to(source)).Key;
                    }
                    catch (Exception ex)
                    {
                        "chocolatey".Log().Warn("Attempted to use a source name {0} to get default source but failed:{1} {2}".format_with(sourceValue, Environment.NewLine, ex.Message));
                    }
                }

                updatedSources.AppendFormat("{0};", source);

                try
                {
                    var uri = new Uri(source);
                    if (uri.IsFile || uri.IsUnc)
                    {
                        repositories.Add(new ChocolateyLocalPackageRepository(uri.LocalPath));
                    }
                    else
                    {
                      repositories.Add(new DataServicePackageRepository(new RedirectedHttpClient(uri)));
                    }
                }
                catch (Exception)
                {
                    repositories.Add(new ChocolateyLocalPackageRepository(source));
                }
            }

            if (updatedSources.Length != 0)
            {
                configuration.Sources = updatedSources.Remove(updatedSources.Length - 1, 1).to_string();
            }

            //todo well that didn't work on failing repos... grrr
            var repository = new AggregateRepository(repositories) {IgnoreFailingRepositories = true};
            repository.ResolveDependenciesVertically = true;
            if (configuration.Debug)
            {
                repository.Logger = nugetLogger;
            }

            return repository;
        }
Ejemplo n.º 22
0
 protected virtual IPackageRepository GetRepository() {
     var aggregateRepository = AggregateRepositoryHelper.CreateAggregateRepositoryFromSources(RepositoryFactory, SourceProvider, (IEnumerable<string>)Source);
     var failingRepositories = aggregateRepository.IgnoreFailingRepositories;
     if (!NoCache)
         aggregateRepository = new AggregateRepository((IEnumerable<IPackageRepository>)new IPackageRepository[2] {
             CacheRepository,
             (IPackageRepository)aggregateRepository
         }) {
             IgnoreFailingRepositories = failingRepositories
         };
     aggregateRepository.Logger = (ILogger)Console;
     return (IPackageRepository)aggregateRepository;
 }
Ejemplo n.º 23
0
        /// <summary>
        /// </summary>
        private int Run(Assembly integrationAgentAssembly, string integrationAgentExeFileName, string integrationAgentExeDirectory, string[] args)
        {
            var parameters = Program.ParseArguments(args);
            var fileVersion = FileVersionInfo.GetVersionInfo(integrationAgentAssembly.Location).FileVersion;

            if (parameters.ShowVersion || parameters.ShowHelp)
            {
                Console.WriteLine("IntegrationAgent  v" + fileVersion);
            }

            if (parameters.ShowHelp)
            {
                Program.ShowHelp();
            }

            if (parameters.ShowVersion || parameters.ShowHelp)
            {
                return 0;
            }

            // Verify that assembly is signed and uses the correct key
            var traceWriter = Program.CreateTraceWriter(parameters.TraceLevel);
            traceWriter(TraceLevel.Verbose, "Checking assembly strong name.");
            if (!integrationAgentAssembly.HasValidStrongName())
            {
                traceWriter(TraceLevel.Error, "Unsigned assembly!");
                return 1;
            }
            traceWriter(TraceLevel.Verbose, "Verifying assembly signature.");
            if (!integrationAgentAssembly.PublicKeyTokenEqualsTo(Token.Bytes))
            {
                traceWriter(TraceLevel.Error, "Invalid assembly!");
                return 2;
            }

            // If no JSON config file name provided as paramter uses the application name
            traceWriter(TraceLevel.Verbose, "Looking for JSON config file.");
            var configFile = Path.Combine(integrationAgentExeDirectory, Path.GetFileNameWithoutExtension(integrationAgentExeFileName) + ".json");
            if (!string.IsNullOrEmpty(parameters.Config))
            {
                if (!parameters.Config.EndsWith(".json"))
                {
                    parameters.Config = parameters.Config + ".json";
                }
                configFile = Path.Combine(integrationAgentExeDirectory, parameters.Config);
            }

            // Check and reads the configuration file
            var configuration = new Configuration();
            if (File.Exists(configFile))
            {
                traceWriter(TraceLevel.Verbose, "Reading the JSON config file.");
                var configJson = File.ReadAllText(configFile);
                var jsonSerializer = new JavaScriptSerializer();
                configuration = jsonSerializer.Deserialize<Configuration>(configJson) ?? configuration;
                traceWriter(TraceLevel.Verbose, "JSON config file loaded.");
            }

            // Merges config file and command line parameters. Command line paramters have precedence.
            configuration.package = parameters.Package ?? configuration.package;
            configuration.token = parameters.Token ?? configuration.token;
            configuration.repository = parameters.Repository ?? configuration.repository;
            configuration.repositoryUsername = parameters.RepositoryUsername ?? configuration.repositoryUsername;
            configuration.repositoryPassword = parameters.RepositoryPassword ?? configuration.repositoryPassword;

            traceWriter(TraceLevel.Verbose, "Checking input parameters.");
            if (string.IsNullOrWhiteSpace(configuration.package) && string.IsNullOrEmpty(configuration.token))
            {
                traceWriter(TraceLevel.Error, "Invalid configuration!");
                return 3;
            }

            // Initializes NuGet repositories
            traceWriter(TraceLevel.Verbose, "Initializing NuGet repositories.");
            var nugetRepository = new DataServicePackageRepository(new Uri(NuGetRepository));
            var aggregateRepository = new AggregateRepository(new[] { nugetRepository });
            if (Uri.IsWellFormedUriString(configuration.repository, UriKind.Absolute))
            {
                if (!string.IsNullOrWhiteSpace(configuration.repositoryUsername) &&
                    !string.IsNullOrWhiteSpace(configuration.repositoryPassword))
                {
                    HttpClient.DefaultCredentialProvider = new NugetCredentialProvider(
                        configuration.repositoryUsername, configuration.repositoryPassword);
                }
                var client = new HttpClient(new Uri(configuration.repository));
                var customRepository = new DataServicePackageRepository(client);
                aggregateRepository = new AggregateRepository(new[] { customRepository, nugetRepository });
            }

            // Perform auto-update if not disabled
            if (!parameters.DisableUpdates)
            {
                traceWriter(TraceLevel.Verbose, "Checking for self update.");
                var integrationAgentAssemblyName = integrationAgentAssembly.GetName();
                var version = new SemanticVersion(integrationAgentAssemblyName.Version);
                var package = aggregateRepository
                    .GetUpdates(new[] { new PackageName(integrationAgentAssemblyName.Name, version) }, includePrerelease: false, includeAllVersions: false)
                    .OrderBy(p => p.Version)
                    .LastOrDefault();

                if (package != null && package.Version > version)
                {
                    traceWriter(TraceLevel.Verbose, "Newer version found. Updating files.");
                    var filename = Path.GetFileName(integrationAgentExeFileName);
                    var file = package.GetFiles().FirstOrDefault(f => !string.IsNullOrEmpty(f.Path) && Path.GetFileName(f.Path).Equals(filename, StringComparison.OrdinalIgnoreCase));
                    if (file != null)
                    {
                        File.Delete(integrationAgentExeFileName + ".bak");
                        File.Move(integrationAgentExeFileName, integrationAgentExeFileName + ".bak");
                        using (Stream fromStream = file.GetStream(), toStream = File.Create(integrationAgentExeFileName))
                        {
                            fromStream.CopyTo(toStream);
                        }
                        Process.Start(integrationAgentExeFileName, string.Join(" ", args) + " -disableupdates");
                        Environment.Exit(0);
                    }
                }
                else
                {
                    traceWriter(TraceLevel.Verbose, "Version is up to date.");
                }
            }

            // Install the package to run including its dependencies
            traceWriter(TraceLevel.Verbose, "Checking for execution package.");
            var packagesPath = Path.Combine(integrationAgentExeDirectory, "packages");
            var remotePackage = aggregateRepository.FindPackagesById(configuration.package).OrderBy(p => p.Version).LastOrDefault();
            var localRepository = new SharedPackageRepository(packagesPath);
            if (!localRepository.Exists(remotePackage))
            {
                traceWriter(TraceLevel.Verbose, "Execution package not found localy. Installing remote.");
                var packageManager = new PackageManager(aggregateRepository, packagesPath);
                packageManager.InstallPackage(remotePackage, ignoreDependencies: false, allowPrereleaseVersions: false);
            }

            var localPackage = localRepository.FindPackagesById(configuration.package).OrderBy(p => p.Version).LastOrDefault();
            if (localPackage == null)
            {
                traceWriter(TraceLevel.Error, "Package not found!");
                return 4;
            }

            // Build a dictionary list of assemblies based on assembly fully qualified name for dynamically resolving from the loaded package
            traceWriter(TraceLevel.Verbose, "Resolving execution package dependencies.");
            var allAssemblies = localRepository
                .GetPackages()
                .ToArray()
                .SelectMany(p => p.AssemblyReferences.Select(a =>
                {
                    var path = Path.Combine(packagesPath, p.Id + "." + p.Version, a.Path);
                    var aname = AssemblyName.GetAssemblyName(path);
                    return new { key = aname.FullName, value = path };
                }))
                .DistinctBy(i => i.key)
                .ToDictionary(i => i.key, i => i.value);
            AppDomain.CurrentDomain.AssemblyResolve += (sender, eventArgs) =>
            {
                var aname = new AssemblyName(eventArgs.Name);
                if (allAssemblies.ContainsKey(aname.FullName))
                {
                    return Assembly.LoadFile(allAssemblies[aname.FullName]);
                }
                return null;
            };

            // Run the package export delegate if found
            var assemblies = localPackage.AssemblyReferences.Select(a => new AssemblyCatalog(Path.Combine(packagesPath, localPackage.Id + "." + localPackage.Version, a.Path)));
            using (var catalog = new AggregateCatalog(assemblies))
            using (var container = new CompositionContainer(catalog))
            {
                traceWriter(TraceLevel.Verbose, "Resolving execution package entry point.");
                container.SatisfyImportsOnce(this);
                if (this.RunAssembly == null)
                {
                    traceWriter(TraceLevel.Error, "Execution package extry point not found!");
                    return 5;
                }
                traceWriter(TraceLevel.Verbose, "Invoking execution package extry point.");
                this.RunAssembly(configuration.token, traceWriter);
                traceWriter(TraceLevel.Verbose, "Execution package finished successfully.");
                return 0;
            }
        }
Ejemplo n.º 24
0
        public static IPackageRepository GetRemoteRepository(ChocolateyConfiguration configuration, ILogger nugetLogger)
        {
            IEnumerable<string> sources = configuration.Sources.Split(new[] {";", ","}, StringSplitOptions.RemoveEmptyEntries);

            IList<IPackageRepository> repositories = new List<IPackageRepository>();

            // ensure credentials can be grabbed from configuration
            HttpClient.DefaultCredentialProvider = new ChocolateyNugetCredentialProvider(configuration);
            if (!string.IsNullOrWhiteSpace(configuration.Proxy.Location))
            {
                "chocolatey".Log().Debug("Using proxy server '{0}'.".format_with(configuration.Proxy.Location));
                var proxy = new WebProxy(configuration.Proxy.Location, true);

                if (!String.IsNullOrWhiteSpace(configuration.Proxy.User) && !String.IsNullOrWhiteSpace(configuration.Proxy.EncryptedPassword))
                {
                    proxy.Credentials = new NetworkCredential(configuration.Proxy.User, NugetEncryptionUtility.DecryptString(configuration.Proxy.EncryptedPassword));
                }
                
                ProxyCache.Instance.Override(proxy);
            }

            foreach (var source in sources.or_empty_list_if_null())
            {
                try
                {
                    var uri = new Uri(source);
                    if (uri.IsFile || uri.IsUnc)
                    {
                        repositories.Add(new ChocolateyLocalPackageRepository(uri.LocalPath));
                    }
                    else
                    {
                      repositories.Add(new DataServicePackageRepository(new RedirectedHttpClient(uri)));
                    }
                }
                catch (Exception)
                {
                    repositories.Add(new ChocolateyLocalPackageRepository(source));
                }
            }

            //todo well that didn't work on failing repos... grrr
            var repository = new AggregateRepository(repositories) {IgnoreFailingRepositories = true};
            repository.ResolveDependenciesVertically = true;
            if (configuration.Debug)
            {
                repository.Logger = nugetLogger;
            }

            return repository;
        }
		public void Logger_SetLoggerWhenSourceRepositoryIsAggregateRepository_LoggerOnAggregateRepositoryIsSet ()
		{
			var aggregateRepository = new AggregateRepository (new FakePackageRepository [0]);
			CreateProject (aggregateRepository);
			var expectedLogger = new FakeLogger ();

			project.Logger = expectedLogger;

			Assert.AreEqual (expectedLogger, aggregateRepository.Logger);
		}
Ejemplo n.º 26
0
        /// <summary>
        ///     Downloads the specified package and installs it in the configured folder
        /// </summary>
        /// <param name="info">Pacakge informations</param>
        private void DownloadPackage(PackageInfo info, ICollection<string> repositories)
        {
            Logger.Log(String.Format("Downloading package for {0} version {1} ... ", info.Name, info.Version));

            var factory = new PackageRepositoryFactory();

            IPackage package;

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

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

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

            var manager = new PackageManager(
                globalRepo,
                new CustomPathResolver() { BasePath = info.InstallationDirectory },
                new OverWritingPhysicalFilesystem(info.InstallationDirectory));

            manager.InstallPackage(package, false, true);

            Logger.Log(String.Format("Package for {0} version {1} downloaded ... ", info.Name, info.Version));
        }
Ejemplo n.º 27
0
        protected virtual IPackageRepository GetAvailableRepository()
        {
            var repositories = new List<IPackageRepository>
            {
                PackageRepositoryFactory.Default.CreateRepository(AvailableRepository)
            };

            var packageSources = FileUtil.MapPath("/sitecore/shell/client/Applications/Pathfinder/PackageSources.txt");
            if (File.Exists(packageSources))
            {
                var sources = File.ReadAllLines(packageSources);
                foreach (var source in sources)
                {
                    if (string.IsNullOrEmpty(source.Trim()))
                    {
                        continue;
                    }

                    repositories.Add(PackageRepositoryFactory.Default.CreateRepository(source));
                }
            }

            var aggregateRepository = new AggregateRepository(repositories);
            return aggregateRepository;
        }
Ejemplo n.º 28
0
        private async Task Initialize()
        {
            var listEndpoints = await GetListEndpointsAsync(_sourceProvider).ConfigureAwait(false);

            var repositoryFactory = new PackageRepositoryFactory();

            var repositories = listEndpoints
                .Select(s => repositoryFactory.CreateRepository(s))
                .ToList();

            _repository = new AggregateRepository(repositories);
        }
        private static void AssertExpectedPackageSources(AggregateRepository actualRepo, params string[] expectedSources)
        {
            foreach(string expectedSource in expectedSources)
            {
                Assert.IsTrue(actualRepo.Repositories.Any(r => string.Equals(r.Source, expectedSource)),
                    "Expected package source does not exist: {0}", expectedSource);
            }

            Assert.AreEqual(expectedSources.Length, actualRepo.Repositories.Count(), "Too many repositories returned");
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            var orchardDirectory = args[0];
            var inputDirectory = args[1];
            var outputDirectory = args[2];
            var cacheDirectory = args[3];

            var cacheFileSystem = new PhysicalFileSystem(cacheDirectory);
            var cachePackageResolver = new DefaultPackagePathResolver(cacheFileSystem, false);

            var orchardRepository = new AggregateRepository(new IPackageRepository[]
                {
                    new LocalPackageRepository(orchardDirectory),
                    new DataServicePackageRepository(new Uri("http://nuget.org/api/v2")),
                });

            var orchardManager = new PackageManager(orchardRepository, cachePackageResolver, cacheFileSystem);

            var inputRepository = new LocalPackageRepository(inputDirectory);
            var inputManager = new PackageManager(inputRepository, cachePackageResolver, cacheFileSystem);

            var references = new[] { "Orchard.Core", "Orchard.Framework", "Orchard.External" };

            foreach (var reference in references)
                orchardManager.InstallPackage(orchardRepository.FindPackage(reference), false, false);

            foreach (var inputPackage in inputRepository.GetPackages().Where(p => p.Id.StartsWith("Orchard.Module.")))
            {
                Do(inputRepository, inputManager, inputPackage, cacheDirectory, references, outputDirectory);
            }
        }