Beispiel #1
0
        private async Task PushPackage(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       bool skipDuplicate,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            var nupkgsToPush = LocalFolderUtility.ResolvePackageFromPath(packagePath, isSnupkg: false);

            if (!(nupkgsToPush != null && nupkgsToPush.Any()))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          Strings.UnableToFindFile,
                                                          packagePath));
            }

            var sourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            await PushAll(source, apiKey, noServiceEndpoint, skipDuplicate, requestTimeout, log, packagesToPush : nupkgsToPush, token);
        }
Beispiel #2
0
        public async Task RestoreCommand_FileUriV3Folder()
        {
            // Arrange
            var sources = new List <PackageSource>();

            // Both TxMs reference packageA, but they are different types.
            // Verify that the reference does not show up under libraries.
            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""packageA"": ""4.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(UriUtility.CreateSourceUri(packageSource.FullName).AbsoluteUri));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    packageSource.FullName,
                    new PackageIdentity("packageA", NuGetVersion.Parse("4.0.0")));

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(1, lockFile.Libraries.Count);
            }
        }
        private async Task PushPackage(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            var sourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            var packagesToPush = LocalFolderUtility.ResolvePackageFromPath(packagePath);

            LocalFolderUtility.EnsurePackageFileExists(packagePath, packagesToPush);

            foreach (var packageToPush in packagesToPush)
            {
                await PushPackageCore(source, apiKey, packageToPush, noServiceEndpoint, requestTimeout, log, token);
            }
        }
        private async Task PushSymbols(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            // Get the symbol package for this package
            var symbolPackagePath = GetSymbolsPath(packagePath);

            // Push the symbols package if it exists
            if (File.Exists(symbolPackagePath))
            {
                var sourceUri = UriUtility.CreateSourceUri(source);

                // See if the api key exists
                if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
                {
                    log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                 Strings.Warning_SymbolServerNotConfigured,
                                                 Path.GetFileName(symbolPackagePath),
                                                 Strings.DefaultSymbolServer));
                }

                await PushPackage(symbolPackagePath, source, apiKey, noServiceEndpoint, requestTimeout, log, token);
            }
        }
        private async Task PushPackageCore(string source,
                                           string apiKey,
                                           string packageToPush,
                                           bool noServiceEndpoint,
                                           TimeSpan requestTimeout,
                                           ILogger log,
                                           CancellationToken token)
        {
            var sourceUri  = UriUtility.CreateSourceUri(source);
            var sourceName = GetSourceDisplayName(source);

            log.LogInformation(string.Format(CultureInfo.CurrentCulture,
                                             Strings.PushCommandPushingPackage,
                                             Path.GetFileName(packageToPush),
                                             sourceName));

            if (sourceUri.IsFile)
            {
                await PushPackageToFileSystem(sourceUri, packageToPush, log, token);
            }
            else
            {
                var length = new FileInfo(packageToPush).Length;
                await PushPackageToServer(source, apiKey, packageToPush, length, noServiceEndpoint, requestTimeout, log, token);
            }

            log.LogInformation(Strings.PushCommandPackagePushed);
        }
        // Deletes a package from a FileSystem.
        private void DeletePackageFromFileSystem(string source, string packageId, string packageVersion, ILogger logger)
        {
            var sourceuri = UriUtility.CreateSourceUri(source);
            var root      = sourceuri.LocalPath;
            var resolver  = new PackagePathResolver(sourceuri.AbsolutePath, useSideBySidePaths: true);

            resolver.GetPackageFileName(new Packaging.Core.PackageIdentity(packageId, new NuGetVersion(packageVersion)));
            var packageIdentity = new PackageIdentity(packageId, new NuGetVersion(packageVersion));

            if (IsV2LocalRepository(root))
            {
                var packageFileName = resolver.GetPackageFileName(packageIdentity);
                var nupkgFilePath   = Path.Combine(root, packageFileName);
                if (!File.Exists(nupkgFilePath))
                {
                    throw new ArgumentException(Strings.DeletePackage_NotFound);
                }
                ForceDeleteFile(nupkgFilePath);
            }
            else
            {
                var packageDirectory = OfflineFeedUtility.GetPackageDirectory(packageIdentity, root);
                if (!Directory.Exists(packageDirectory))
                {
                    throw new ArgumentException(Strings.DeletePackage_NotFound);
                }
                ForceDeleteDirectory(packageDirectory);
            }
        }
