Exemplo n.º 1
0
 public void LoadHostVersionInfo()
 {
     try
     {
         var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "gitlab4vs.dat");
         if (System.IO.File.Exists(filename))
         {
             HostVersionInfo = JsonConvert.DeserializeObject <Dictionary <string, ApiVersion> >(System.IO.File.ReadAllText(filename));
         }
     }
     catch (Exception ex)
     {
         HostVersionInfo = new Dictionary <string, ApiVersion>();
         OutputWindowHelper.WarningWriteLine("Can't load host version infos");
     }
     if (HostVersionInfo == null)
     {
         HostVersionInfo = new Dictionary <string, ApiVersion>();
     }
     if (HostVersionInfo.Count == 0)
     {
         HostVersionInfo.Add("gitlab.com", ApiVersion.V4_Oauth);
         HostVersionInfo.Add("gitclub.cn", ApiVersion.V4_Oauth);
         HostVersionInfo.Add("gitee.com", ApiVersion.V3_1);
         SaveHostVersion();
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Retrieves a <see cref="SetCodeItems"/> of CodeItems within the specified document.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="loadLazyInitializedValues">
        /// A flag indicating if lazy initialized values should be immediately loaded.
        /// </param>
        /// <returns>The set of code items within the document.</returns>
        internal SetCodeItems RetrieveAllCodeItems(Document document, bool loadLazyInitializedValues = false)
        {
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            OutputWindowHelper.DiagnosticWriteLine(
                string.Format("CodeModelManager.RetrieveAllCodeItems for '{0}'", document.FullName));

            var codeModel = _codeModelCache.GetCodeModel(document);

            if (codeModel.IsBuilding)
            {
                if (!codeModel.IsBuiltWaitHandle.WaitOne(TimeSpan.FromSeconds(30)))
                {
                    OutputWindowHelper.WarningWriteLine(
                        string.Format("Timed out waiting for code model to be built for '{0}'", codeModel.Document.FullName));
                    return(null);
                }
            }
            else if (codeModel.IsStale)
            {
                BuildCodeItems(codeModel);

                if (loadLazyInitializedValues)
                {
                    LoadLazyInitializedValues(codeModel);
                }
            }

            return(codeModel.CodeItems);
        }
Exemplo n.º 3
0
        /// <summary>
        ///     Replaces GUID placeholders in a document.
        /// </summary>
        /// <param name="document">The document.</param>
        private void ReplaceGuidPlaceholders(Document document)
        {
            // Make sure the document to be cleaned up is active, required for some commands like format document.
            document.Activate();

            // Check for designer windows being active, which should not proceed with cleanup as the code isn't truly active.
            if (document.ActiveWindow.Caption.EndsWith(" [Design]"))
            {
                return;
            }

            if (Package.Dte.ActiveDocument != document)
            {
                OutputWindowHelper.WarningWriteLine(
                    $"Activation was not completed before replacing began for '{document.Name}'");
            }

            OutputWindowHelper.DiagnosticWriteLine($"ReplaceGuidPlaceholders started for '{document.FullName}'");
            Package.Dte.StatusBar.Text = $"Replacing GUID placeholders in '{document.Name}'...";

            var textDocument = document.GetTextDocument();

            ReplaceGuidPlaceholders(textDocument);

            Package.Dte.StatusBar.Text = $"Replaced GUID placeholders in '{document.Name}'.";
            OutputWindowHelper.DiagnosticWriteLine($"ReplaceGuidPlaceholders completed for '{document.FullName}'");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Finds a code cleanup method appropriate for the specified document, otherwise null.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>The code cleanup method, otherwise null.</returns>
        private Action <Document> FindCodeCleanupMethod(Document document)
        {
            switch (document.GetCodeLanguage())
            {
            case CodeLanguage.CSharp:
                return(RunCodeCleanupCSharp);

            case CodeLanguage.CPlusPlus:
            case CodeLanguage.CSS:
            case CodeLanguage.JavaScript:
            case CodeLanguage.JSON:
            case CodeLanguage.LESS:
            case CodeLanguage.PHP:
            case CodeLanguage.PowerShell:
            case CodeLanguage.R:
            case CodeLanguage.SCSS:
            case CodeLanguage.TypeScript:
                return(RunCodeCleanupC);

            case CodeLanguage.HTML:
            case CodeLanguage.XAML:
            case CodeLanguage.XML:
                return(RunCodeCleanupMarkup);

            case CodeLanguage.FSharp:
            case CodeLanguage.VisualBasic:
            case CodeLanguage.Unknown:
                return(RunCodeCleanupGeneric);

            default:
                OutputWindowHelper.WarningWriteLine($"FindCodeCleanupMethod does not recognize document language '{document.Language}'");
                return(null);
            }
        }
Exemplo n.º 5
0
 public void Erase()
 {
     try
     {
         List <FileInfo> files = new List <FileInfo>();
         files.Add(new FileInfo(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), $"{new Uri(Host).Host}.gitlab4vs")));
         files.Add(new FileInfo(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), $"{new Uri(Strings.DefaultHost).Host}.gitlab4vs")));
         files.Add(new FileInfo(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "gitlab4vs.cfg")));
         files.ForEach(f =>
         {
             try
             {
                 f.Delete();
             }
             catch (Exception)
             {
             }
         });
         EraseCredential($"git:{Host}");
         EraseCredential($"token:{Host}");
     }
     catch (Exception ex)
     {
         OutputWindowHelper.WarningWriteLine("Erase" + ex.Message);
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Finds a code cleanup method appropriate for the specified document, otherwise null.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>The code cleanup method, otherwise null.</returns>
        private Action <Document, bool> FindCodeCleanupMethod(Document document)
        {
            switch (document.Language)
            {
            case "CSharp":
                return(RunCodeCleanupCSharp);

            case "C/C++":
            case "CSS":
            case "JavaScript":
            case "JScript":
            case "LESS":
            case "SCSS":
            case "TypeScript":
                return(RunCodeCleanupC);

            case "HTML":
            case "HTMLX":
            case "XAML":
            case "XML":
                return(RunCodeCleanupMarkup);

            case "Basic":
            case "F#":
                return(RunCodeCleanupGeneric);

            default:
                OutputWindowHelper.WarningWriteLine(
                    string.Format("FindCodeCleanupMethod does not recognize document language '{0}'", document.Language));
                return(null);
            }
        }
Exemplo n.º 7
0
 private void SaveHostVersion()
 {
     try
     {
         var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "gitlab4vs.dat");
         System.IO.File.WriteAllText(filename, JsonConvert.SerializeObject(HostVersionInfo));
     }
     catch (Exception ex)
     {
         OutputWindowHelper.WarningWriteLine("Can't save host version info");
     }
 }
