static void Main() { var repo = new LocalPackageRepository(@"C:\Code\Common\Group\Business-Logic\packages"); IQueryable <IPackage> packages = repo.GetPackages(); OutputGraph(repo, packages, 0); }
public IEnumerable <string> CreatePackageFile() { var packagesFile = Path.Combine(_fileSystem.CurrentDirectory, Constants.PackagesFile); var packageReferenceFile = new PackageReferenceFile(packagesFile); var packagesFolder = Path.Combine(_fileSystem.CurrentDirectory, Constants.PackagesFolder); var repository = new LocalPackageRepository(packagesFolder); var newestPackages = repository.GetPackages().GroupBy(p => p.Id) .Select(g => g.OrderByDescending(p => p.Version).FirstOrDefault()); foreach (var package in newestPackages) { var newestFramework = GetNewestSupportedFramework(package); packageReferenceFile.AddEntry(package.Id, package.Version, newestFramework); if (newestFramework == null) { yield return(string.Format("{0}, Version {1}", package.Id, package.Version)); } else { yield return(string.Format("{0}, Version {1}, .NET {2}", package.Id, package.Version, newestFramework.Version)); } } }
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); } }
public IEnumerable <IPackage> GetAllPackages(string rootFolder) //rootFolder is repository root { var targetFolder = rootFolder.AppendPath(PackagesFolder); var packagePathResolver = new DefaultPackagePathResolver(targetFolder); var packagesFolderFileSystem = new PhysicalFileSystem(targetFolder); var localRepository = new LocalPackageRepository(packagePathResolver, packagesFolderFileSystem); return(localRepository.GetPackages()); }
internal static IPackage GetLastestVersionPackage(string packageDir, string packageId) { var repo = new LocalPackageRepository(Path.GetFullPath(packageDir)); var pkgs = repo.GetPackages().ToArray(); var targetPackages = pkgs.Where(x => x.Id == packageId).ToArray(); var newbePk = targetPackages.First(x => x.Id == packageId && x.Version == targetPackages.Max(a => a.Version)); return(newbePk); }
public void GetPackagesOnlyRetrievesPackageFilesWhereLastModifiedIsOutOfDate() { // Arrange var mockFileSystem = new Mock <MockProjectSystem>() { CallBase = true }; var lastModified = new Dictionary <string, DateTimeOffset>(); mockFileSystem.Setup(m => m.GetLastModified("P1.nupkg")).Returns(() => lastModified["P1.nupkg"]); mockFileSystem.Setup(m => m.GetLastModified("P2.nupkg")).Returns(() => lastModified["P2.nupkg"]); mockFileSystem.Object.AddFile("P1.nupkg"); mockFileSystem.Object.AddFile("P2.nupkg"); var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem.Object), mockFileSystem.Object); var results = new List <string>(); Func <string, IPackage> openPackage = p => { results.Add(p); string id = Path.GetFileNameWithoutExtension(p); return(PackageUtility.CreatePackage(id, "1.0")); }; // Populate cache lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 30); lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30); repository.GetPackages(openPackage).ToList(); // Verify that both packages have been created from the file system Assert.Equal(2, results.Count); results.Clear(); // Act lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 35); lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30); repository.GetPackages(openPackage).ToList(); // Assert Assert.Equal(results.Count, 1); Assert.Equal(results[0], "P1.nupkg"); }
public void OpenPackagePrintsPathToPackageIfItCannotBeRead() { // Arrange var fileSystem = new MockFileSystem(); fileSystem.AddFile(@"Foo.nupkg"); var pathResolver = new DefaultPackagePathResolver(fileSystem); var repository = new LocalPackageRepository(pathResolver, fileSystem); // Act and Assert ExceptionAssert.Throws <InvalidDataException>(() => repository.GetPackages().ToList(), "Unable to read package from path 'Foo.nupkg'."); }
static void Main(string[] args) { Console.Write("Enter the local repo folder (ie C:\\...\\packages\\) : "); var repoFolder = Console.ReadLine(); var repo = new LocalPackageRepository(repoFolder); IQueryable <IPackage> packages = repo.GetPackages(); OutputGraph(repo, packages, 0); Console.Write("Press enter to exit :"); Console.ReadLine(); }
public IEnumerable <IPackageReference> FindReferences(string path) { var packageReferenceFile = new PackageReferenceFile(path); var references = packageReferenceFile.GetPackageReferences().ToList(); if (references.Any()) { foreach (var packageReference in references) { yield return(new PackageReference( packageReference.Id, packageReference.TargetFramework, packageReference.Version.Version, packageReference.Version.SpecialVersion)); } yield break; } // No packages.config, check packages folder var packagesFolder = Path.Combine(_fileSystem.GetWorkingDirectory(path), _fileSystem.PackagesFolder); if (!_fileSystem.DirectoryExists(packagesFolder)) { yield break; } var repository = new LocalPackageRepository(packagesFolder); var arbitraryPackages = repository.GetPackages(); if (!arbitraryPackages.Any()) { yield break; } foreach (var arbitraryPackage in arbitraryPackages) { var newestFramework = GetNewestSupportedFramework(arbitraryPackage) ?? VersionUtility.EmptyFramework; yield return(new PackageReference( arbitraryPackage.Id, newestFramework, arbitraryPackage.Version.Version, arbitraryPackage.Version.SpecialVersion)); } }
private static string GetLatestPackageVersion(string dependencyId, string dependencyVersion, string destination) { string lastVersion = dependencyVersion; var localRepo = new LocalPackageRepository(destination); var packagesById = from p in localRepo.GetPackages() where p.Id == dependencyId select p; if (packagesById.Any()) { lastVersion = packagesById.Select(m => m.Version) .Max().ToString(); } return(lastVersion); }
public static void Main(string[] args) { var frameworkName = new FrameworkName(".NETFramework, Version=4.0"); var repository = new LocalPackageRepository(@"C:\Users\ggherardi\AppData\Local\NuGet\Cache"); const bool prerelease = false; var packages = repository.GetPackages() .Where(p => prerelease ? p.IsAbsoluteLatestVersion : p.IsLatestVersion) .Where(p => VersionUtility.IsCompatible(frameworkName, p.GetSupportedFrameworks())); foreach (IPackage package in packages) { GetValue(repository, frameworkName, package, prerelease, 0); } Console.WriteLine(); Console.WriteLine("Press Enter..."); Console.ReadLine(); }
static void Main() { Console.Write("Enter the local repo folder: "); var repoFolder = Console.ReadLine(); while (true) { Console.Write("Enter the dependency id matching criteria: "); var criteria = Console.ReadLine(); var repo = new LocalPackageRepository(repoFolder); IQueryable <IPackage> packages = repo.GetPackages().Where(p => p.Id.Contains(criteria)); OutputGraph(repo, packages, 0, 1); Console.ReadKey(); } }
static void Main() { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); var repo = new LocalPackageRepository(@"\\Mac\Home\Documents\Visual Studio 2015\Projects\ConsoleApplication1\packages"); IQueryable <IPackage> packages = repo.GetPackages(); ECSDependecy basePkg = new ECSDependecy { versions = new List <String> { "1.0-SNAPSHOT" }, key = "nuget:demo", name = "Basismodul", dependencies = new List <ECSDependecy>() }; OutputGraph(repo, packages, 0, basePkg); OutputECSGraph(0, basePkg); ECSArtifact artifact = new ECSArtifact { project = "Mein Demo Projekt", moduleId = "nuget.demo", module = "Artefakt 1", dependencies = new List <ECSDependecy> { basePkg } }; var client = new RestClient("https://ecs-app.eacg.de"); client.Proxy = new System.Net.WebProxy("http://*****:*****@eacg.de"); request.AddHeader("x-apikey", "a301eb79-2fd5-4ef8-820d-33df5f9a188a"); client.Execute(request); //Console.ReadLine(); }
public void CreatePackageFile() { var packagesFile = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFile); var packageReferenceFile = new PackageReferenceFile(packagesFile); var packagesFolder = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFolder); var repository = new LocalPackageRepository(packagesFolder); var newestPackages = repository.GetPackages().GroupBy(p => p.Id) .Select(g => g.OrderByDescending(p => p.Version).FirstOrDefault()); if (!newestPackages.Any()) { _logger.Info("No packages found!"); return; } _logger.InfoFormat("{0} {1}...", (File.Exists(packagesFile) ? "Updating" : "Creating"), _fileSystem.PackagesFile); foreach (var package in newestPackages) { var newestFramework = GetNewestSupportedFramework(package); if (!packageReferenceFile.EntryExists(package.Id, package.Version)) { packageReferenceFile.AddEntry(package.Id, package.Version, package.DevelopmentDependency, newestFramework); if (newestFramework == null) { _logger.InfoFormat("Added {0} (v{1}) to {2}", package.Id, package.Version, _fileSystem.PackagesFile); } else { _logger.InfoFormat("Added {0} (v{1}, .NET {2}) to {3}", package.Id, package.Version, newestFramework.Version, _fileSystem.PackagesFile); } continue; } _logger.InfoFormat("Skipped {0} because it already exists.", package.Id); } _logger.InfoFormat("Successfully {0} {1}.", (File.Exists(packagesFile) ? "updated" : "created"), _fileSystem.PackagesFile); }
private static void ComputePackages(string nugetPath) { var repository = new LocalPackageRepository(nugetPath); foreach (var dependency in Dependencies) { foreach (IPackage package in repository.GetPackages()) { var files = package.GetFiles(); if (files.Any(f => f.Path.Contains(dependency.Key))) { if (!Packages.ContainsKey(dependency.Key)) { Packages[dependency.Key] = package; } } } } }
internal void VerifyPackage(string filename) { try { Log.InfoFormat("Creating verify path {0}", filename); var fi = new FileInfo(filename); var tempPath = new FileInfo( Path.Combine( Path.GetTempPath(), "octgn", Guid.NewGuid().ToString(), fi.Name.Replace(fi.Extension, ".nupkg"))); if (!File.Exists(filename)) { Log.InfoFormat("Package magically disappeared {0}", filename); return; } Log.InfoFormat("Creating directory {0}", filename); if (!Directory.Exists(tempPath.Directory.FullName)) { Directory.CreateDirectory(tempPath.Directory.FullName); } Log.InfoFormat("Copying file {0}", filename); fi.MegaCopyTo(tempPath); Log.InfoFormat("Creating repo to make sure it loads {0}", filename); var repo = new LocalPackageRepository(tempPath.Directory.FullName); Log.InfoFormat("Loading repo into array to make sure it works {0}", filename); var arr = repo.GetPackages().ToArray(); Log.InfoFormat("Fully verified {0}", filename); } catch (Exception e) { Log.WarnFormat("Package not valid {0}", filename); throw new UserMessageException("The file {0} is invalid.", filename); } finally { Log.InfoFormat("Finished {0}", filename); } }
public override void CreatePackageFile() { var packagesFile = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFile); var packagesFolder = Path.Combine(_fileSystem.CurrentDirectory, _fileSystem.PackagesFolder); var repository = new LocalPackageRepository(packagesFolder); var packages = repository.GetPackages().OrderByDescending(x => x.Version); var configFile = new JObject(); var dependencyObject = new JObject(); configFile.Add("dependencies", dependencyObject); foreach (var package in packages) { if (dependencyObject[package.Id] == null) { dependencyObject.Add(new JProperty(package.Id, package.Version.ToString())); } } File.WriteAllText(packagesFile, configFile.ToString()); }
public void GetPackageReturnsPackagesFromNestedDirectories() { // Arrange string id = "Test"; string version = "1.3.1.0"; string packageName = @"SubDir\Test.1.3.1.nupkg"; var repositoryRoot = CreatePackage(id, version, packageName); CreatePackage(id, "1.3.4", "Test.nupkg", repositoryRoot); CreatePackage("Foo", "1.4", @"SubDir2\Test.1.4.nupkg", repositoryRoot); var repository = new LocalPackageRepository(repositoryRoot); // Act var packages = repository.GetPackages().ToList(); // Assert Assert.Equal(3, packages.Count); AssertPackage("Test", "1.3.1.0", packages[0]); AssertPackage("Foo", "1.4", packages[1]); AssertPackage("Test", "1.3.4", packages[2]); }
public void GetPackagesOnlyRetrievesPackageFilesWhereLastModifiedIsOutOfDate() { // Arrange var mockFileSystem = new Mock<MockProjectSystem>() { CallBase = true }; var lastModified = new Dictionary<string, DateTimeOffset>(); mockFileSystem.Setup(m => m.GetLastModified("P1.nupkg")).Returns(() => lastModified["P1.nupkg"]); mockFileSystem.Setup(m => m.GetLastModified("P2.nupkg")).Returns(() => lastModified["P2.nupkg"]); mockFileSystem.Object.AddFile("P1.nupkg"); mockFileSystem.Object.AddFile("P2.nupkg"); var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem.Object), mockFileSystem.Object); var results = new List<string>(); Func<string, IPackage> openPackage = p => { results.Add(p); string id = Path.GetFileNameWithoutExtension(p); return PackageUtility.CreatePackage(id, "1.0"); }; // Populate cache lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 30); lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30); repository.GetPackages(openPackage).ToList(); // Verify that both packages have been created from the file system Assert.Equal(2, results.Count); results.Clear(); // Act lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 35); lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30); repository.GetPackages(openPackage).ToList(); // Assert Assert.Equal(results.Count, 1); Assert.Equal(results[0], "P1.nupkg"); }
public static int Main(string[] args) { // TODO: Take a switch saying whether to use TeamCity logger // TODO: Show extraneous packages, exclusions, etc. // TODO: Get this from the command line var ignoreAssistanceMode = IgnoreAssistanceMode.None; ignoreAssistanceMode = IgnoreAssistanceMode.ShowNew; if (args.Length < 1 || args.Length > 2) { Console.WriteLine(@"USAGE: NuGetSuperBVT.exe c:\path\to\packages [c:\path\to\packages-to-scan.json]"); return(ReturnBadArgs); } var logger = new PackageVerifierLogger(); IDictionary <string, PackageSet> packageSets = null; if (args.Length >= 2) { string packagesToScanJsonFilePath = args[1]; if (!File.Exists(packagesToScanJsonFilePath)) { logger.LogError("Couldn't find packages JSON file at {0}", packagesToScanJsonFilePath); return(ReturnBadArgs); } string packagesToScanJsonFileContent = File.ReadAllText(packagesToScanJsonFilePath); packageSets = JsonConvert.DeserializeObject <IDictionary <string, PackageSet> >(packagesToScanJsonFileContent, new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); logger.LogInfo("Read {0} package set(s) from {1}", packageSets.Count, packagesToScanJsonFilePath); } var totalTimeStopWatch = Stopwatch.StartNew(); var nupkgsPath = args[0]; // TODO: Look this up using reflection or something var allRules = new IPackageVerifierRule[] { new AssemblyHasDocumentFileRule(), new AssemblyHasVersionAttributesRule(), new AssemblyHasServicingAttributeRule(), new AssemblyStrongNameRule(), new AuthenticodeSigningRule(), new PowerShellScriptIsSignedRule(), new RequiredPackageMetadataRule(), new SatellitePackageRule(), new StrictSemanticVersionValidationRule(), }.ToDictionary(t => t.GetType().Name, t => t); var localPackageRepo = new LocalPackageRepository(nupkgsPath); var numPackagesInRepo = localPackageRepo.GetPackages().Count(); logger.LogInfo("Found {0} packages in {1}", numPackagesInRepo, nupkgsPath); var processedPackages = new HashSet <IPackage>(); var totalErrors = 0; var totalWarnings = 0; var ignoreAssistanceData = new Dictionary <string, IDictionary <string, IDictionary <string, string> > >(StringComparer.OrdinalIgnoreCase); foreach (var packageSet in packageSets) { logger.LogInfo("Processing package set '{0}' with {1} package(s)", packageSet.Key, packageSet.Value.Packages.Count); var packageSetRuleInfo = packageSet.Value.Rules; var packageSetRules = packageSetRuleInfo.Select(ruleId => allRules.Single(rule => string.Equals(rule.Key, ruleId, StringComparison.OrdinalIgnoreCase)).Value); var analyzer = new PackageAnalyzer(); foreach (var ruleInstance in packageSetRules) { analyzer.Rules.Add(ruleInstance); } IList <IssueIgnore> issuesToIgnore = GetIgnoresFromFile(packageSet.Value.Packages); var issueProcessor = new IssueProcessor(issuesToIgnore); foreach (var packageInfo in packageSet.Value.Packages) { var packageId = packageInfo.Key; var packageIgnoreInfo = packageInfo.Value; var packagesWithId = localPackageRepo.FindPackagesById(packageId); if (!packagesWithId.Any()) { logger.LogError("Couldn't find package '{0}' in the repo", packageId); totalErrors++; continue; } if (packagesWithId.Count() > 1) { logger.LogError("Found more than one package with id '{0}' in the repo", packageId); totalErrors++; continue; } var package = packagesWithId.Single(); var packageTimeStopWatch = Stopwatch.StartNew(); logger.LogInfo("Analyzing {0} ({1})", package.Id, package.Version); var issues = analyzer.AnalyzePackage(localPackageRepo, package, logger).ToList(); var packageErrorsAndWarnings = ProcessPackageIssues( ignoreAssistanceMode, logger, issueProcessor, ignoreAssistanceData, package, issues); totalErrors += packageErrorsAndWarnings.Item1; totalWarnings += packageErrorsAndWarnings.Item2; packageTimeStopWatch.Stop(); logger.LogInfo("Took {0}ms", packageTimeStopWatch.ElapsedMilliseconds); Console.WriteLine(); processedPackages.Add(package); } } var unprocessedPackages = localPackageRepo.GetPackages().Except(processedPackages); if (unprocessedPackages.Any()) { logger.LogWarning("Found {0} unprocessed packages. Every package in the repo should be listed in exactly one package set. Running all rules on unlisted packages.", unprocessedPackages.Count()); // For unprocessed packages we run all rules (because we have no idea what exactly to run) var analyzer = new PackageAnalyzer(); foreach (var ruleInstance in allRules.Values) { analyzer.Rules.Add(ruleInstance); } var issueProcessor = new IssueProcessor(issuesToIgnore: null); foreach (var unprocessedPackage in unprocessedPackages) { logger.LogWarning("\tUnprocessed package: {0} ({1})", unprocessedPackage.Id, unprocessedPackage.Version); var packageTimeStopWatch = Stopwatch.StartNew(); logger.LogInfo("Analyzing {0} ({1})", unprocessedPackage.Id, unprocessedPackage.Version); var issues = analyzer.AnalyzePackage(localPackageRepo, unprocessedPackage, logger).ToList(); var packageErrorsAndWarnings = ProcessPackageIssues( ignoreAssistanceMode, logger, issueProcessor, ignoreAssistanceData, unprocessedPackage, issues); totalErrors += packageErrorsAndWarnings.Item1; totalWarnings += packageErrorsAndWarnings.Item2; packageTimeStopWatch.Stop(); logger.LogInfo("Took {0}ms", packageTimeStopWatch.ElapsedMilliseconds); Console.WriteLine(); } } if (ignoreAssistanceMode != IgnoreAssistanceMode.None) { Console.WriteLine("Showing JSON for ignore content:"); Console.WriteLine(JsonConvert.SerializeObject(ignoreAssistanceData, Formatting.Indented)); Console.WriteLine(); } LogLevel errorLevel = LogLevel.Info; if (totalWarnings > 0) { errorLevel = LogLevel.Warning; } if (totalErrors > 0) { errorLevel = LogLevel.Error; } logger.Log( errorLevel, "SUMMARY: {0} error(s) and {1} warning(s) found", totalErrors, totalWarnings); totalTimeStopWatch.Stop(); logger.LogInfo("Total took {0}ms", totalTimeStopWatch.ElapsedMilliseconds); Console.ReadLine(); return((totalErrors + totalWarnings > 0) ? ReturnErrorsOrWarnings : ReturnOk); }
public void OpenPackagePrintsPathToPackageIfItCannotBeRead() { // Arrange var fileSystem = new MockFileSystem(); fileSystem.AddFile(@"Foo.nupkg"); var pathResolver = new DefaultPackagePathResolver(fileSystem); var repository = new LocalPackageRepository(pathResolver, fileSystem); // Act and Assert ExceptionAssert.Throws<InvalidDataException>(() => repository.GetPackages().ToList(), "Unable to read package from path 'Foo.nupkg'."); }
public void GetPackageReturnsPackagesFromNestedDirectories() { // Arrange string id = "Test"; string version = "1.3.1.0"; string packageName = @"SubDir\Test.1.3.1.nupkg"; var repositoryRoot = CreatePackage(id, version, packageName); CreatePackage(id, "1.3.4", "Test.nupkg", repositoryRoot); CreatePackage("Foo", "1.4", @"SubDir2\Test.1.4.nupkg", repositoryRoot); var repository = new LocalPackageRepository(repositoryRoot); // Act var packages = repository.GetPackages().ToList(); // Assert Assert.Equal(3, packages.Count); AssertPackage("Test", "1.3.1.0", packages[0]); AssertPackage("Foo", "1.4", packages[1]); AssertPackage("Test", "1.3.4", packages[2]); }