Beispiel #7
0
        private async Task PushSymbols(string packagePath,
                                       string source,
                                       string apiKey,
                                       bool noServiceEndpoint,
                                       SymbolPackageUpdateResourceV3 symbolPackageUpdateResource,
                                       TimeSpan requestTimeout,
                                       ILogger log,
                                       CancellationToken token)
        {
            var isSymbolEndpointSnupkgCapable = symbolPackageUpdateResource != null;
            // Get the symbol package for this package
            var symbolPackagePath = GetSymbolsPath(packagePath, isSymbolEndpointSnupkgCapable);

            // Push the symbols package if it exists
            if (File.Exists(symbolPackagePath) || symbolPackagePath.IndexOf('*') != -1)
            {
                var sourceUri = UriUtility.CreateSourceUri(source);

                // See if the api key exists
                if (string.IsNullOrEmpty(apiKey) && !sourceUri.IsFile)
                {
                    log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                 Strings.Warning_SymbolServerNotConfigured,
                                                 Path.GetFileName(symbolPackagePath),
                                                 Strings.DefaultSymbolServer));
                }

                var skipDuplicate = false;
                await PushPackage(symbolPackagePath, source, apiKey, noServiceEndpoint, skipDuplicate, requestTimeout, log, token, isSnupkgPush : isSymbolEndpointSnupkgCapable);
            }
        }
        // Ensure a trailing slash at the end
        private static Uri EnsureTrailingSlash(string value)
        {
            if (!value.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                value += "/";
            }

            return(UriUtility.CreateSourceUri(value));
        }
        private IPackageRepository GetRepository()
        {
            var repository = V2Client as DataServicePackageRepository;

            if (repository != null)
            {
                var sourceUri = UriUtility.CreateSourceUri(repository.Source);
                repository = new DataServicePackageRepository(sourceUri);
            }

            // If the repository is not a DataServicePackageRepository just return the current one.
            return(repository ?? V2Client);
        }