Exemplo n.º 8
0
 public void SaveConfig()
 {
     try
     {
         var filename = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "gitlab4vs.cfg");
         System.IO.File.WriteAllText(filename, JsonConvert.SerializeObject(AppSettings));
     }
     catch (Exception)
     {
         OutputWindowHelper.WarningWriteLine("Can't save config!");
     }
 }
Exemplo n.º 9
0
        /// <summary 代码清理逻辑> Attempts to run code
        /// cleanup on the specified document.
        /// </summary> <param name="document">The
        /// document for cleanup.</param>
        internal void Cleanup(Document document)
        {
            if (!_codeCleanupAvailabilityLogic.CanCleanupDocument(document, true))
            {
                return;
            }

            // Make sure the document to be cleaned
            // up is active, required for some
            // commands like format document.
            document.Activate();

            // Check for designer windows being
            // active, which should not proceed
            // with cleanup as the code isn't truly active.
            if (document.ActiveWindow.Caption.EndsWith(" [Design]"))
            {
                return;
            }

            if (_package.ActiveDocument != document)
            {
                OutputWindowHelper.WarningWriteLine($"Activation was not completed before cleaning began for '{document.Name}'");
            }

            // Conditionally start cleanup with reorganization.
            if (Settings.Default.Reorganizing_RunAtStartOfCleanup)
            {
                _codeReorganizationManager.Reorganize(document);
            }

            new UndoTransactionHelper(_package, string.Format(Resources.CodeMaidCleanupFor0, document.Name)).Run(
                delegate
            {
                //通过判断文档对应的语言类型,调用对应的清理方法来执行
                var cleanupMethod = FindCodeCleanupMethod(document);
                if (cleanupMethod != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup started for '{document.FullName}'");
                    _package.IDE.StatusBar.Text = string.Format(Resources.CodeMaidIsCleaning0, document.Name);

                    // Perform the set of
                    // configured cleanups
                    // based on the language.
                    cleanupMethod(document);

                    _package.IDE.StatusBar.Text = string.Format(Resources.CodeMaidCleaned0, document.Name);
                    OutputWindowHelper.DiagnosticWriteLine($"CodeCleanupManager.Cleanup completed for '{document.FullName}'");
                }
            });
        }
