Ejemplo n.º 1
0
        private void InsertIntoTextBuffer(IVsTextBuffer document, LibraryInstallationState libraryInstallationState, Manifest manifest)
        {
            ITextBuffer textBuffer = GetTextBuffer(document);

            if (textBuffer != null)
            {
                MemberNode            libraries = GetLibraries(textBuffer);
                SortedNodeList <Node> children  = JsonHelpers.GetChildren(libraries);

                if (children.Count > 0)
                {
                    ArrayNode arrayNode = children.OfType <ArrayNode>().First();

                    string newLibrary      = GetLibraryTextToBeInserted(libraryInstallationState, manifest);
                    bool   containsLibrary = arrayNode.BlockChildren.Any();

                    int insertionIndex = libraries.End - 1;

                    string lineBreakText = GetLineBreakTextFromPreviousLine(textBuffer, insertionIndex);

                    string insertionText;

                    if (containsLibrary)
                    {
                        insertionText = "," + lineBreakText + newLibrary + lineBreakText;
                    }
                    else
                    {
                        insertionText = newLibrary + lineBreakText;
                    }

                    if (insertionIndex > 0)
                    {
                        FormatSelection(textBuffer, insertionIndex, insertionText);
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public ILibraryInstallationState ConvertToLibraryInstallationState(LibraryInstallationStateOnDisk stateOnDisk)
        {
            if (stateOnDisk == null)
            {
                return(null);
            }

            string provider    = string.IsNullOrEmpty(stateOnDisk.ProviderId) ? _defaultProvider : stateOnDisk.ProviderId;
            string destination = string.IsNullOrEmpty(stateOnDisk.DestinationPath) ? _defaultDestination : stateOnDisk.DestinationPath;

            var state = new LibraryInstallationState()
            {
                IsUsingDefaultDestination = string.IsNullOrEmpty(stateOnDisk.DestinationPath),
                IsUsingDefaultProvider    = string.IsNullOrEmpty(stateOnDisk.ProviderId),
                ProviderId      = provider,
                DestinationPath = destination,
                Files           = stateOnDisk.Files
            };

            (state.Name, state.Version) = LibraryIdToNameAndVersionConverter.Instance.GetLibraryNameAndVersion(stateOnDisk.LibraryId, provider);

            return(state);
        }
        public async Task InstallAsync_RelativeFolderFiles()
        {
            string folder = Path.Combine(Path.GetTempPath(), "LibraryManager_test\\");

            Directory.CreateDirectory(folder);
            File.WriteAllText(Path.Combine(folder, "file1.js"), "");
            File.WriteAllText(Path.Combine(folder, "file2.js"), "");
            File.WriteAllText(Path.Combine(folder, "file3.js"), "");

            var origin         = new Uri(folder, UriKind.Absolute);
            var current        = new Uri(_projectFolder, UriKind.Absolute);
            Uri relativeFolder = current.MakeRelativeUri(origin);

            IProvider provider = _dependencies.GetProvider("filesystem");

            var desiredState = new LibraryInstallationState
            {
                ProviderId      = "filesystem",
                LibraryId       = relativeFolder.OriginalString,
                DestinationPath = "lib",
                Files           = new[] { "file1.js", "file2.js" }
            };

            ILibraryOperationResult result = await provider.InstallAsync(desiredState, CancellationToken.None);

            Assert.IsTrue(result.Success, "Didn't install");

            string file1 = Path.Combine(_projectFolder, desiredState.DestinationPath, desiredState.Files[0]);
            string file2 = Path.Combine(_projectFolder, desiredState.DestinationPath, desiredState.Files[1]);

            Assert.IsTrue(File.Exists(file1), "File1 wasn't copied");
            Assert.IsTrue(File.Exists(file2), "File1 wasn't copied");

            Assert.IsFalse(result.Cancelled);
            Assert.AreSame(desiredState, result.InstallationState);
            Assert.AreEqual(0, result.Errors.Count);
        }
Ejemplo n.º 4
0
        private void InsertIntoTextBuffer(IVsTextBuffer document, LibraryInstallationState libraryInstallationState)
        {
            ITextBuffer textBuffer = GetTextBuffer(document);

            if (textBuffer != null)
            {
                JSONMember libraries = GetLibraries(textBuffer);

                if (libraries?.Children != null)
                {
                    string    insertionText;
                    JSONArray jsonArray = libraries.Children.OfType <JSONArray>().First();

                    string newLibrary      = GetLibraryToBeInserted(libraryInstallationState);
                    bool   containsLibrary = jsonArray.BlockItemChildren.Any();

                    int insertionIndex = libraries.AfterEnd - 1;

                    string lineBreakText = GetLineBreakTextFromPreviousLine(textBuffer, insertionIndex);

                    if (containsLibrary)
                    {
                        insertionText = "," + lineBreakText + newLibrary + lineBreakText;
                    }
                    else
                    {
                        insertionText = newLibrary + lineBreakText;
                    }

                    if (insertionIndex > 0)
                    {
                        FormatSelection(textBuffer, insertionIndex, insertionText);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private async Task InstallPackageAsync()
        {
            try
            {
                bool isLibraryInstallationStateValid = await IsLibraryInstallationStateValidAsync().ConfigureAwait(false);

                if (isLibraryInstallationStateValid)
                {
                    ILibrary selectedPackage = SelectedPackage;
                    InstallPackageCommand.CanExecute(null);
                    Manifest manifest = await Manifest.FromFileAsync(_configFileName, _deps, CancellationToken.None).ConfigureAwait(false);

                    string targetPath = _targetPath;

                    if (!string.IsNullOrEmpty(_configFileName))
                    {
                        Uri configContainerUri = new Uri(_configFileName, UriKind.Absolute);
                        Uri targetUri          = new Uri(targetPath, UriKind.Absolute);
                        targetPath = configContainerUri.MakeRelativeUri(targetUri).ToString();
                    }

                    if (String.IsNullOrEmpty(manifest.Version))
                    {
                        manifest.Version = Manifest.SupportedVersions.Max().ToString();
                    }

                    (string name, string version) = LibraryIdToNameAndVersionConverter.Instance.GetLibraryNameAndVersion(PackageId, SelectedProvider.Id);
                    LibraryInstallationState libraryInstallationState = new LibraryInstallationState
                    {
                        Name            = name,
                        Version         = version,
                        ProviderId      = selectedPackage.ProviderId,
                        DestinationPath = InstallationFolder.DestinationFolder,
                    };

                    _isInstalling = true;

                    // When "Include all files" option is checked, we don't want to write out the files to libman.json.
                    // We will only list the files when user chose to install specific files.
                    if (LibraryFilesToInstall == FileSelectionType.ChooseSpecificFilesToInstall)
                    {
                        libraryInstallationState.Files = SelectedFiles.ToList();
                    }

                    manifest.AddLibrary(libraryInstallationState);

                    await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    if (!File.Exists(_configFileName))
                    {
                        await manifest.SaveAsync(_configFileName, CancellationToken.None);

                        if (_project != null)
                        {
                            await _project.AddFileToProjectAsync(_configFileName);
                        }
                    }

                    RunningDocumentTable rdt = new RunningDocumentTable(Shell.ServiceProvider.GlobalProvider);
                    string configFilePath    = Path.GetFullPath(_configFileName);

                    IVsTextBuffer textBuffer = rdt.FindDocument(configFilePath) as IVsTextBuffer;

                    _dispatcher.Invoke(() =>
                    {
                        _closeDialog(true);
                    });

                    // The file isn't open. So we'll write to disk directly
                    if (textBuffer == null)
                    {
                        manifest.AddLibrary(libraryInstallationState);

                        await manifest.SaveAsync(_configFileName, CancellationToken.None).ConfigureAwait(false);

                        Telemetry.TrackUserTask("Invoke-RestoreFromAddClientLibrariesDialog");
                        await _libraryCommandService.RestoreAsync(_configFileName, CancellationToken.None).ConfigureAwait(false);
                    }
                    else
                    {
                        // libman.json file is open, so we will write to the textBuffer.
                        InsertIntoTextBuffer(textBuffer, libraryInstallationState, manifest);

                        // Save manifest file so we can restore library files.
                        rdt.SaveFileIfDirty(configFilePath);
                    }
                }
            }
            catch (Exception ex)
            {
                Telemetry.TrackException(nameof(InstallPackageAsync), ex);
            }
        }
Ejemplo n.º 6
0
        public async Task InstallAsync_FullEndToEnd()
        {
            ILibraryCatalog catalog = _provider.GetCatalog();

            // Search for libraries to display in search result
            IReadOnlyList <ILibraryGroup> groups = await catalog.SearchAsync("jquery", 4, CancellationToken.None);

            Assert.IsTrue(groups.Count > 0);

            // Show details for selected library
            ILibraryGroup group = groups.FirstOrDefault();

            Assert.AreEqual("jquery", group.DisplayName);

            // Get all libraries in group to display version list
            IEnumerable <string> libraryVersions = await group.GetLibraryVersions(CancellationToken.None);

            Assert.IsTrue(libraryVersions.Count() >= 0);

            // Get the library to install
            ILibrary library = await catalog.GetLibraryAsync("jquery", libraryVersions.First(), CancellationToken.None);

            Assert.AreEqual(group.DisplayName, library.Name);

            var desiredState = new LibraryInstallationState
            {
                Name            = "jquery",
                Version         = "3.3.1",
                ProviderId      = "jsdelivr",
                DestinationPath = "lib",
                Files           = new[] { "dist/jquery.js", "dist/jquery.min.js" }
            };

            // Install library
            ILibraryOperationResult result = await _provider.InstallAsync(desiredState, CancellationToken.None).ConfigureAwait(false);

            foreach (string file in desiredState.Files)
            {
                string absolute = Path.Combine(_projectFolder, desiredState.DestinationPath, file);
                Assert.IsTrue(File.Exists(absolute));
            }


            //GitHub library test
            Assert.IsTrue(result.Success);
            Assert.IsFalse(result.Cancelled);
            Assert.AreSame(desiredState, result.InstallationState);
            Assert.AreEqual(0, result.Errors.Count);

            var desiredStateGH = new LibraryInstallationState
            {
                Name            = "jquery/jquery",
                Version         = "3.3.1",
                ProviderId      = "jsdelivr",
                DestinationPath = "lib",
                Files           = new[] { "dist/jquery.js", "dist/jquery.min.js" }
            };

            // Install library
            ILibraryOperationResult resultGH = await _provider.InstallAsync(desiredStateGH, CancellationToken.None).ConfigureAwait(false);

            foreach (string file in desiredStateGH.Files)
            {
                string absolute = Path.Combine(_projectFolder, desiredStateGH.DestinationPath, file);
                Assert.IsTrue(File.Exists(absolute));
            }

            Assert.IsTrue(resultGH.Success);
            Assert.IsFalse(resultGH.Cancelled);
            Assert.AreSame(desiredStateGH, resultGH.InstallationState);
            Assert.AreEqual(0, resultGH.Errors.Count);
        }
Ejemplo n.º 7
0
        /// <inheritdoc />
        public virtual async Task <ILibraryOperationResult> UpdateStateAsync(ILibraryInstallationState desiredState, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(LibraryOperationResult.FromCancelled(desiredState));
            }

            string libraryId = LibraryNamingScheme.GetLibraryId(desiredState.Name, desiredState.Version);

            try
            {
                ILibraryCatalog catalog = GetCatalog();
                ILibrary        library = await catalog.GetLibraryAsync(desiredState.Name, desiredState.Version, cancellationToken).ConfigureAwait(false);

                if (library == null)
                {
                    return(new LibraryOperationResult(desiredState, PredefinedErrors.UnableToResolveSource(desiredState.Name, desiredState.ProviderId)));
                }

                if (desiredState.Files != null && desiredState.Files.Count > 0)
                {
                    // expand any potential file patterns
                    IEnumerable <string> updatedFiles = FileGlobbingUtility.ExpandFileGlobs(desiredState.Files, library.Files.Keys);
                    var processedState = new LibraryInstallationState
                    {
                        Name                      = desiredState.Name,
                        Version                   = desiredState.Version,
                        ProviderId                = desiredState.ProviderId,
                        DestinationPath           = desiredState.DestinationPath,
                        IsUsingDefaultDestination = desiredState.IsUsingDefaultDestination,
                        IsUsingDefaultProvider    = desiredState.IsUsingDefaultProvider,
                        Files                     = updatedFiles.ToList(),
                    };

                    return(CheckForInvalidFiles(processedState, libraryId, library));
                }

                desiredState = new LibraryInstallationState
                {
                    ProviderId                = Id,
                    Name                      = desiredState.Name,
                    Version                   = desiredState.Version,
                    DestinationPath           = desiredState.DestinationPath,
                    Files                     = library.Files.Keys.ToList(),
                    IsUsingDefaultDestination = desiredState.IsUsingDefaultDestination,
                    IsUsingDefaultProvider    = desiredState.IsUsingDefaultProvider
                };
            }
            catch (InvalidLibraryException)
            {
                return(new LibraryOperationResult(desiredState, PredefinedErrors.UnableToResolveSource(libraryId, desiredState.ProviderId)));
            }
            catch (UnauthorizedAccessException)
            {
                return(new LibraryOperationResult(desiredState, PredefinedErrors.PathOutsideWorkingDirectory()));
            }
            catch (Exception ex)
            {
                HostInteraction.Logger.Log(ex.ToString(), LogLevel.Error);
                return(new LibraryOperationResult(desiredState, PredefinedErrors.UnknownException()));
            }

            return(LibraryOperationResult.FromSuccess(desiredState));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Installs a library as specified in the <paramref name="desiredState" /> parameter.
        /// </summary>
        /// <param name="desiredState">The details about the library to install.</param>
        /// <param name="cancellationToken">A token that allows for the operation to be cancelled.</param>
        /// <returns>
        /// The <see cref="T:Microsoft.Web.LibraryInstaller.Contracts.ILibraryInstallationResult" /> from the installation process.
        /// </returns>
        /// <exception cref="InvalidLibraryException"></exception>
        public async Task <ILibraryInstallationResult> InstallAsync(ILibraryInstallationState desiredState, CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(LibraryInstallationResult.FromCancelled(desiredState));
            }

            if (!desiredState.IsValid(out IEnumerable <IError> errors))
            {
                return(new LibraryInstallationResult(desiredState, errors.ToArray()));
            }


            try
            {
                var      catalog = (CdnjsCatalog)GetCatalog();
                ILibrary library = await catalog.GetLibraryAsync(desiredState.LibraryId, cancellationToken).ConfigureAwait(false);

                if (library == null)
                {
                    throw new InvalidLibraryException(desiredState.LibraryId, Id);
                }

                await HydrateCacheAsync(library, cancellationToken).ConfigureAwait(false);

                var files = desiredState.Files?.ToList();
                // "Files" is optional on this provider, so when none are specified all should be used
                if (files == null || files.Count == 0)
                {
                    desiredState = new LibraryInstallationState
                    {
                        ProviderId      = Id,
                        LibraryId       = desiredState.LibraryId,
                        DestinationPath = desiredState.DestinationPath,
                        Files           = library.Files.Keys.ToList(),
                    };
                }

                foreach (string file in desiredState.Files)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(LibraryInstallationResult.FromCancelled(desiredState));
                    }

                    string path         = Path.Combine(desiredState.DestinationPath, file);
                    var    sourceStream = new Func <Stream>(() => GetStreamAsync(desiredState, file, cancellationToken).Result);
                    bool   writeOk      = await HostInteraction.WriteFileAsync(path, sourceStream, desiredState, cancellationToken).ConfigureAwait(false);

                    if (!writeOk)
                    {
                        return(new LibraryInstallationResult(desiredState, PredefinedErrors.CouldNotWriteFile(file)));
                    }
                }
            }
            catch (Exception ex) when(ex is InvalidLibraryException || ex.InnerException is InvalidLibraryException)
            {
                return(new LibraryInstallationResult(desiredState, PredefinedErrors.UnableToResolveSource(desiredState.LibraryId, desiredState.ProviderId)));
            }
            catch (UnauthorizedAccessException)
            {
                return(new LibraryInstallationResult(desiredState, PredefinedErrors.PathOutsideWorkingDirectory()));
            }
            catch (Exception ex)
            {
                HostInteraction.Logger.Log(ex.ToString(), LogLevel.Error);
                return(new LibraryInstallationResult(desiredState, PredefinedErrors.UnknownException()));
            }

            return(LibraryInstallationResult.FromSuccess(desiredState));
        }
Ejemplo n.º 9
0
        public async Task <ILibraryInstallationResult> InstallAsync(ILibraryInstallationState desiredState, CancellationToken cancellationToken)
        {
            try
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(LibraryInstallationResult.FromCancelled(desiredState));
                }

                var      catalog = (CdnjsCatalog)GetCatalog();
                ILibrary library = await catalog.GetLibraryAsync(desiredState.LibraryId, cancellationToken).ConfigureAwait(false);

                if (library == null)
                {
                    throw new InvalidLibraryException(desiredState.LibraryId, Id);
                }

                await HydrateCacheAsync(library, cancellationToken).ConfigureAwait(false);

                var files = desiredState.Files?.ToList();

                if (files == null || files.Count == 0)
                {
                    desiredState = new LibraryInstallationState
                    {
                        ProviderId      = Id,
                        LibraryId       = desiredState.LibraryId,
                        DestinationPath = desiredState.DestinationPath,
                        Files           = library.Files.Keys.ToList()
                    };
                }

                foreach (string file in desiredState.Files)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(LibraryInstallationResult.FromCancelled(desiredState));
                    }

                    string path    = Path.Combine(desiredState.DestinationPath, file);
                    var    func    = new Func <Stream>(() => GetStream(desiredState, file));
                    bool   writeOk = await HostInteraction.WriteFileAsync(path, func, desiredState, cancellationToken).ConfigureAwait(false);

                    if (!writeOk)
                    {
                        return(new LibraryInstallationResult(desiredState, PredefinedErrors.CouldNotWriteFile(file)));
                    }
                }
            }
            catch (Exception ex) when(ex is InvalidLibraryException || ex.InnerException is InvalidLibraryException)
            {
                return(new LibraryInstallationResult(desiredState, PredefinedErrors.UnableToResolveSource(desiredState.LibraryId, desiredState.ProviderId)));
            }
            catch (Exception ex)
            {
                HostInteraction.Logger.Log(ex.ToString(), LogLevel.Error);
                return(new LibraryInstallationResult(desiredState, PredefinedErrors.UnknownException()));
            }

            return(LibraryInstallationResult.FromSuccess(desiredState));
        }
        private async void InstallPackageAsync()
        {
            try
            {
                ILibrary selectedPackage = SelectedPackage;
                _isInstalling = true;
                InstallPackageCommand.CanExecute(null);
                Manifest manifest = await Manifest.FromFileAsync(_configFileName, _deps, CancellationToken.None).ConfigureAwait(false);

                string targetPath = _targetPath;

                if (!string.IsNullOrEmpty(_configFileName))
                {
                    Uri configContainerUri = new Uri(_configFileName, UriKind.Absolute);
                    Uri targetUri          = new Uri(targetPath, UriKind.Absolute);
                    targetPath = configContainerUri.MakeRelativeUri(targetUri).ToString();
                }

                if (String.IsNullOrEmpty(manifest.Version))
                {
                    manifest.Version = Manifest.SupportedVersions.Max().ToString();
                }

                LibraryInstallationState libraryInstallationState = new LibraryInstallationState
                {
                    LibraryId       = PackageId,
                    ProviderId      = selectedPackage.ProviderId,
                    DestinationPath = InstallationFolder.DestinationFolder,
                };

                // When "Include all files" option is checked, we don't want to write out the files to libman.json.
                // We will only list the files when user chose to install specific files.
                if (LibraryFilesToInstall == FileSelectionType.ChooseSpecificFilesToInstall)
                {
                    libraryInstallationState.Files = SelectedFiles.ToList();
                }

                manifest.AddLibrary(libraryInstallationState);

                await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                EnvDTE.Project project = VsHelpers.DTE.SelectedItems.Item(1)?.ProjectItem?.ContainingProject;
                project?.AddFileToProjectAsync(_configFileName);

                RunningDocumentTable rdt = new RunningDocumentTable(Shell.ServiceProvider.GlobalProvider);
                string configFilePath    = Path.GetFullPath(_configFileName);

                IVsTextBuffer textBuffer = rdt.FindDocument(configFilePath) as IVsTextBuffer;

                _dispatcher.Invoke(() =>
                {
                    _closeDialog(true);
                });

                // The file isn't open. So we'll write to disk directly
                if (textBuffer == null)
                {
                    manifest.AddLibrary(libraryInstallationState);

                    await manifest.SaveAsync(_configFileName, CancellationToken.None).ConfigureAwait(false);

                    await _libraryCommandService.RestoreAsync(_configFileName, CancellationToken.None).ConfigureAwait(false);
                }
                else
                {
                    // libman.json file is open, so we will write to the textBuffer.
                    InsertIntoTextBuffer(textBuffer, libraryInstallationState);

                    // Save manifest file so we can restore library files.
                    rdt.SaveFileIfDirty(configFilePath);
                }
            }
            catch { }
        }