Beispiel #10
0
        public async Task FindLocalPackagesResource_FindPackagesByIdBasicAsync()
        {
            using (var rootPackagesConfig = TestDirectory.Create())
                using (var rootUnzip = TestDirectory.Create())
                    using (var rootV3 = TestDirectory.Create())
                        using (var rootV2 = TestDirectory.Create())
                        {
                            // Arrange
                            var testLogger = new TestLogger();
                            await CreateFeedsAsync(rootV2, rootV3, rootUnzip, rootPackagesConfig, PackageSet1);

                            var expected = new HashSet <PackageIdentity>(new[]
                            {
                                PackageA1,
                                PackageA2,
                                PackageA3,
                                PackageA4,
                                PackageA5,
                            });

                            var resources = new FindLocalPackagesResource[]
                            {
                                new FindLocalPackagesResourcePackagesConfig(rootPackagesConfig),
                                new FindLocalPackagesResourceUnzipped(rootUnzip),
                                new FindLocalPackagesResourceV2(rootV2),
                                new FindLocalPackagesResourceV3(rootV3),
                                new FindLocalPackagesResourcePackagesConfig(UriUtility.CreateSourceUri(rootPackagesConfig).AbsoluteUri),
                                new FindLocalPackagesResourceUnzipped(UriUtility.CreateSourceUri(rootUnzip).AbsoluteUri),
                                new FindLocalPackagesResourceV2(UriUtility.CreateSourceUri(rootV2).AbsoluteUri),
                                new FindLocalPackagesResourceV3(UriUtility.CreateSourceUri(rootV3).AbsoluteUri)
                            };

                            foreach (var resource in resources)
                            {
                                // Act
                                var result = resource.FindPackagesById("a", testLogger, CancellationToken.None).ToList();

                                // Assert
                                Assert.True(expected.SetEquals(result.Select(p => p.Identity)));
                                Assert.True(expected.SetEquals(result.Select(p =>
                                {
                                    using (var reader = p.GetReader())
                                    {
                                        return(reader.GetIdentity());
                                    }
                                })));
                                Assert.True(expected.SetEquals(result.Select(p => p.Nuspec.GetIdentity())));
                                Assert.True(result.All(p => p.IsNupkg));
                            }
                        }
        }
        public void FeedTypeUtility_NupkgAtRootIsV2_FileUri()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                CreateFile(Path.Combine(root, "a.1.0.0.nupkg"));

                // Act
                var type = FeedTypeUtility.GetFeedType(new PackageSource(UriUtility.CreateSourceUri(root).AbsoluteUri));

                // Assert
                Assert.Equal(FeedType.FileSystemV2, type);
            }
        }
        public void GetFeedType_WithFileSystemV2LayoutAndFileUri_ReturnsFileSystemV2()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                CreateFile(Path.Combine(root, "a.1.0.0.nupkg"));

                // Act
                var type = FeedTypeUtility.GetFeedType(new PackageSource(UriUtility.CreateSourceUri(root).AbsoluteUri));

                // Assert
                Assert.Equal(FeedType.FileSystemV2, type);
            }
        }
        public void FeedTypeUtility_NupkgInVersionFolderIsV3_FileUri()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                CreateFile(Path.Combine(root, "a", "1.0.0", "a.1.0.0.nupkg.sha512"));
                CreateFile(Path.Combine(root, "a", "1.0.0", "a.nuspec"));
                CreateFile(Path.Combine(root, "a", "1.0.0", "a.1.0.0.nupkg"));

                // Act
                var type = FeedTypeUtility.GetFeedType(new PackageSource(UriUtility.CreateSourceUri(root).AbsoluteUri));

                // Assert
                Assert.Equal(FeedType.FileSystemV3, type);
            }
        }
        /// <summary>
        /// Uri -> Package
        /// </summary>
        private static Dictionary <Uri, LocalPackageInfo> GetPathIndex(Lazy <IReadOnlyList <LocalPackageInfo> > packages)
        {
            var index = new Dictionary <Uri, LocalPackageInfo>();

            foreach (var package in packages.Value)
            {
                var path = UriUtility.CreateSourceUri(package.Path, UriKind.Absolute);

                if (!index.ContainsKey(path))
                {
                    index.Add(path, package);
                }
            }

            return(index);
        }
Beispiel #15
0
        /// <summary>
        /// Convert a package into a PackageDependencyInfo
        /// </summary>
        private SourcePackageDependencyInfo CreateDependencyInfo(LocalPackageInfo package, NuGetFramework projectFramework)
        {
            // Take only the dependency group valid for the project TFM
            var group        = NuGetFrameworkUtility.GetNearest <PackageDependencyGroup>(package.Nuspec.GetDependencyGroups(), projectFramework);
            var dependencies = group?.Packages ?? Enumerable.Empty <PackageDependency>();

            var result = new SourcePackageDependencyInfo(
                package.Identity,
                dependencies,
                listed: true,
                source: _source,
                downloadUri: UriUtility.CreateSourceUri(package.Path, UriKind.Absolute),
                packageHash: null);

            return(result);
        }
        public AutoCompleteResourceV2Feed(HttpSourceResource httpSourceResource, string baseAddress, Configuration.PackageSource packageSource)
        {
            if (httpSourceResource == null)
            {
                throw new ArgumentNullException(nameof(httpSourceResource));
            }

            if (packageSource == null)
            {
                throw new ArgumentNullException(nameof(packageSource));
            }

            _httpSource = httpSourceResource.HttpSource;

            _baseUri = UriUtility.CreateSourceUri($"{baseAddress}/");
        }