Exemplo n.º 10
0
        /// <summary>
        /// Attempts to run code cleanup on the specified document.
        /// </summary>
        /// <param name="document">The document for cleanup.</param>
        /// <param name="isAutoSave">A flag indicating if occurring due to auto-save.</param>
        internal void Cleanup(Document document, bool isAutoSave = false)
        {
            if (!_codeCleanupAvailabilityLogic.ShouldCleanup(document, true))
            {
                return;
            }

            // Make sure the document to be cleaned up is active, required for some commands like
            // format document.
            document.Activate();

            if (_package.ActiveDocument != document)
            {
                OutputWindowHelper.WarningWriteLine(
                    string.Format("Activation was not completed before cleaning began for '{0}'", document.Name));
            }

            // Conditionally start cleanup with reorganization.
            if (Settings.Default.Reorganizing_RunAtStartOfCleanup)
            {
                _codeReorderManager.Reorganize(document, isAutoSave);
            }

            _undoTransactionHelper.Run(
                () => !(isAutoSave && Settings.Default.General_SkipUndoTransactionsDuringAutoCleanupOnSave),
                delegate
            {
                var cleanupMethod = FindCodeCleanupMethod(document);
                if (cleanupMethod != null)
                {
                    OutputWindowHelper.DiagnosticWriteLine(
                        string.Format("CodeCleanupManager.Cleanup started for '{0}'", document.FullName));

                    _package.IDE.StatusBar.Text = string.Format("CodeMaid is cleaning '{0}'...", document.Name);

                    // Perform the set of configured cleanups based on the language.
                    cleanupMethod(document, isAutoSave);

                    _package.IDE.StatusBar.Text = string.Format("CodeMaid cleaned '{0}'.", document.Name);

                    OutputWindowHelper.DiagnosticWriteLine(
                        string.Format("CodeCleanupManager.Cleanup completed for '{0}'", document.FullName));
                }
            },
                delegate(Exception ex)
            {
                OutputWindowHelper.ExceptionWriteLine(
                    string.Format("Stopped cleaning '{0}'", document.Name), ex);
                _package.IDE.StatusBar.Text = string.Format("CodeMaid stopped cleaning '{0}'.  See output window for more details.", document.Name);
            });
        }
Exemplo n.º 11
0
 public void AddHostVersionInfo(string host, ApiVersion apiVersion)
 {
     try
     {
         if (Uri.TryCreate(host, UriKind.RelativeOrAbsolute, out var uri))
         {
             if (HostVersionInfo.ContainsKey(uri.Host))
             {
                 HostVersionInfo.Remove(uri.Host);
             }
             HostVersionInfo.Add(uri.Host, apiVersion);
             SaveHostVersion();
         }
         else
         {
             OutputWindowHelper.WarningWriteLine($"Can't Create Uri Host:{host},ApiVersion:{apiVersion}");
         }
     }
     catch (Exception ex)
     {
         OutputWindowHelper.ExceptionWriteLine("AddHostVersionInfo", ex);
     }
 }
Exemplo n.º 12
0
        private void MenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    try
                    {
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        command.Enabled = match.Success;
                        if (command.Enabled)
                        {
                            Uri uri = new Uri(match.Value);
                            command.Text = string.Format(Strings.OpenFrom0, uri.Host);
                        }
                        else
                        {
                            command.Text = Strings.OpenFromURL;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                {
                    try
                    {
                        var git = GitAnalysis.GetBy(GetActiveFilePath());
                        if (!git.IsDiscoveredGitRepository)
                        {
                            command.Enabled = false;
                            return;
                        }
                        var type       = ToGiteaUrlType(command.CommandID.ID);
                        var targetPath = git.GetGiteaTargetPath(type);
                        if (type == GiteaUrlType.CurrentBranch && targetPath == "master")
                        {
                            command.Visible = false;
                        }
                        else
                        {
                            command.Text    = git.GetGiteaTargetDescription(type);
                            command.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                var exstr = ex.ToString();
                Debug.Write(exstr);
                command.Text    = "error:" + ex.GetType().Name;
                command.Enabled = false;
                OutputWindowHelper.WarningWriteLine(ex.Message);
            }
        }
Exemplo n.º 13
0
        private void MenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    try
                    {
                        command.Enabled = false;
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        if (match.Success)
                        {
                            Uri uri = new Uri(match.Value);
                            if (uri.Host.ToLower() == "gitee.com")
                            {
                                command.Enabled = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                case PackageIds.OpenWebIDE:
                {
                    try
                    {
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        var git = GitAnalysis.GetBy(GetActiveFilePath());
                        if (!git.IsDiscoveredGitRepository)
                        {
                            command.Enabled = false;
                            return;
                        }
                        var type       = ToGiteaUrlType(command.CommandID.ID);
                        var targetPath = git.GetGiteaTargetPath(type);
                        if (type == GiteeUrlType.CurrentBranch && targetPath == "master")
                        {
                            command.Visible = false;
                        }
                        else
                        {
                            command.Text    = git.GetGiteaTargetDescription(type);
                            command.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                }
                break;

                case PackageIds.OpenCreateSnippet:
                    var selectionLineRange = GetSelectionLineRange();
                    command.Enabled = selectionLineRange != null && selectionLineRange.Item1 < selectionLineRange.Item2;
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                var exstr = ex.ToString();
                Debug.Write(exstr);
                command.Text    = "error:" + ex.GetType().Name;
                command.Enabled = false;
                OutputWindowHelper.WarningWriteLine(ex.Message);
            }
        }