Beispiel #17
0
        private async Task PushSymbolsPath(string packagePath,
                                           string symbolSource,
                                           string apiKey,
                                           bool noServiceEndpoint,
                                           bool skipDuplicate,
                                           SymbolPackageUpdateResourceV3 symbolPackageUpdateResource,
                                           TimeSpan requestTimeout,
                                           ILogger log,
                                           bool explicitSymbolsPush,
                                           CancellationToken token)
        {
            bool isSymbolEndpointSnupkgCapable = symbolPackageUpdateResource != null;
            // Get the symbol package for this package
            string symbolPackagePath = GetSymbolsPath(packagePath, isSymbolEndpointSnupkgCapable);

            IEnumerable <string> symbolsToPush = LocalFolderUtility.ResolvePackageFromPath(symbolPackagePath, isSnupkg: isSymbolEndpointSnupkgCapable);
            bool symbolsPathResolved           = symbolsToPush != null && symbolsToPush.Any();

            //No files were resolved.
            if (!symbolsPathResolved)
            {
                if (explicitSymbolsPush)
                {
                    throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                              Strings.UnableToFindFile,
                                                              packagePath));
                }
            }
            else
            {
                Uri symbolSourceUri = UriUtility.CreateSourceUri(symbolSource);

                // See if the api key exists
                if (string.IsNullOrEmpty(apiKey) && !symbolSourceUri.IsFile)
                {
                    log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                 Strings.Warning_SymbolServerNotConfigured,
                                                 Path.GetFileName(symbolPackagePath),
                                                 Strings.DefaultSymbolServer));
                }

                foreach (string packageToPush in symbolsToPush)
                {
                    await PushPackageCore(symbolSource, apiKey, packageToPush, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);
                }
            }
        }
Beispiel #18
0
        public void SourceTelemetry_LocalFeedsVerifyCount()
        {
            var sources = new List <PackageSource>()
            {
                new PackageSource("packages"),
                new PackageSource(UriUtility.CreateSourceUri(Path.Combine(Path.GetTempPath(), "packages"), UriKind.Absolute).AbsoluteUri),
                new PackageSource(@"\\share\packages"),
            };

            var summary        = SourceTelemetry.GetSourceSummaryEvent(Parent, sources);
            var summaryStrings = GetValuesAsStrings(summary);
            var summaryInts    = GetValuesAsInts(summary);

            summaryStrings["NuGetOrg"].Should().Be("NotPresent");
            summaryInts["NumLocalFeeds"].Should().Be(3);
            summaryInts["NumHTTPv2Feeds"].Should().Be(0);
            summaryInts["NumHTTPv3Feeds"].Should().Be(0);
        }
        public async Task FindLocalPackagesResource_GetPackageBasic()
        {
            using (var rootPackagesConfig = TestDirectory.Create())
                using (var rootUnzip = TestDirectory.Create())
                    using (var rootV3 = TestDirectory.Create())
                        using (var rootV2 = TestDirectory.Create())
                        {
                            // Arrange
                            var testLogger = new TestLogger();
                            await CreateFeeds(rootV2, rootV3, rootUnzip, rootPackagesConfig, PackageSet1);

                            var expected = new HashSet <PackageIdentity>(new[]
                            {
                                PackageA1,
                                PackageA2,
                                PackageA3,
                                PackageA4,
                                PackageA5,
                            });

                            var resources = new FindLocalPackagesResource[]
                            {
                                new FindLocalPackagesResourcePackagesConfig(rootPackagesConfig),
                                new FindLocalPackagesResourceUnzipped(rootUnzip),
                                new FindLocalPackagesResourceV2(rootV2),
                                new FindLocalPackagesResourceV3(rootV3),
                                new FindLocalPackagesResourcePackagesConfig(UriUtility.CreateSourceUri(rootPackagesConfig).AbsoluteUri),
                                new FindLocalPackagesResourceUnzipped(UriUtility.CreateSourceUri(rootUnzip).AbsoluteUri),
                                new FindLocalPackagesResourceV2(UriUtility.CreateSourceUri(rootV2).AbsoluteUri),
                                new FindLocalPackagesResourceV3(UriUtility.CreateSourceUri(rootV3).AbsoluteUri)
                            };

                            foreach (var resource in resources)
                            {
                                // Act
                                var result  = resource.GetPackage(PackageA3, testLogger, CancellationToken.None);
                                var result2 = resource.GetPackage(UriUtility.CreateSourceUri(result.Path), testLogger, CancellationToken.None);

                                // Assert
                                Assert.Equal(PackageA3, result.Identity);
                                Assert.Equal(PackageA3, result2.Identity);
                            }
                        }
        }
        public void LocalFeedsVerifyCount()
        {
            var sources = new List <PackageSource>()
            {
                new PackageSource("packages"),
                new PackageSource(UriUtility.CreateSourceUri(Path.Combine(Path.GetTempPath(), "packages"), UriKind.Absolute).AbsoluteUri),
                new PackageSource(@"\\share\packages"),
            };

            var summary        = SourceTelemetry.GetRestoreSourceSummaryEvent(Parent, sources, ProtocolDiagnosticTotals);
            var summaryStrings = GetValuesAsStrings(summary);
            var summaryInts    = GetValuesAsInts(summary);
            var summaryBools   = GetValuesAsBools(summary);

            summaryInts[NumLocalFeeds].Should().Be(3);
            summaryInts[NumHTTPv2Feeds].Should().Be(0);
            summaryInts[NumHTTPv3Feeds].Should().Be(0);
            summaryStrings[ParentId].Should().Be(Parent.ToString());
            summaryStrings[NuGetOrg].Should().Be(NotPresent);
            summaryBools[VsOfflinePackages].Should().Be(false);
            summaryBools[DotnetCuratedFeed].Should().Be(false);
        }
        public void FindLocalPackagesResource_EmptyFolders()
        {
            using (var emptyDir = TestDirectory.Create())
            {
                // Arrange
                var testLogger   = new TestLogger();
                var doesNotExist = Path.Combine(emptyDir, "doesNotExist");

                var resources = new FindLocalPackagesResource[]
                {
                    new FindLocalPackagesResourcePackagesConfig(doesNotExist),
                    new FindLocalPackagesResourcePackagesConfig(emptyDir),
                    new FindLocalPackagesResourceUnzipped(doesNotExist),
                    new FindLocalPackagesResourceV2(doesNotExist),
                    new FindLocalPackagesResourceV3(doesNotExist),
                    new FindLocalPackagesResourceUnzipped(emptyDir),
                    new FindLocalPackagesResourceV2(emptyDir),
                    new FindLocalPackagesResourceV3(emptyDir),
                    new FindLocalPackagesResourcePackagesConfig(UriUtility.CreateSourceUri(doesNotExist).AbsoluteUri),
                    new FindLocalPackagesResourceUnzipped(UriUtility.CreateSourceUri(doesNotExist).AbsoluteUri),
                    new FindLocalPackagesResourceV2(UriUtility.CreateSourceUri(doesNotExist).AbsoluteUri),
                    new FindLocalPackagesResourceV3(UriUtility.CreateSourceUri(doesNotExist).AbsoluteUri),
                };

                foreach (var resource in resources)
                {
                    // Act
                    var getPackages  = resource.GetPackages(testLogger, CancellationToken.None).ToList();
                    var findPackages = resource.FindPackagesById("a", testLogger, CancellationToken.None).ToList();
                    var package      = resource.GetPackage(PackageA1, testLogger, CancellationToken.None);

                    // Assert
                    Assert.Equal(0, getPackages.Count);
                    Assert.Equal(0, findPackages.Count);
                    Assert.Null(package);
                }
            }
        }
Beispiel #22
0
        public async Task FindLocalPackagesResource_GetPackagesBasic()
        {
            using (var rootPackagesConfig = TestFileSystemUtility.CreateRandomTestFolder())
                using (var rootUnzip = TestFileSystemUtility.CreateRandomTestFolder())
                    using (var rootV3 = TestFileSystemUtility.CreateRandomTestFolder())
                        using (var rootV2 = TestFileSystemUtility.CreateRandomTestFolder())
                        {
                            // Arrange
                            var testLogger = new TestLogger();
                            await CreateFeeds(rootV2, rootV3, rootUnzip, rootPackagesConfig, PackageSet1);

                            var expected = new HashSet <PackageIdentity>(PackageSet1);

                            var resources = new FindLocalPackagesResource[]
                            {
                                new FindLocalPackagesResourcePackagesConfig(rootPackagesConfig),
                                new FindLocalPackagesResourceUnzipped(rootUnzip),
                                new FindLocalPackagesResourceV2(rootV2),
                                new FindLocalPackagesResourceV3(rootV3),
                                new FindLocalPackagesResourcePackagesConfig(UriUtility.CreateSourceUri(rootPackagesConfig).AbsoluteUri),
                                new FindLocalPackagesResourceUnzipped(UriUtility.CreateSourceUri(rootUnzip).AbsoluteUri),
                                new FindLocalPackagesResourceV2(UriUtility.CreateSourceUri(rootV2).AbsoluteUri),
                                new FindLocalPackagesResourceV3(UriUtility.CreateSourceUri(rootV3).AbsoluteUri)
                            };

                            foreach (var resource in resources)
                            {
                                // Act
                                var result = resource.GetPackages(testLogger, CancellationToken.None).ToList();

                                // Assert
                                Assert.True(expected.SetEquals(result.Select(p => p.Identity)));
                                Assert.True(expected.SetEquals(result.Select(p => p.GetReader().GetIdentity())));
                                Assert.True(expected.SetEquals(result.Select(p => p.Nuspec.GetIdentity())));
                                Assert.True(result.All(p => p.IsNupkg));
                            }
                        }
        }
        private async Task <bool> PushPackageCore(string source,
                                                  string apiKey,
                                                  string packageToPush,
                                                  bool noServiceEndpoint,
                                                  bool skipDuplicate,
                                                  TimeSpan requestTimeout,
                                                  bool warnForHttpSources,
                                                  ILogger log,
                                                  CancellationToken token)
        {
            var sourceUri  = UriUtility.CreateSourceUri(source);
            var sourceName = GetSourceDisplayName(source);

            log.LogInformation(string.Format(CultureInfo.CurrentCulture,
                                             Strings.PushCommandPushingPackage,
                                             Path.GetFileName(packageToPush),
                                             sourceName));

            bool wasPackagePushed = true;

            if (sourceUri.IsFile)
            {
                await PushPackageToFileSystem(sourceUri, packageToPush, skipDuplicate, log, token);
            }
            else
            {
                wasPackagePushed = await PushPackageToServer(source, apiKey, packageToPush, noServiceEndpoint, skipDuplicate,
                                                             requestTimeout, warnForHttpSources, log, token);
            }

            if (wasPackagePushed)
            {
                log.LogInformation(Strings.PushCommandPackagePushed);
            }

            return(wasPackagePushed);
        }
Beispiel #24
0
        /// <summary>
        /// Push nupkgs, and if successful, push any corresponding symbols.
        /// </summary>
        /// <exception cref="ArgumentException">Thrown when any resolved file path does not exist.</exception>
        private async Task PushPackagePath(string packagePath,
                                           string source,
                                           string symbolSource, // empty to not push symbols
                                           string apiKey,
                                           Func <string, string> getSymbolApiKey,
                                           bool noServiceEndpoint,
                                           bool skipDuplicate,
                                           SymbolPackageUpdateResourceV3 symbolPackageUpdateResource,
                                           TimeSpan requestTimeout,
                                           ILogger log,
                                           CancellationToken token)
        {
            IEnumerable <string> nupkgsToPush           = LocalFolderUtility.ResolvePackageFromPath(packagePath, isSnupkg: false);
            bool alreadyWarnedSymbolServerNotConfigured = false;

            if (!(nupkgsToPush != null && nupkgsToPush.Any()))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          Strings.UnableToFindFile,
                                                          packagePath));
            }

            Uri packageSourceUri = UriUtility.CreateSourceUri(source);

            if (string.IsNullOrEmpty(apiKey) && !packageSourceUri.IsFile)
            {
                log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                             Strings.NoApiKeyFound,
                                             GetSourceDisplayName(source)));
            }

            foreach (string nupkgToPush in nupkgsToPush)
            {
                bool packageWasPushed = await PushPackageCore(source, apiKey, nupkgToPush, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);

                // Push corresponding symbols, if successful.
                if (packageWasPushed && !string.IsNullOrEmpty(symbolSource))
                {
                    bool   isSymbolEndpointSnupkgCapable = symbolPackageUpdateResource != null;
                    string symbolPackagePath             = GetSymbolsPath(nupkgToPush, isSnupkg: isSymbolEndpointSnupkgCapable);

                    // There may not be a snupkg with the same filename. Ignore it since this isn't an explicit snupkg push.
                    if (!File.Exists(symbolPackagePath))
                    {
                        continue;
                    }

                    if (!alreadyWarnedSymbolServerNotConfigured)
                    {
                        Uri symbolSourceUri = UriUtility.CreateSourceUri(symbolSource);

                        // See if the api key exists
                        if (string.IsNullOrEmpty(apiKey) && !symbolSourceUri.IsFile)
                        {
                            log.LogWarning(string.Format(CultureInfo.CurrentCulture,
                                                         Strings.Warning_SymbolServerNotConfigured,
                                                         Path.GetFileName(symbolPackagePath),
                                                         Strings.DefaultSymbolServer));

                            alreadyWarnedSymbolServerNotConfigured = true;
                        }
                    }

                    string symbolApiKey = getSymbolApiKey(symbolSource);
                    await PushPackageCore(symbolSource, symbolApiKey, symbolPackagePath, noServiceEndpoint, skipDuplicate, requestTimeout, log, token);
                }
            }
        }
        private DownloadResourceResult DownloadFromIdentity(
            PackageIdentity identity,
            IPackageRepository repository,
            NuGet.Common.ILogger logger,
            CancellationToken token)
        {
            var version         = SemanticVersion.Parse(identity.Version.ToString());
            var dataServiceRepo = repository as DataServicePackageRepository;

            if (dataServiceRepo != null)
            {
                // Clone the repo to allow for concurrent calls
                var sourceUri = UriUtility.CreateSourceUri(dataServiceRepo.Source);
                dataServiceRepo = new DataServicePackageRepository(sourceUri);

                var package            = dataServiceRepo.FindPackage(identity.Id, version);
                var dataServicePackage = package as DataServicePackage;

                if (dataServicePackage != null)
                {
                    token.ThrowIfCancellationRequested();

                    // For online sources get the url and retrieve it with cancel support
                    var url = dataServicePackage.DownloadUrl;

                    var downloadedPackage = DownloadToMachineCache(
                        MachineCache.Default,
                        identity,
                        dataServiceRepo,
                        url,
                        logger,
                        token);

                    if (downloadedPackage != null)
                    {
                        return(new DownloadResourceResult(downloadedPackage.GetStream()));
                    }
                }
            }
            else
            {
                var package = repository.FindPackage(identity.Id, version);

                if (package != null)
                {
                    // Use a folder reader for unzipped repos
                    if (repository is UnzippedPackageRepository)
                    {
                        var packagePath   = Path.Combine(repository.Source, identity.Id + "." + version);
                        var directoryInfo = new DirectoryInfo(packagePath);
                        if (directoryInfo.Exists)
                        {
                            return(new DownloadResourceResult(
                                       package.GetStream(),
                                       new PackageFolderReader(directoryInfo)));
                        }
                    }

                    return(new DownloadResourceResult(package.GetStream()));
                }
            }

            return(new DownloadResourceResult(DownloadResourceResultStatus.NotFound));
        }
Beispiel #26
0
        public XDocument Format(INode featureNode, GeneralTree <INode> features, DirectoryInfoBase rootFolder)
        {
            XNamespace xmlns = HtmlNamespace.Xhtml;

            // If path2 is 'rooted', then Path.Combine returns path2. See http://stackoverflow.com/q/53102/206297.
            // The root node has a RelativePathFromRoot of '/'.  On Unix, this counts as a rooted path,
            // and we end up trying to write index.html to the root of the filesystem.  So trim the leading /.
            var unrootedRelativePathFromRoot = featureNode.RelativePathFromRoot.TrimStart(Path.DirectorySeparatorChar);

            string featureNodeOutputPath = this.fileSystem.Path.Combine(
                this.configuration.OutputFolder.FullName,
                unrootedRelativePathFromRoot);

            // If it was the root node, Path.Combine will now have lost the directory separator, which
            // marks it as a directory.  We need this is order for MakeRelativeUri to work correctly.
            if (string.IsNullOrWhiteSpace(unrootedRelativePathFromRoot))
            {
                featureNodeOutputPath += Path.DirectorySeparatorChar;
            }

            var featureNodeOutputUri = UriUtility.CreateSourceUri(featureNodeOutputPath);

            var container = new XElement(xmlns + "div", new XAttribute("id", "container"));

            container.Add(this.htmlHeaderFormatter.Format());
            container.Add(this.htmlTableOfContentsFormatter.Format(featureNode.OriginalLocationUrl, features, rootFolder));
            container.Add(this.htmlContentFormatter.Format(featureNode, features));
            container.Add(this.htmlFooterFormatter.Format());

            var body = new XElement(xmlns + "body");

            body.Add(container);

            var head = new XElement(xmlns + "head");

            head.Add(new XElement(xmlns + "title", featureNode.Name));

            head.Add(
                new XElement(
                    xmlns + "link",
                    new XAttribute("rel", "stylesheet"),
                    new XAttribute(
                        "href",
                        featureNodeOutputUri.MakeRelativeUri(this.htmlResources.MasterStylesheet)),
                    new XAttribute("type", "text/css")));

            head.Add(
                new XElement(
                    xmlns + "link",
                    new XAttribute("rel", "stylesheet"),
                    new XAttribute(
                        "href",
                        featureNodeOutputUri.MakeRelativeUri(this.htmlResources.PrintStylesheet)),
                    new XAttribute("type", "text/css"),
                    new XAttribute("media", "print")));

            head.Add(
                new XElement(
                    xmlns + "script",
                    new XAttribute("src", featureNodeOutputUri.MakeRelativeUri(this.htmlResources.JQueryScript)),
                    new XAttribute("type", "text/javascript"),
                    new XText(string.Empty)));

            head.Add(
                new XElement(
                    xmlns + "script",
                    new XAttribute(
                        "src",
                        featureNodeOutputUri.MakeRelativeUri(this.htmlResources.AdditionalScripts)),
                    new XAttribute("type", "text/javascript"),
                    new XText(string.Empty)));

            head.Add(
                new XElement(
                    xmlns + "script",
                    new XAttribute("type", "text/javascript"),
                    DocumentReady));

            head.Add(new XComment(" We are using Font Awesome - http://fortawesome.github.com/Font-Awesome - licensed under CC BY 3.0 "));

            var html = new XElement(
                xmlns + "html",
                new XAttribute(XNamespace.Xml + "lang", "en"),
                head,
                body);

            var document = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),
                new XDocumentType(
                    "html",
                    "-//W3C//DTD XHTML 1.0 Strict//EN",
                    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd",
                    string.Empty),
                html);

            return(document);
        }
        private bool IsSourceNuGetSymbolServer(string source)
        {
            var sourceUri = UriUtility.CreateSourceUri(source);

            return(sourceUri.Host.Equals(NuGetConstants.NuGetSymbolHostName, StringComparison.OrdinalIgnoreCase));
        }