diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml
index e9432e4..6cdb818 100644
--- a/.github/workflows/dotnet.yml
+++ b/.github/workflows/dotnet.yml
@@ -29,8 +29,8 @@ env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1
DOTNET_NOLOGO: true
VisxDirectory: ${{github.workspace}}/vsix
- Version: '2.1.0.${{ github.run_number }}'
- BaseVersion: '2.1.0.0'
+ Version: '2.1.1.${{ github.run_number }}'
+ BaseVersion: '2.1.1.0'
defaults:
run:
diff --git a/CodeDocumentor.Common/CodeDocumentor.Common.csproj b/CodeDocumentor.Common/CodeDocumentor.Common.csproj
new file mode 100644
index 0000000..d670910
--- /dev/null
+++ b/CodeDocumentor.Common/CodeDocumentor.Common.csproj
@@ -0,0 +1,13 @@
+
+
+
+ netstandard2.0
+
+
+
+
+
+
+
+
+
diff --git a/CodeDocumentor/Models/Constants.cs b/CodeDocumentor.Common/Constants.cs
similarity index 98%
rename from CodeDocumentor/Models/Constants.cs
rename to CodeDocumentor.Common/Constants.cs
index 5f9672b..167c8f2 100644
--- a/CodeDocumentor/Models/Constants.cs
+++ b/CodeDocumentor.Common/Constants.cs
@@ -1,16 +1,19 @@
// For definitions of XML nodes see:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments see
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
+using System;
using System.Collections.Generic;
-using CodeDocumentor.Helper;
+using CodeDocumentor.Common.Models;
using Microsoft.CodeAnalysis;
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common
{
public static class Constants
{
public const DiagnosticSeverity DefaultDiagnosticSeverityOnError = DiagnosticSeverity.Info;
+ public const string TODO = "TODO: Add Summary";
+
public static class EventIds
{
public const int ANALYZER = 1000;
diff --git a/CodeDocumentor.Common/Extensions/ListExtensions.cs b/CodeDocumentor.Common/Extensions/ListExtensions.cs
new file mode 100644
index 0000000..b4e08a4
--- /dev/null
+++ b/CodeDocumentor.Common/Extensions/ListExtensions.cs
@@ -0,0 +1,196 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Models;
+using Microsoft.CodeAnalysis;
+
+namespace CodeDocumentor.Helper
+{
+ public static class ListExtensions
+ {
+ public static List AddCustomPart(this List parts, string part = null, int idx = -1)
+ {
+ if (part is null)
+ {
+ return parts;
+ }
+ if (idx == -1)
+ {
+ parts.Add(part);
+ return parts;
+ }
+ parts.Insert(idx, part);
+ return parts;
+ }
+
+ public static string JoinToString(this List parts, string delimiter = " ")
+ {
+ return $"{string.Join(delimiter, parts)}";
+ }
+
+ public static List PluaralizeLastWord(this List parts)
+ {
+ var lastIdx = parts.Count - 1;
+ parts[lastIdx] = Pluralizer.ForcePluralization(parts[lastIdx]);
+ return parts;
+ }
+
+ public static List Tap(this List parts, Action> tapAction)
+ {
+ tapAction?.Invoke(parts);
+ return parts;
+ }
+
+ public static List ToLowerParts(this List parts, bool forceFirstCharToLower = false)
+ {
+ var i = forceFirstCharToLower ||
+ (
+ parts.Count > 0 &&
+ !parts[0].Equals("The", StringComparison.InvariantCultureIgnoreCase) &&
+ !parts[0].Equals("If true,", StringComparison.InvariantCultureIgnoreCase) &&
+ !parts[0].IsVerb() //if the first word is a verb we are not adding The anyway so we need to leave it Pascal
+ )
+ ? 0 : 1;
+
+ parts.SwapXmlTokens((part) =>
+ {
+ if (!part.All(a => char.IsUpper(a)))
+ {
+ part = part.ToLower();
+ }
+ return part;
+ }, i);
+
+ //First letter is always caps unless it was forced lower
+ if (!forceFirstCharToLower && parts.Count > 0 && char.IsLower(parts[0], 0))
+ {
+ parts[0] = parts[0].ToTitleCase();
+ }
+ return parts;
+ }
+
+ public static List TranslateParts(this List parts, WordMap[] wordMaps)
+ {
+ for (var i = 0; i < parts.Count; i++)
+ {
+ var nextWord = i + 1 < parts.Count ? parts[i + 1] : null;
+ var userMaps = wordMaps ?? Array.Empty();
+ foreach (var wordMap in Constants.INTERNAL_WORD_MAPS)
+ {
+ if (!CanEvaluateWordMap(wordMap, i))
+ {
+ continue;
+ }
+ //dont run an internal word map if the user has one for the same thing
+ if (!userMaps.Any(a => a.Word == wordMap.Word))
+ {
+ var wordToLookFor = string.Format(Constants.WORD_MATCH_REGEX_TEMPLATE, wordMap.Word);
+ parts[i] = Regex.Replace(parts[i], wordToLookFor, wordMap.GetTranslation(nextWord));
+ }
+ }
+ }
+ return parts;
+ }
+
+ private static bool CanEvaluateWordMap(WordMap wordMap, int partIdx)
+ {
+ return wordMap.Word != "Is" || partIdx == 0;
+ }
+
+ public static List TryInsertTheWord(this List parts, Action> customInsertCallback = null)
+ {
+ if (customInsertCallback != null)
+ {
+ customInsertCallback.Invoke(parts);
+ }
+ else if (parts.Count > 0)
+ {
+ var checkWord = parts[0].GetWordFirstPart();
+ var skipThe = checkWord.IsVerb();
+ var addTheAnyway = Constants.ADD_THE_ANYWAY_LIST.Any(w => w.Equals(parts[0], StringComparison.InvariantCultureIgnoreCase));
+ if (!skipThe || addTheAnyway)
+ {
+ if (!parts[0].Equals("the", StringComparison.InvariantCultureIgnoreCase))
+ {
+ parts.Insert(0, "The");
+ }
+ else
+ {
+ parts[0] = "The"; //force casing
+ }
+ }
+ }
+ return parts;
+ }
+
+ public static List AddPropertyBooleanPart(this List parts)
+ {
+ if (parts.Count > 0)
+ {
+ var booleanPart = " a value indicating whether to";
+ if (parts[0].IsPastTense() || parts[0].IsVerb())
+ {
+ booleanPart = "a value indicating whether";
+ }
+
+ //is messes up readability. Lets remove it. ex) IsEnabledForDays
+ var isTwoLettweWord = parts[0].IsTwoLetterPropertyExclusionVerb();//we only care if forst word is relavent
+ if (isTwoLettweWord)
+ {
+ parts.Remove(parts[0]);
+ }
+ parts.Insert(0, booleanPart);
+ }
+
+ return parts;
+ }
+
+ public static List HandleAsyncKeyword(this List parts, bool excludeAsyncSuffix)
+ {
+ if (excludeAsyncSuffix && parts.Last().IndexOf("async", StringComparison.OrdinalIgnoreCase) > -1)
+ {
+ parts.Remove(parts.Last());
+ }
+ var idx = parts.FindIndex(f => f.Equals("async", StringComparison.OrdinalIgnoreCase));
+ if (idx > -1)
+ {
+ parts[idx] = "asynchronously";
+ }
+ return parts;
+ }
+
+ public static List TryAddTodoSummary(this List parts, string returnType, bool useToDoCommentsOnSummaryError)
+ {
+ if (returnType == "void" && (parts.Count == 1 || (parts.Count == 2 && parts.Last() == "asynchronously")))
+ {
+ if (useToDoCommentsOnSummaryError)
+ {
+ parts = new List { Constants.TODO};
+ }
+ else
+ {
+ parts = new List();
+ }
+ }
+ return parts;
+ }
+
+ public static List TryPluarizeFirstWord(this List parts)
+ {
+ if (parts.Count > 0)
+ {
+ if (parts.Count >= 2)
+ {
+ parts[0] = Pluralizer.Pluralize(parts[0], parts[1]);
+ }
+ else
+ {
+ parts[0] = Pluralizer.Pluralize(parts[0]);
+ }
+ }
+ return parts;
+ }
+ }
+}
diff --git a/CodeDocumentor.Common/Extensions/SettingsExtensions.cs b/CodeDocumentor.Common/Extensions/SettingsExtensions.cs
new file mode 100644
index 0000000..2f6c787
--- /dev/null
+++ b/CodeDocumentor.Common/Extensions/SettingsExtensions.cs
@@ -0,0 +1,160 @@
+#pragma warning disable IDE0130
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Common.Models;
+using Microsoft.CodeAnalysis;
+using Newtonsoft.Json;
+
+namespace CodeDocumentor.Common
+{
+ public static class SettingsExtensions
+ {
+ public const string PREFIX = "codedocumentor_";
+ //This impl was adopted from https://github.com/mike-ward/VSColorOutput64/tree/db549b54709ca77ae5538c4046c332f1e51f90e7
+
+ private static readonly string _programDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CodeDocumentor");
+
+ ///
+ /// Loads the .
+ ///
+ /// A Settings.
+ public static ISettings Load(this ISettings settings)
+ {
+ if (Runtime.RunningUnitTests)
+ {
+ return new Settings();
+ }
+
+ Directory.CreateDirectory(_programDataFolder);
+ var json = File.ReadAllText(GetSettingsFilePath());
+ settings = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
+ return settings;
+ }
+
+ public static void Save(this ISettings settings)
+ {
+ if (Runtime.RunningUnitTests)
+ {
+ return;
+ }
+
+ Directory.CreateDirectory(_programDataFolder);
+ settings.SaveToFile(GetSettingsFilePath());
+ }
+
+ public static void SaveToEditorConfig(this ISettings settings, Action setToClipboardAction)
+ {
+ if (Runtime.RunningUnitTests)
+ {
+ return;
+ }
+
+ var clipboardLInes = new List
+ {
+ "[*.cs]",
+ "# CodeDocumentor settings",
+ $"{PREFIX}class_diagram_severity = {settings.ClassDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}constructor_diagram_severity = {settings.ConstructorDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}default_diagram_severity = {settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}enum_diagram_severity = {settings.EnumDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}field_diagram_severity = {settings.FieldDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}interface_diagram_severity = {settings.InterfaceDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}method_diagram_severity = {settings.MethodDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}property_diagram_severity = {settings.PropertyDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}record_diagram_severity = {settings.RecordDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity}",
+ $"{PREFIX}exclude_async_suffix = {settings.ExcludeAsyncSuffix}",
+ $"{PREFIX}include_value_node_in_properties = {settings.IncludeValueNodeInProperties}",
+ $"{PREFIX}is_enabled_for_public_members_only = {settings.IsEnabledForPublicMembersOnly}",
+ $"{PREFIX}is_enabled_for_non_public_fields = {settings.IsEnabledForNonPublicFields}",
+ $"{PREFIX}preserve_existing_summary_text = {settings.PreserveExistingSummaryText}",
+ $"{PREFIX}try_to_include_crefs_for_return_types = {settings.TryToIncludeCrefsForReturnTypes}",
+ $"{PREFIX}use_natural_language_for_return_node = {settings.UseNaturalLanguageForReturnNode}",
+ $"{PREFIX}use_todo_comments_on_summary_error = {settings.UseToDoCommentsOnSummaryError}"
+ };
+
+ if (settings.WordMaps != null && settings.WordMaps.Length > 0)
+ {
+ var maps = settings.WordMaps.Where(wm => !string.IsNullOrWhiteSpace(wm?.Word) || !string.IsNullOrWhiteSpace(wm?.Translation))
+ .Select(s => $"{s.Word}:{s.Translation}").ToList();
+ clipboardLInes.Add($"{PREFIX}wordmap = {string.Join("|", maps)}");
+ }
+ setToClipboardAction.Invoke(string.Join(Environment.NewLine, clipboardLInes));
+ }
+
+ ///
+ /// Saves the settings to file.
+ ///
+ /// The path.
+ public static void SaveToFile(this ISettings settings, string path)
+ {
+ File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(settings));
+ }
+
+ public static void SetFromOptionsGrid(this ISettings settings, ISettings optionsGrid)
+ {
+ settings.DefaultDiagnosticSeverity = optionsGrid?.DefaultDiagnosticSeverity ?? DiagnosticSeverity.Warning;
+ settings.ClassDiagnosticSeverity = optionsGrid.ClassDiagnosticSeverity;
+ settings.ConstructorDiagnosticSeverity = optionsGrid.ConstructorDiagnosticSeverity;
+ settings.EnumDiagnosticSeverity = optionsGrid.EnumDiagnosticSeverity;
+ settings.FieldDiagnosticSeverity = optionsGrid.FieldDiagnosticSeverity;
+ settings.InterfaceDiagnosticSeverity = optionsGrid.InterfaceDiagnosticSeverity;
+ settings.MethodDiagnosticSeverity = optionsGrid.MethodDiagnosticSeverity;
+ settings.PropertyDiagnosticSeverity = optionsGrid.PropertyDiagnosticSeverity;
+ settings.RecordDiagnosticSeverity = optionsGrid.RecordDiagnosticSeverity;
+ settings.ExcludeAsyncSuffix = optionsGrid?.ExcludeAsyncSuffix ?? false;
+ settings.IncludeValueNodeInProperties = optionsGrid?.IncludeValueNodeInProperties ?? false;
+ settings.IsEnabledForPublicMembersOnly = optionsGrid?.IsEnabledForPublicMembersOnly ?? false;
+ settings.IsEnabledForNonPublicFields = optionsGrid?.IsEnabledForNonPublicFields ?? false;
+ settings.PreserveExistingSummaryText = optionsGrid?.PreserveExistingSummaryText ?? true;
+ settings.UseNaturalLanguageForReturnNode = optionsGrid?.UseNaturalLanguageForReturnNode ?? false;
+ settings.UseToDoCommentsOnSummaryError = optionsGrid?.UseToDoCommentsOnSummaryError ?? false;
+ settings.TryToIncludeCrefsForReturnTypes = optionsGrid?.TryToIncludeCrefsForReturnTypes ?? false;
+ settings.WordMaps = optionsGrid?.WordMaps ?? Constants.DEFAULT_WORD_MAPS;
+ }
+
+ public static ISettings Update(this ISettings settings, ISettings newSettings, IEventLogger logger)
+ {
+ settings.IsEnabledForPublicMembersOnly = newSettings.IsEnabledForPublicMembersOnly;
+ settings.UseNaturalLanguageForReturnNode = newSettings.UseNaturalLanguageForReturnNode;
+ settings.ExcludeAsyncSuffix = newSettings.ExcludeAsyncSuffix;
+ settings.IncludeValueNodeInProperties = newSettings.IncludeValueNodeInProperties;
+ settings.UseToDoCommentsOnSummaryError = newSettings.UseToDoCommentsOnSummaryError;
+ settings.WordMaps = newSettings.WordMaps;
+ settings.DefaultDiagnosticSeverity = newSettings.DefaultDiagnosticSeverity;
+ settings.PreserveExistingSummaryText = newSettings.PreserveExistingSummaryText;
+ settings.ClassDiagnosticSeverity = newSettings.ClassDiagnosticSeverity;
+ settings.ConstructorDiagnosticSeverity = newSettings.ConstructorDiagnosticSeverity;
+ settings.EnumDiagnosticSeverity = newSettings.EnumDiagnosticSeverity;
+ settings.FieldDiagnosticSeverity = newSettings.FieldDiagnosticSeverity;
+ settings.InterfaceDiagnosticSeverity = newSettings.InterfaceDiagnosticSeverity;
+ settings.MethodDiagnosticSeverity = newSettings.MethodDiagnosticSeverity;
+ settings.PropertyDiagnosticSeverity = newSettings.PropertyDiagnosticSeverity;
+ settings.RecordDiagnosticSeverity = newSettings.RecordDiagnosticSeverity;
+ settings.IsEnabledForNonPublicFields = newSettings.IsEnabledForNonPublicFields;
+ settings.TryToIncludeCrefsForReturnTypes = newSettings.TryToIncludeCrefsForReturnTypes;
+
+ logger.LogInfo(JsonConvert.SerializeObject(settings), 200, 0, "Options updated");
+ return settings;
+ }
+
+ ///
+ /// Gets the settings file path.
+ ///
+ /// A string.
+ private static string GetSettingsFilePath()
+ {
+ const string name = "codedocumentor.json";
+ var settingsPath = Path.Combine(_programDataFolder, name);
+
+ if (!File.Exists(settingsPath))
+ {
+ new Settings().SaveToFile(settingsPath);
+ }
+
+ return settingsPath;
+ }
+ }
+}
diff --git a/CodeDocumentor.Common/Extensions/StringExtensions.cs b/CodeDocumentor.Common/Extensions/StringExtensions.cs
new file mode 100644
index 0000000..aec5e8e
--- /dev/null
+++ b/CodeDocumentor.Common/Extensions/StringExtensions.cs
@@ -0,0 +1,26 @@
+#pragma warning disable IDE0130
+
+namespace System
+{
+ public static class StringExtensions
+ {
+ public static string RemovePeriod(this string text)
+ {
+ return text?.Trim().EndsWith(".") == true ? text.Remove(text.Length - 1) : text;
+ }
+
+ ///
+ /// Withs the period.
+ ///
+ /// The text.
+ /// A string.
+ public static string WithPeriod(this string text)
+ {
+ if (text?.Trim().EndsWith(".") == true)
+ {
+ return text;
+ }
+ return text.Length > 0 ? text + "." : text;
+ }
+ }
+}
diff --git a/CodeDocumentor/Helper/Translator.cs b/CodeDocumentor.Common/Extensions/Translator.cs
similarity index 56%
rename from CodeDocumentor/Helper/Translator.cs
rename to CodeDocumentor.Common/Extensions/Translator.cs
index cbd80ea..c5fa7ef 100644
--- a/CodeDocumentor/Helper/Translator.cs
+++ b/CodeDocumentor.Common/Extensions/Translator.cs
@@ -1,37 +1,19 @@
using System.Text.RegularExpressions;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
-using Microsoft.CodeAnalysis.CSharp;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Models;
namespace CodeDocumentor.Helper
{
public static class Translator
{
- private static IOptionsService _optionsService;
-
- ///
- /// Translates text replacing words from the WordMap settings
- ///
- ///
- /// A string
- public static string ApplyUserTranslations(this CSharpSyntaxNode node)
- {
- return TranslateText(node.ToString());
- }
-
///
/// Translates text replacing words from the WordMap settings
///
///
/// A string
- public static string ApplyUserTranslations(this string text)
- {
- return TranslateText(text);
- }
-
- public static void Initialize(IOptionsService optionsService)
+ public static string ApplyUserTranslations(this string text, WordMap[] wordMaps)
{
- _optionsService = optionsService;
+ return TranslateText(text, wordMaps);
}
///
@@ -39,16 +21,16 @@ public static void Initialize(IOptionsService optionsService)
///
///
/// A string
- internal static string TranslateText(string text)
+ private static string TranslateText(string text, WordMap[] wordMaps)
{
var converted = text;
- if (_optionsService.WordMaps == null)
+ if (wordMaps == null || wordMaps.Length == 0)
{
return converted;
}
converted = converted.SwapXmlTokens((line) =>
{
- foreach (var wordMap in _optionsService.WordMaps)
+ foreach (var wordMap in wordMaps)
{
var wordToLookFor = string.Format(Constants.WORD_MATCH_REGEX_TEMPLATE, wordMap.Word);
line = Regex.Replace(line, wordToLookFor, wordMap.GetTranslation());
diff --git a/CodeDocumentor.Common/Extensions/WordExtensions.cs b/CodeDocumentor.Common/Extensions/WordExtensions.cs
new file mode 100644
index 0000000..0a58630
--- /dev/null
+++ b/CodeDocumentor.Common/Extensions/WordExtensions.cs
@@ -0,0 +1,141 @@
+#pragma warning disable IDE0130
+using System.Collections.Generic;
+using System.Linq;
+using System.Text.RegularExpressions;
+using CodeDocumentor.Common;
+
+namespace System
+{
+ public static class WordExtensions
+ {
+ private static readonly Regex _xmlElementRegEx = new Regex(Constants.XML_ELEMENT_ONLY_MATCH_REGEX_TEMPLATE);
+
+ public static string Clean(this string word)
+ {
+ var pattern = "[^a-zA-Z0-9 ]";
+ return Regex.Replace(word, pattern, "");
+ }
+
+ public static string GetWordFirstPart(this string word)
+ {
+ var checkWord = word;
+ if (word.Contains(" ")) //a translation already happened and swapped a word for a set of words. the first word is really what we are checking
+ {
+ checkWord = word.Split(' ').First();
+ }
+ return checkWord;
+ }
+
+ public static bool IsPastTense(this string word)
+ {
+ // Check if the word ends with "-ed"
+ return word.EndsWith("ed");
+ }
+
+ public static bool IsIngVerb(this string word)
+ {
+ // Check if the word ends with "-ed"
+ return word.EndsWith("ing") && !word.Equals("string", StringComparison.InvariantCultureIgnoreCase);
+ }
+
+ public static bool IsTwoLetterPropertyExclusionVerb(this string word)
+ {
+ var checkWord = word.GetWordFirstPart().Clean();
+ return Constants.TWO_LETTER_PROPERTY_WORD_EXCLUSION_LIST.Any(w => w.Equals(checkWord, StringComparison.InvariantCultureIgnoreCase));
+ }
+
+ public static bool IsTwoLetterVerb(this string word)
+ {
+ var checkWord = word.GetWordFirstPart().Clean();
+ return Constants.TWO_LETTER_WORD_LIST.Any(w => w.Equals(checkWord, StringComparison.InvariantCultureIgnoreCase));
+ }
+
+ public static bool IsVerb(this string word)
+ {
+ var checkWord = word.GetWordFirstPart().Clean();
+ var variations = new List();
+ var baseWord = checkWord;
+ if (checkWord.IsIngVerb())
+ {
+ return true;
+ }
+ else if (Constants.PAST_TENSE_WORDS_NOT_VERBS.Any(a => a.Equals(checkWord, StringComparison.InvariantCultureIgnoreCase)))
+ {
+ return false;
+ }
+ else if (baseWord.IsPastTense()) //remove "ed"
+ {
+ baseWord = baseWord.Substring(0, checkWord.Length - 2);
+ }
+ else if (baseWord.EndsWith("s") && !Constants.LETTER_S_SUFFIX_EXCLUSION_FOR_PLURALIZER.Any(a => a.Equals(baseWord, StringComparison.InvariantCultureIgnoreCase)))
+ {
+ baseWord = baseWord.Substring(0, checkWord.Length - 1);
+ }
+
+ return Constants.GetInternalVerbCheckList().Any(w =>
+ w.Equals(baseWord, StringComparison.InvariantCultureIgnoreCase)
+ || checkWord.Equals((w + "ed"), StringComparison.InvariantCultureIgnoreCase)
+ //|| checkWord.Equals((w + "ing"), System.StringComparison.InvariantCultureIgnoreCase)
+ || (checkWord.Equals((w + "s"), StringComparison.InvariantCultureIgnoreCase)
+ && !Constants.LETTER_S_SUFFIX_EXCLUSION_FOR_PLURALIZER.Any(a => a.Equals(w, StringComparison.InvariantCultureIgnoreCase)))
+ );
+ }
+
+ public static bool IsVerbCombo(this string word, string nextWord = null)
+ {
+ if (string.IsNullOrEmpty(word))
+ {
+ return false;
+ }
+ var skipWord = word.IsVerb();
+ var skipNextWord = false;
+ if (!string.IsNullOrEmpty(nextWord) && !skipWord)
+ {
+ skipNextWord = nextWord.IsVerb();
+ }
+ return skipWord || skipNextWord;
+ }
+
+ public static bool IsXml(this string str)
+ {
+ if (string.IsNullOrEmpty(str))
+ {
+ return false;
+ }
+ return _xmlElementRegEx.IsMatch(str);
+ }
+
+ public static bool StartsWith_A_An_And(this string str)
+ {
+ if (string.IsNullOrEmpty(str))
+ {
+ return false;
+ }
+ return str.StartsWith("a ", StringComparison.InvariantCultureIgnoreCase) ||
+ str.StartsWith("an ", StringComparison.InvariantCultureIgnoreCase) ||
+ str.StartsWith("and ", StringComparison.InvariantCultureIgnoreCase);
+ }
+
+ public static string ToTitleCase(this string txt)
+ {
+ if (string.IsNullOrEmpty(txt))
+ {
+ return txt;
+ }
+
+ return char.ToUpper(txt[0]) + txt.Substring(1);
+ }
+
+ public static void TryAddSingleWord(this List words, List singleWord, bool clearSingleWord = false)
+ {
+ if (singleWord.Any())
+ {
+ words.Add(new string(singleWord.ToArray()));
+ }
+ if (clearSingleWord)
+ {
+ singleWord.Clear();
+ }
+ }
+ }
+}
diff --git a/CodeDocumentor/Helper/DictionaryExtensions.cs b/CodeDocumentor.Common/Helpers/DictionaryExtensions.cs
similarity index 84%
rename from CodeDocumentor/Helper/DictionaryExtensions.cs
rename to CodeDocumentor.Common/Helpers/DictionaryExtensions.cs
index d461a32..9c5e148 100644
--- a/CodeDocumentor/Helper/DictionaryExtensions.cs
+++ b/CodeDocumentor.Common/Helpers/DictionaryExtensions.cs
@@ -1,6 +1,6 @@
-using System.Collections.Generic;
+#pragma warning disable IDE0130
-namespace CodeDocumentor.Helper
+namespace System.Collections.Generic
{
public static class DictionaryExtensions
{
diff --git a/CodeDocumentor/Helper/NameSplitter.cs b/CodeDocumentor.Common/Helpers/NameSplitter.cs
similarity index 99%
rename from CodeDocumentor/Helper/NameSplitter.cs
rename to CodeDocumentor.Common/Helpers/NameSplitter.cs
index 4d69cbf..23117b0 100644
--- a/CodeDocumentor/Helper/NameSplitter.cs
+++ b/CodeDocumentor.Common/Helpers/NameSplitter.cs
@@ -3,7 +3,7 @@
using System.Linq;
using System.Text.RegularExpressions;
-namespace CodeDocumentor.Helper
+namespace CodeDocumentor.Common
{
///
/// The name splitter.
diff --git a/CodeDocumentor/Helper/Pluralizer.cs b/CodeDocumentor.Common/Helpers/Pluralizer.cs
similarity index 96%
rename from CodeDocumentor/Helper/Pluralizer.cs
rename to CodeDocumentor.Common/Helpers/Pluralizer.cs
index b3e54b2..86b41cd 100644
--- a/CodeDocumentor/Helper/Pluralizer.cs
+++ b/CodeDocumentor.Common/Helpers/Pluralizer.cs
@@ -1,4 +1,5 @@
-namespace CodeDocumentor.Helper
+#pragma warning disable IDE0130
+namespace System
{
public static class Pluralizer
{
diff --git a/CodeDocumentor/Helper/TokenHelper.cs b/CodeDocumentor.Common/Helpers/TokenHelper.cs
similarity index 84%
rename from CodeDocumentor/Helper/TokenHelper.cs
rename to CodeDocumentor.Common/Helpers/TokenHelper.cs
index b6e9a1a..d4c4a1d 100644
--- a/CodeDocumentor/Helper/TokenHelper.cs
+++ b/CodeDocumentor.Common/Helpers/TokenHelper.cs
@@ -1,16 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
-using CodeDocumentor.Vsix2022;
-namespace CodeDocumentor.Helper
+namespace CodeDocumentor.Common
{
//This takes XML nodes in a string and swaps them to tokens for string manipulation, and then replaces them once complete. This keeps the validity of the XML
- internal static class TokenHelper
+ public static class TokenHelper
{
private static readonly Regex _xmlElementRegEx = new Regex(Constants.XML_ELEMENT_MATCH_REGEX_TEMPLATE);
- internal static void SwapXmlTokens(this List parts, Func swapLineCallback, int startingIndex = 0)
+ public static void SwapXmlTokens(this List parts, Func swapLineCallback, int startingIndex = 0)
{
var i = startingIndex;
var swaps = new Dictionary();
@@ -34,7 +33,7 @@ internal static void SwapXmlTokens(this List parts, Func
}
}
- internal static string SwapXmlTokens(this string content, Func swapLineCallback, int startingIndex = 0)
+ public static string SwapXmlTokens(this string content, Func swapLineCallback, int startingIndex = 0)
{
var i = startingIndex;
var swaps = new Dictionary();
@@ -54,7 +53,7 @@ internal static string SwapXmlTokens(this string content, Func s
return content;
}
- internal static (string replacedString, Dictionary tokens) SwapXmlTokens(this string content, int startingIndex = 0)
+ public static (string replacedString, Dictionary tokens) SwapXmlTokens(this string content, int startingIndex = 0)
{
var i = startingIndex;
var swaps = new Dictionary();
diff --git a/CodeDocumentor/Helper/TryHelper.cs b/CodeDocumentor.Common/Helpers/TryHelper.cs
similarity index 50%
rename from CodeDocumentor/Helper/TryHelper.cs
rename to CodeDocumentor.Common/Helpers/TryHelper.cs
index 9278e47..5a508ae 100644
--- a/CodeDocumentor/Helper/TryHelper.cs
+++ b/CodeDocumentor.Common/Helpers/TryHelper.cs
@@ -1,11 +1,11 @@
using System;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common.Interfaces;
-namespace CodeDocumentor.Helper
+namespace CodeDocumentor.Common
{
- internal static class TryHelper
+ public static class TryHelper
{
- internal static void Try(Action action, Action exceptionCallback = null, bool reThrow = false, int eventId = 0, short category = 0)
+ public static void Try(Action action, string diagnosticId, IEventLogger logger, Action exceptionCallback = null, bool reThrow = false, int eventId = 0, short category = 0)
{
try
{
@@ -13,7 +13,7 @@ internal static void Try(Action action, Action exceptionCallback = nu
}
catch (Exception ex)
{
- Log.LogError(ex.ToString(), eventId, category);
+ logger.LogError(ex.ToString(), eventId, category, diagnosticId);
exceptionCallback?.Invoke(ex);
if (reThrow)
{
@@ -22,7 +22,7 @@ internal static void Try(Action action, Action exceptionCallback = nu
}
}
- internal static TResult Try(Func action, Func exceptionCallback, bool reThrow = false, int eventId = 0, short category = 0)
+ public static TResult Try(Func action, string diagnosticId, IEventLogger logger, Func exceptionCallback, bool reThrow = false, int eventId = 0, short category = 0)
{
try
{
@@ -30,7 +30,7 @@ internal static TResult Try(Func action, Func(Func action, Func(Func action, Action exceptionCallback = null, bool reThrow = false, int eventId = 0, short category = 0)
+ public static TResult Try(Func action, string diagnosticId, IEventLogger logger, Action exceptionCallback = null, bool reThrow = false, int eventId = 0, short category = 0)
{
try
{
@@ -47,7 +47,7 @@ internal static TResult Try(Func action, Action exc
}
catch (Exception ex)
{
- Log.LogError(ex.ToString(), eventId, category);
+ logger.LogError(ex.ToString(), eventId, category, diagnosticId);
exceptionCallback?.Invoke(ex);
if (reThrow)
{
diff --git a/CodeDocumentor.Common/Interfaces/IEventLogger.cs b/CodeDocumentor.Common/Interfaces/IEventLogger.cs
new file mode 100644
index 0000000..a8c4fcf
--- /dev/null
+++ b/CodeDocumentor.Common/Interfaces/IEventLogger.cs
@@ -0,0 +1,11 @@
+// For definitions of XML nodes see:
+// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments see
+// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
+namespace CodeDocumentor.Common.Interfaces
+{
+ public interface IEventLogger
+ {
+ void LogError(string message, int eventId, short category, string diagnosticId);
+ void LogInfo(string message, int eventId, short category, string diagnosticId);
+ }
+}
diff --git a/CodeDocumentor/Interfaces/IOptionPageGrid.cs b/CodeDocumentor.Common/Interfaces/ISettings.cs
similarity index 87%
rename from CodeDocumentor/Interfaces/IOptionPageGrid.cs
rename to CodeDocumentor.Common/Interfaces/ISettings.cs
index e1187e6..4e5c5d8 100644
--- a/CodeDocumentor/Interfaces/IOptionPageGrid.cs
+++ b/CodeDocumentor.Common/Interfaces/ISettings.cs
@@ -1,11 +1,12 @@
+using CodeDocumentor.Common.Models;
using Microsoft.CodeAnalysis;
// For definitions of XML nodes see:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments see
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common.Interfaces
{
- public interface IOptionPageGrid
+ public interface ISettings
{
DiagnosticSeverity? ClassDiagnosticSeverity { get; set; }
@@ -63,6 +64,12 @@ public interface IOptionPageGrid
/// A bool.
bool TryToIncludeCrefsForReturnTypes { get; set; }
+ ///
+ /// Gets or Sets a value indicating whether to use the .editorconfig file for settings.
+ ///
+ /// This will convert the existing settings to a %USERPROFILE% .editorconfig file
+ bool UseEditorConfigForSettings { get; set; }
+
///
/// Gets or Sets a value indicating whether use natural language for return node.
///
@@ -80,5 +87,7 @@ public interface IOptionPageGrid
///
/// A list of wordmaps.
WordMap[] WordMaps { get; set; }
+
+ ISettings Clone();
}
}
diff --git a/CodeDocumentor/Models/ReturnTypeBuilderOptions.cs b/CodeDocumentor.Common/Models/ReturnTypeBuilderOptions.cs
similarity index 97%
rename from CodeDocumentor/Models/ReturnTypeBuilderOptions.cs
rename to CodeDocumentor.Common/Models/ReturnTypeBuilderOptions.cs
index 9ffcca6..1b1ad0c 100644
--- a/CodeDocumentor/Models/ReturnTypeBuilderOptions.cs
+++ b/CodeDocumentor.Common/Models/ReturnTypeBuilderOptions.cs
@@ -1,4 +1,4 @@
-namespace CodeDocumentor.Helper
+namespace CodeDocumentor.Common.Models
{
public class ReturnTypeBuilderOptions
{
diff --git a/CodeDocumentor/Models/Runtime.cs b/CodeDocumentor.Common/Models/Runtime.cs
similarity index 92%
rename from CodeDocumentor/Models/Runtime.cs
rename to CodeDocumentor.Common/Models/Runtime.cs
index f7abba6..1ff4c2a 100644
--- a/CodeDocumentor/Models/Runtime.cs
+++ b/CodeDocumentor.Common/Models/Runtime.cs
@@ -1,7 +1,7 @@
// For definitions of XML nodes see:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments see
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common.Models
{
public static class Runtime
{
diff --git a/CodeDocumentor/Models/Settings.cs b/CodeDocumentor.Common/Models/Settings.cs
similarity index 56%
rename from CodeDocumentor/Models/Settings.cs
rename to CodeDocumentor.Common/Models/Settings.cs
index 72cd0e2..c253f28 100644
--- a/CodeDocumentor/Models/Settings.cs
+++ b/CodeDocumentor.Common/Models/Settings.cs
@@ -1,67 +1,61 @@
-using System;
-using System.IO;
+
+using System.Collections.Generic;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
// For definitions of XML nodes see:
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/documentation-comments see
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common.Models
{
- public class Settings : IOptionPageGrid
+ public class Settings : ISettings
{
- //This impl was adopted from https://github.com/mike-ward/VSColorOutput64/tree/db549b54709ca77ae5538c4046c332f1e51f90e7
-
- private static readonly string _programDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CodeDocumentor");
-
public DiagnosticSeverity? ClassDiagnosticSeverity { get; set; }
public DiagnosticSeverity? ConstructorDiagnosticSeverity { get; set; }
- ///
- /// Gets or Sets the default diagnostic severity.
- ///
public DiagnosticSeverity DefaultDiagnosticSeverity { get; set; } = DiagnosticSeverity.Warning;
public DiagnosticSeverity? EnumDiagnosticSeverity { get; set; }
+ public DiagnosticSeverity? FieldDiagnosticSeverity { get; set; }
+
+ public DiagnosticSeverity? InterfaceDiagnosticSeverity { get; set; }
+
+ public DiagnosticSeverity? MethodDiagnosticSeverity { get; set; }
+
+ public DiagnosticSeverity? PropertyDiagnosticSeverity { get; set; }
+
+ public DiagnosticSeverity? RecordDiagnosticSeverity { get; set; }
+
///
/// Gets or Sets a value indicating whether exclude asynchronously suffix.
///
/// A bool.
public bool ExcludeAsyncSuffix { get; set; }
- public DiagnosticSeverity? FieldDiagnosticSeverity { get; set; }
-
///
/// Gets or Sets a value indicating whether include value node in properties.
///
/// A bool.
public bool IncludeValueNodeInProperties { get; set; }
- public DiagnosticSeverity? InterfaceDiagnosticSeverity { get; set; }
-
- ///
- /// Gets or Sets a value indicating whether enabled for non public is fields.
- ///
- public bool IsEnabledForNonPublicFields { get; set; }
-
///
/// Gets or Sets a value indicating whether enabled for publish members is only.
///
/// A bool.
public bool IsEnabledForPublicMembersOnly { get; set; }
- public DiagnosticSeverity? MethodDiagnosticSeverity { get; set; }
+ ///
+ /// Gets or Sets a value indicating whether enabled for non public is fields.
+ ///
+ public bool IsEnabledForNonPublicFields { get; set; }
///
/// Gets or Sets a value indicating whether preserve existing summary text.
///
public bool PreserveExistingSummaryText { get; set; } = true;
- public DiagnosticSeverity? PropertyDiagnosticSeverity { get; set; }
-
- public DiagnosticSeverity? RecordDiagnosticSeverity { get; set; }
-
///
/// Gets or Sets a value indicating whether use try and include crefs in method comments.
///
@@ -86,71 +80,48 @@ public class Settings : IOptionPageGrid
/// An array of wordmaps.
public WordMap[] WordMaps { get; set; } = Constants.DEFAULT_WORD_MAPS;
- public static event EventHandler SettingsUpdated;
-
///
- /// Loads the .
+ /// Gets or Sets a value indicating whether to use the .editorconfig file for settings.
///
- /// A Settings.
- public static Settings Load()
- {
- if (Runtime.RunningUnitTests)
- {
- return new Settings();
- }
+ ///
+ /// This will convert the existing settings to a %USERPROFILE% .editorconfig file
+ ///
+ public bool UseEditorConfigForSettings { get; set; }
- Directory.CreateDirectory(_programDataFolder);
- var json = File.ReadAllText(GetSettingsFilePath());
- var settings = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
- return settings;
- }
-
- ///
- /// Saves the settings
- ///
- public void Save()
+ public ISettings Clone()
{
- if (Runtime.RunningUnitTests)
+ var newService = new Settings
{
- return;
- }
-
- Directory.CreateDirectory(_programDataFolder);
- SaveToFile(GetSettingsFilePath());
- OnSettingsUpdated(this, EventArgs.Empty);
- }
-
- ///
- /// Saves the settings to file.
- ///
- /// The path.
- public void SaveToFile(string path)
- {
- File.WriteAllText(path, Newtonsoft.Json.JsonConvert.SerializeObject(this));
- }
-
- ///
- /// Gets the settings file path.
- ///
- /// A string.
- private static string GetSettingsFilePath()
- {
- const string name = "codedocumentor.json";
- var settingsPath = Path.Combine(_programDataFolder, name);
-
- if (!File.Exists(settingsPath))
+ ClassDiagnosticSeverity = ClassDiagnosticSeverity,
+ ConstructorDiagnosticSeverity = ConstructorDiagnosticSeverity,
+ DefaultDiagnosticSeverity = DefaultDiagnosticSeverity,
+ EnumDiagnosticSeverity = EnumDiagnosticSeverity,
+ ExcludeAsyncSuffix = ExcludeAsyncSuffix,
+ FieldDiagnosticSeverity = FieldDiagnosticSeverity,
+ IncludeValueNodeInProperties = IncludeValueNodeInProperties,
+ InterfaceDiagnosticSeverity = InterfaceDiagnosticSeverity,
+ IsEnabledForNonPublicFields = IsEnabledForNonPublicFields,
+ IsEnabledForPublicMembersOnly = IsEnabledForPublicMembersOnly,
+ MethodDiagnosticSeverity = MethodDiagnosticSeverity,
+ PreserveExistingSummaryText = PreserveExistingSummaryText,
+ PropertyDiagnosticSeverity = PropertyDiagnosticSeverity,
+ RecordDiagnosticSeverity = RecordDiagnosticSeverity,
+ TryToIncludeCrefsForReturnTypes = TryToIncludeCrefsForReturnTypes,
+ UseNaturalLanguageForReturnNode = UseNaturalLanguageForReturnNode,
+ UseToDoCommentsOnSummaryError = UseNaturalLanguageForReturnNode
+ };
+ var clonedMaps = new List();
+ foreach (var item in WordMaps)
{
- new Settings().SaveToFile(settingsPath);
+ clonedMaps.Add(new WordMap
+ {
+ Translation = item.Translation,
+ Word = item.Word,
+ WordEvaluator = item.WordEvaluator
+ });
}
-
- return settingsPath;
+ newService.WordMaps = clonedMaps.ToArray();
+ return newService;
}
-
- ///
- /// Ons the settings updated.
- ///
- /// The sender.
- /// The ea.
- private static void OnSettingsUpdated(object sender, EventArgs ea) => SettingsUpdated?.Invoke(sender, ea);
}
}
diff --git a/CodeDocumentor/Models/WordMap.cs b/CodeDocumentor.Common/Models/WordMap.cs
similarity index 96%
rename from CodeDocumentor/Models/WordMap.cs
rename to CodeDocumentor.Common/Models/WordMap.cs
index 9f89762..5933bb8 100644
--- a/CodeDocumentor/Models/WordMap.cs
+++ b/CodeDocumentor.Common/Models/WordMap.cs
@@ -3,7 +3,7 @@
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
using System;
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common.Models
{
public class WordMap
{
diff --git a/CodeDocumentor/Models/XmlInformation.cs b/CodeDocumentor.Common/Models/XmlInformation.cs
similarity index 96%
rename from CodeDocumentor/Models/XmlInformation.cs
rename to CodeDocumentor.Common/Models/XmlInformation.cs
index cc16a4a..060662a 100644
--- a/CodeDocumentor/Models/XmlInformation.cs
+++ b/CodeDocumentor.Common/Models/XmlInformation.cs
@@ -3,7 +3,7 @@
// also https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags
using System.Text.RegularExpressions;
-namespace CodeDocumentor.Vsix2022
+namespace CodeDocumentor.Common.Models
{
public class XmlInformation
{
diff --git a/CodeDocumentor.Test/Builders/DocumentationBuilderTests.cs b/CodeDocumentor.Test/Builders/DocumentationBuilderTests.cs
index 5c8bd65..c576801 100644
--- a/CodeDocumentor.Test/Builders/DocumentationBuilderTests.cs
+++ b/CodeDocumentor.Test/Builders/DocumentationBuilderTests.cs
@@ -1,15 +1,8 @@
-using System;
-using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
using CodeDocumentor.Builders;
-using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common.Interfaces;
using FluentAssertions;
-using Microsoft.VisualStudio.TestPlatform.Utilities;
+using Moq;
using Xunit;
using Xunit.Abstractions;
@@ -28,14 +21,15 @@ public DocumentationBuilderTests(TestFixture fixture, ITestOutputHelper output)
_output = output;
_fixture.Initialize(output);
_builder = new DocumentationBuilder();
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
}
[Fact]
public void CreateReturnComment__ReturnsValidNameWithStartingWord_WhenUseNaturalLanguageForReturnNodeIsTrue()
{
var method = TestFixture.BuildMethodDeclarationSyntax("TResult", "Tester");
- var comment = _builder.WithReturnType(method).Build();
+ _fixture.MockSettings.UseNaturalLanguageForReturnNode = true;
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes = false;
+ var comment = _builder.WithReturnType(method, _fixture.MockSettings.UseNaturalLanguageForReturnNode, _fixture.MockSettings.TryToIncludeCrefsForReturnTypes, _fixture.MockSettings.WordMaps).Build();
comment.Count.Should().Be(3);
comment[1].ToFullString().Should().Be(@"A ");
}
diff --git a/CodeDocumentor.Test/Classes/ClassUnitTests.cs b/CodeDocumentor.Test/Classes/ClassUnitTests.cs
index 10cde00..3891a12 100644
--- a/CodeDocumentor.Test/Classes/ClassUnitTests.cs
+++ b/CodeDocumentor.Test/Classes/ClassUnitTests.cs
@@ -50,15 +50,16 @@ public async Task NoDiagnosticsShow(string testCode)
[Theory]
[InlineData("ClassTester.cs", "ClassTesterFix.cs", 3, 19, TestFixture.DIAG_TYPE_PRIVATE)]
[InlineData("PublicClassTester.cs", "PublicClassTesterFix.cs", 3, 26, TestFixture.DIAG_TYPE_PUBLIC_ONLY)]
+ [InlineData("ClassConstructorTester.cs", "ClassConstructorTesterFix.cs", 3, 18, TestFixture.DIAG_TYPE_PUBLIC_ONLY)]
public async Task ShowClassDiagnosticAndFix(string testCode, string fixCode, int line, int column, string diagType)
{
var fix = _fixture.LoadTestFile($"./Classes/TestFiles/{fixCode}");
var test = _fixture.LoadTestFile($"./Classes/TestFiles/{testCode}");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- _fixture.SetPublicProcessingOption(o, diagType);
- });
+ var clone = new TestSettings();
+ _fixture.SetPublicProcessingOption(clone, diagType);
+ _fixture.MockSettings.SetClone(clone);
+
var expected = new DiagnosticResult
{
Id = ClassAnalyzerSettings.DiagnosticId,
@@ -80,10 +81,10 @@ public async Task SkipsClassDiagnosticAndFixWhenPublicOnlyTrue()
{
var fix = _fixture.LoadTestFile("./Classes/TestFiles/ClassTester.cs");
var test = _fixture.LoadTestFile("./Classes/TestFiles/ClassTester.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.IsEnabledForPublicMembersOnly = true;
- });
+ var clone = new TestSettings {
+ IsEnabledForPublicMembersOnly = true
+ };
+ _fixture.MockSettings.SetClone(clone);
await VerifyCSharpDiagnosticAsync(test, TestFixture.DIAG_TYPE_PUBLIC_ONLY);
diff --git a/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTester.cs b/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTester.cs
new file mode 100644
index 0000000..4e94b09
--- /dev/null
+++ b/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTester.cs
@@ -0,0 +1,6 @@
+namespace ConsoleApp4
+{
+ public class ClassConstructorTester(string name, int age)
+ {
+ }
+}
diff --git a/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTesterFix.cs b/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTesterFix.cs
new file mode 100644
index 0000000..406f7b4
--- /dev/null
+++ b/CodeDocumentor.Test/Classes/TestFiles/ClassConstructorTesterFix.cs
@@ -0,0 +1,11 @@
+namespace ConsoleApp4
+{
+ ///
+ /// The class constructor tester.
+ ///
+ /// The name.
+ /// The age.
+ public class ClassConstructorTester(string name, int age)
+ {
+ }
+}
diff --git a/CodeDocumentor.Test/CodeDocumentor.Test.csproj b/CodeDocumentor.Test/CodeDocumentor.Test.csproj
index 214ca35..2e133a4 100644
--- a/CodeDocumentor.Test/CodeDocumentor.Test.csproj
+++ b/CodeDocumentor.Test/CodeDocumentor.Test.csproj
@@ -10,6 +10,8 @@
+
+
@@ -22,6 +24,8 @@
+
+
@@ -38,6 +42,12 @@
+
+
+
+
+
+
@@ -45,6 +55,8 @@
+
+
@@ -118,9 +130,15 @@
+
+ Always
+
Always
+
+ Always
+
Always
@@ -160,21 +178,39 @@
Always
+
+ Always
+
+
+ Always
+
Always
Always
+
+ Always
+
Always
+
+ Always
+
Always
+
+ Always
+
Always
+
+ Always
+
Always
@@ -304,6 +340,12 @@
+
+ Always
+
+
+ Always
+
Always
@@ -445,27 +487,26 @@
-
-
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
-
-
+
+
+
compile; build; native; contentfiles; analyzers; buildtransitive
-
-
-
-
-
-
-
+
+
+
+
+
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
-
+
all
runtime; build; native; contentfiles; analyzers; buildtransitive
diff --git a/CodeDocumentor.Test/Constructors/ConstructorUnitTests.cs b/CodeDocumentor.Test/Constructors/ConstructorUnitTests.cs
index 68f5712..44452a2 100644
--- a/CodeDocumentor.Test/Constructors/ConstructorUnitTests.cs
+++ b/CodeDocumentor.Test/Constructors/ConstructorUnitTests.cs
@@ -70,10 +70,9 @@ public async Task ShowConstructorDiagnosticAndFix(string testCode, string fixCod
{
var fix = _fixture.LoadTestFile($"./Constructors/TestFiles/{fixCode}");
var test = _fixture.LoadTestFile($"./Constructors/TestFiles/{testCode}");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- _fixture.SetPublicProcessingOption(o, diagType);
- });
+ var clone = new TestSettings();
+ _fixture.SetPublicProcessingOption(clone, diagType);
+ _fixture.MockSettings.SetClone(clone);
var expected = new DiagnosticResult
{
@@ -96,10 +95,11 @@ public async Task SkipsConstructorDiagnosticAndFixWhenPublicOnlyTrue()
{
var fix = _fixture.LoadTestFile("./Constructors/TestFiles/PrivateConstructorTestCode.cs");
var test = _fixture.LoadTestFile("./Constructors/TestFiles/PrivateConstructorTestCode.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
+ var clone = new TestSettings
{
- o.IsEnabledForPublicMembersOnly = true;
- });
+ IsEnabledForPublicMembersOnly = true
+ };
+ _fixture.MockSettings.SetClone(clone);
await VerifyCSharpDiagnosticAsync(test, TestFixture.DIAG_TYPE_PUBLIC_ONLY);
diff --git a/CodeDocumentor.Test/Helper/CommentHelperTests.cs b/CodeDocumentor.Test/Helper/CommentHelperTests.cs
index 98f72a8..b2e4e8a 100644
--- a/CodeDocumentor.Test/Helper/CommentHelperTests.cs
+++ b/CodeDocumentor.Test/Helper/CommentHelperTests.cs
@@ -1,8 +1,7 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Test.TestHelpers;
using FluentAssertions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
@@ -17,13 +16,14 @@ public class CommentHelperTests : IClassFixture
{
private readonly TestFixture _fixture;
private readonly ITestOutputHelper _output;
+ private CommentHelper _commentHelper;
public CommentHelperTests(TestFixture fixture, ITestOutputHelper output)
{
_fixture = fixture;
_output = output;
_fixture.Initialize(output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
+ _commentHelper = new CommentHelper();
}
[Theory]
@@ -33,7 +33,8 @@ public CommentHelperTests(TestFixture fixture, ITestOutputHelper output)
[InlineData("_hasErrors", "Has errors.")]
public void CreateFieldComment_ReturnsValidName(string name, string expected)
{
- var comment = CommentHelper.CreateFieldComment(name);
+
+ var comment = _commentHelper.CreateFieldComment(name, _fixture.MockSettings.ExcludeAsyncSuffix, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -67,14 +68,9 @@ public void CreateMethodComment_ReturnsValidName(string name, string returnType,
bool useToDoCommentsOnSummaryError = true
)
{
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.ExcludeAsyncSuffix = excludeAsyncSuffix;
- o.UseToDoCommentsOnSummaryError = useToDoCommentsOnSummaryError;
- o.TryToIncludeCrefsForReturnTypes = true;
- });
- _fixture.Initialize(_output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
+ _fixture.MockSettings.ExcludeAsyncSuffix = excludeAsyncSuffix;
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError = useToDoCommentsOnSummaryError;
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes = true;
TypeSyntax typeSyntax;
if (!string.IsNullOrEmpty(genericReturnType))
@@ -85,44 +81,48 @@ public void CreateMethodComment_ReturnsValidName(string name, string returnType,
{
typeSyntax = SyntaxFactory.ParseTypeName(returnType);
}
-
- var comment = CommentHelper.CreateMethodComment(name, typeSyntax);
+ var commentHelper = new CommentHelper();
+ var comment = commentHelper.CreateMethodComment(name, typeSyntax,
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError,
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes,
+ _fixture.MockSettings.ExcludeAsyncSuffix,
+ _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
[Fact]
public void CreateMethodComment_ReturnsValidCommentWhenOneWordMethodAndLayeredList()
{
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.ExcludeAsyncSuffix = false;
- o.UseToDoCommentsOnSummaryError = false;
- o.TryToIncludeCrefsForReturnTypes = true;
- });
- _fixture.Initialize(_output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
-
TypeSyntax typeSyntax = SyntaxFactory.ParseTypeName("Task>>");
- var comment = CommentHelper.CreateMethodComment("Work", typeSyntax);
+ _fixture.MockSettings.ExcludeAsyncSuffix = false;
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError = false;
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes = true;
+
+ var comment = _commentHelper.CreateMethodComment("Work", typeSyntax, _fixture.MockSettings.UseToDoCommentsOnSummaryError,
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes,
+ _fixture.MockSettings.ExcludeAsyncSuffix,
+ _fixture.MockSettings.WordMaps);
comment.Should().Be("Work and return a of a list of a list of strings.");
}
[Fact]
public void CreateMethodComment_ReturnsValidCommentWhenReturnIsTask_ActionResult_CustomType()
{
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.ExcludeAsyncSuffix = false;
- o.UseToDoCommentsOnSummaryError = false;
- o.TryToIncludeCrefsForReturnTypes = false;
- });
- _fixture.Initialize(_output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
+ var clone = new TestSettings {
+ ExcludeAsyncSuffix = false,
+ UseToDoCommentsOnSummaryError = false,
+ TryToIncludeCrefsForReturnTypes = false
+ };
+ _fixture.MockSettings.SetClone(clone);
TypeSyntax typeSyntax = SyntaxFactory.ParseTypeName("Task>");
-
- var comment = CommentHelper.CreateMethodComment("CreateAsync", typeSyntax);
+ var commentHelper = new CommentHelper();
+ var comment = commentHelper.CreateMethodComment("CreateAsync", typeSyntax,
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError,
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes,
+ _fixture.MockSettings.ExcludeAsyncSuffix,
+ _fixture.MockSettings.WordMaps);
comment.Should().Be("Creates and return a task of type actionresult of type clientdto asynchronously.");
}
@@ -138,14 +138,9 @@ public void CreateMethodComment_ReturnsValidNaturalLanguage(string name, string
bool useToDoCommentsOnSummaryError = true
)
{
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.ExcludeAsyncSuffix = excludeAsyncSuffix;
- o.UseToDoCommentsOnSummaryError = useToDoCommentsOnSummaryError;
- o.TryToIncludeCrefsForReturnTypes = false;
- });
- _fixture.Initialize(_output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
+ _fixture.MockSettings.ExcludeAsyncSuffix = excludeAsyncSuffix;
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError = useToDoCommentsOnSummaryError;
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes = false;
TypeSyntax typeSyntax;
if (!string.IsNullOrEmpty(genericReturnType))
@@ -157,7 +152,11 @@ public void CreateMethodComment_ReturnsValidNaturalLanguage(string name, string
typeSyntax = SyntaxFactory.ParseTypeName(returnType);
}
- var comment = CommentHelper.CreateMethodComment(name, typeSyntax);
+ var comment = _commentHelper.CreateMethodComment(name, typeSyntax,
+ _fixture.MockSettings.UseToDoCommentsOnSummaryError,
+ _fixture.MockSettings.TryToIncludeCrefsForReturnTypes,
+ _fixture.MockSettings.ExcludeAsyncSuffix,
+ _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -167,7 +166,7 @@ public void CreateMethodComment_ReturnsValidNaturalLanguage(string name, string
[InlineData("INotifier", "The notifier interface.")]
public void CreateInterfaceComment_ReturnsValidName(string name, string expected)
{
- var comment = CommentHelper.CreateInterfaceComment(name);
+ var comment = _commentHelper.CreateInterfaceComment(name, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -179,7 +178,7 @@ public void CreateInterfaceComment_ReturnsValidName(string name, string expected
[InlineData("ClientDto", "The client data transfer object.")]
public void CreateClassComment_ReturnsValidName(string name, string expected)
{
- var comment = CommentHelper.CreateClassComment(name);
+ var comment = _commentHelper.CreateClassComment(name, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -188,7 +187,7 @@ public void CreateClassComment_ReturnsValidName(string name, string expected)
[InlineData("ClientDto", "The client data transfer object.")]
public void CreateRecordComment_ReturnsValidName(string name, string expected)
{
- var comment = CommentHelper.CreateRecordComment(name);
+ var comment = _commentHelper.CreateRecordComment(name, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -198,7 +197,7 @@ public void CreateRecordComment_ReturnsValidName(string name, string expected)
[InlineData("HasError", "Gets a value indicating whether has error.", true, false)]
public void CreatePropertyComment_ReturnsValidName(string name, string expected, bool isBool, bool hasSetter)
{
- var comment = CommentHelper.CreatePropertyComment(name, isBool, hasSetter);
+ var comment = _commentHelper.CreatePropertyComment(name, isBool, hasSetter, _fixture.MockSettings.ExcludeAsyncSuffix, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -208,7 +207,7 @@ public void CreatePropertyComment_ReturnsValidName(string name, string expected,
[InlineData("ClientRole", "The clients roles.")]
public void CreateEnumComment_ReturnsValidName(string name, string expected)
{
- var comment = CommentHelper.CreateEnumComment(name);
+ var comment = _commentHelper.CreateEnumComment(name, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -233,7 +232,7 @@ public void CreateParameterComment_ReturnsValidName(string name, string paramTyp
}
var parameter = SyntaxFactory.Parameter(attributeLists, modifiers, typeSyntax, SyntaxFactory.Identifier(name), null);
- var comment = CommentHelper.CreateParameterComment(parameter);
+ var comment = _commentHelper.CreateParameterComment(parameter, _fixture.MockSettings.WordMaps);
comment.Should().Be(expected);
}
@@ -245,8 +244,8 @@ public void CreateParameterComment_ReturnsValidName(string name, string paramTyp
[InlineData("Dto", "Data transfer object")]
public void InternalTranslate_ConvertsCorrectly(string word, string converted)
{
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
- var result = CommentHelper.TranslateParts(new List { word });
+ var list = new List { word };
+ var result = list.TranslateParts(_fixture.MockSettings.WordMaps);
result.Should().Contain(converted);
}
}
diff --git a/CodeDocumentor.Test/Helper/DocumentationHeaderHelperTests.cs b/CodeDocumentor.Test/Helper/DocumentationHeaderHelperTests.cs
index 601f5cd..67b0aa6 100644
--- a/CodeDocumentor.Test/Helper/DocumentationHeaderHelperTests.cs
+++ b/CodeDocumentor.Test/Helper/DocumentationHeaderHelperTests.cs
@@ -3,18 +3,24 @@
using CodeDocumentor.Helper;
using FluentAssertions;
using Xunit;
+using Xunit.Abstractions;
namespace CodeDocumentor.Test.Helper
{
[SuppressMessage("XMLDocumentation", "")]
- public class DocumentationHeaderHelperTests
+ public class DocumentationHeaderHelperTests : IClassFixture
{
+ public DocumentationHeaderHelperTests(TestFixture fixture, ITestOutputHelper output)
+ {
+ fixture.Initialize(output);
+ _documentationHeaderHelper = new DocumentationHeaderHelper();
+ }
[Fact]
public void CreateReturnElementSyntax_ReturnsMultipleCRefAsEmbeddedNodeInReturn()
{
const string str = "A of type ";
const string expected = "A of type ";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -23,7 +29,7 @@ public void CreateReturnElementSyntax_ReturnsTypeParamRefAsEmbeddedNodeInReturn(
{
const string str = "A ";
const string expected = "A ";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -32,7 +38,7 @@ public void CreateReturnElementSyntax_ReturnsCDATAOfTaskInReturn()
{
const string str = "Task";
const string expected = "]]>";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -41,7 +47,7 @@ public void CreateReturnElementSyntax_ReturnsCDATAOfCDATATaskInReturn()
{
const string str = "]]>";
const string expected = "]]>";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -50,7 +56,7 @@ public void CreateReturnElementSyntax_ReturnsCRefOfTypeInReturn()
{
const string str = "";
const string expected = "";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
[Fact]
@@ -58,7 +64,7 @@ public void CreateReturnElementSyntax_ReturnsStringAndCRefOfTypeInReturn()
{
const string str = "Returns a ";
const string expected = "Returns a ";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -67,7 +73,7 @@ public void CreateReturnElementSyntax_ReturnsStringAndCRefOfInterfaceTypeInRetur
{
const string str = "Returns an ";
const string expected = "Returns an ";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -76,7 +82,7 @@ public void CreateReturnElementSyntax_ReturnsStringAnd2CRefOfTypesInReturn()
{
const string str = "Returns a of type ";
const string expected = "Returns a of type ";
- var result = DocumentationHeaderHelper.CreateReturnElementSyntax(str);
+ var result = _documentationHeaderHelper.CreateReturnElementSyntax(str);
result.ToFullString().Should().Be(expected);
}
@@ -161,11 +167,12 @@ public List> ShowMethodWithListListIntReturnTester()
}
}
}";
+ private DocumentationHeaderHelper _documentationHeaderHelper;
[Fact]
public void GetExceptions_ReturnsMatches()
{
- var exceptions = DocumentationHeaderHelper.GetExceptions(MethodWithException);
+ var exceptions = _documentationHeaderHelper.GetExceptions(MethodWithException);
Assert.Single(exceptions.ToList());
}
@@ -173,21 +180,21 @@ public void GetExceptions_ReturnsMatches()
[Fact]
public void GetExceptions_ReturnsNoMatches_WhenNoExceptions()
{
- var exceptions = DocumentationHeaderHelper.GetExceptions(MethodWithNoException);
+ var exceptions = _documentationHeaderHelper.GetExceptions(MethodWithNoException);
Assert.Empty(exceptions.ToList());
}
[Fact]
public void GetExceptions_ReturnsDistinctMatches_WhenDuplicateExceptions()
{
- var exceptions = DocumentationHeaderHelper.GetExceptions(MethodWithDuplicateException);
+ var exceptions = _documentationHeaderHelper.GetExceptions(MethodWithDuplicateException);
Assert.Single(exceptions.ToList());
}
[Fact]
public void GetExceptions_ReturnsTwoMatches_WhenExceptionAndThrowIfHelperException()
{
- var exceptions = DocumentationHeaderHelper.GetExceptions(MethodWithExceptionAndThrowIfHelperException);
+ var exceptions = _documentationHeaderHelper.GetExceptions(MethodWithExceptionAndThrowIfHelperException);
Assert.Equal(2, exceptions.ToList().Count);
}
#endregion
diff --git a/CodeDocumentor.Test/Helper/NameSplitterTests.cs b/CodeDocumentor.Test/Helper/NameSplitterTests.cs
index 8a36b6f..5965a75 100644
--- a/CodeDocumentor.Test/Helper/NameSplitterTests.cs
+++ b/CodeDocumentor.Test/Helper/NameSplitterTests.cs
@@ -1,6 +1,6 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
-using CodeDocumentor.Helper;
+using CodeDocumentor.Common;
using FluentAssertions;
using Xunit;
diff --git a/CodeDocumentor.Test/Helper/ReturnCommentConstructionTests.cs b/CodeDocumentor.Test/Helper/ReturnCommentConstructionTests.cs
index dfc1d87..7b25535 100644
--- a/CodeDocumentor.Test/Helper/ReturnCommentConstructionTests.cs
+++ b/CodeDocumentor.Test/Helper/ReturnCommentConstructionTests.cs
@@ -1,8 +1,6 @@
using System.Diagnostics.CodeAnalysis;
+using CodeDocumentor.Common.Models;
using CodeDocumentor.Constructors;
-using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using FluentAssertions;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
@@ -15,12 +13,12 @@ public class ReturnCommentConstructionTests : IClassFixture
{
private readonly ReturnCommentConstruction _returnCommentBuilder;
private readonly ReturnTypeBuilderOptions _options;
+ private readonly TestFixture _testFixture;
public ReturnCommentConstructionTests(TestFixture testFixture, ITestOutputHelper output)
{
- _returnCommentBuilder = new ReturnCommentConstruction();
testFixture.Initialize(output);
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
+ _returnCommentBuilder = new ReturnCommentConstruction();
_options = new ReturnTypeBuilderOptions
{
@@ -28,6 +26,7 @@ public ReturnCommentConstructionTests(TestFixture testFixture, ITestOutputHelper
TryToIncludeCrefsForReturnTypes = true,
IncludeStartingWordInText = true,
};
+ _testFixture = testFixture;
}
#region QualifiedNameSyntax
@@ -39,7 +38,7 @@ public void GenerateQualifiedNameComment_CreatesValidStringFromName(bool include
{
var roc = TestFixture.BuildQualifiedNameSyntax("System", "String");
_options.IncludeStartingWordInText = includeStartingWordInText;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be(startWord + "");
}
@@ -50,7 +49,7 @@ public void GenerateQualifiedNameComment_CreatesValidStringFromCustomInterface(b
{
var roc = TestFixture.BuildQualifiedNameSyntax("Angler", "IClass");
_options.IncludeStartingWordInText = includeStartingWordInText;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be(startWord + "");
}
#endregion
@@ -64,7 +63,7 @@ public void GenerateArrayTypeComment_CreatesValidStringFromNameAndForcesAnPrefix
{
var roc = TestFixture.BuildArrayTypeSyntax(SyntaxKind.StringKeyword);
_options.IncludeStartingWordInText = includeStartingWordInText;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("an array of strings");
}
#endregion
@@ -77,7 +76,7 @@ public void GeneratePredefinedTypeSyntaxCommentWithCref_CreatesValidStringFromSt
{
var roc = TestFixture.BuildPredefinedTypeSyntax(SyntaxKind.StringKeyword);
_options.IncludeStartingWordInText = includeStartingWordInText;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be(startWord + "");
}
@@ -88,7 +87,7 @@ public void GeneratePredefinedTypeSyntaxCommentWithCref_CreatesValidStringFromIn
{
var roc = TestFixture.BuildPredefinedTypeSyntax(SyntaxKind.IntKeyword);
_options.IncludeStartingWordInText = includeStartingWordInText;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be(startWord + "");
}
#endregion
@@ -100,7 +99,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIReadOnlyCollection
{
var roc = TestFixture.BuildGenericNameSyntax("IReadOnlyCollection", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A read only collection of strings.");
}
@@ -110,7 +109,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIReadOnlyCollection
var list = TestFixture.BuildGenericNameSyntax("List", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax("IReadOnlyCollection", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A read only collection of list of strings.");
}
@@ -121,7 +120,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIReadOnlyCollection
var roc = TestFixture.BuildGenericNameSyntax("IReadOnlyCollection", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A read only collection of a read only collection of strings.");
}
@@ -133,7 +132,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIReadOnlyCollection
public void GenerateGenericTypeComment_CreatesValidStringFromList()
{
var roc = TestFixture.BuildGenericNameSyntax("List", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of strings.");
}
@@ -143,7 +142,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromListOfList()
var list = TestFixture.BuildGenericNameSyntax("List", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax("List", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of a list of strings.");
}
@@ -155,7 +154,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromListOfListOfList()
var list2 = TestFixture.BuildGenericNameSyntax("List", list);
var roc = TestFixture.BuildGenericNameSyntax("List", list2);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of a list of a list of strings.");
}
@@ -163,7 +162,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromListOfListOfList()
public void GenerateGenericTypeComment_CreatesValidStringFromIList()
{
var roc = TestFixture.BuildGenericNameSyntax("IList", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of strings.");
}
@@ -172,7 +171,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIListOfIList()
{
var list = TestFixture.BuildGenericNameSyntax("IList", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax("IList", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of a list of strings.");
}
@@ -180,7 +179,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIListOfIList()
public void GenerateGenericTypeComment_CreatesValidStringFromListOfInt()
{
var roc = TestFixture.BuildGenericNameSyntax("List", SyntaxKind.IntKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of integers.");
}
@@ -189,7 +188,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromListOfListOfInt()
{
var list = TestFixture.BuildGenericNameSyntax("List", SyntaxKind.IntKeyword);
var roc = TestFixture.BuildGenericNameSyntax("IList", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of a list of integers.");
}
@@ -201,7 +200,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromListOfListOfInt()
public void GenerateGenericTypeComment_CreatesValidStringFromIEnumerable()
{
var roc = TestFixture.BuildGenericNameSyntax("IEnumerable", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of strings.");
}
@@ -210,7 +209,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIEnumerableOfIEnume
{
var list = TestFixture.BuildGenericNameSyntax("IEnumerable", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax("IEnumerable", list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A list of a list of strings.");
}
@@ -222,7 +221,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIEnumerableOfIEnume
public void GenerateGenericTypeComment_CreatesValidStringFromICollection()
{
var roc = TestFixture.BuildGenericNameSyntax("ICollection", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A collection of strings.");
}
@@ -230,7 +229,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromICollection()
public void GenerateGenericTypeComment_CreatesValidStringFromCollection()
{
var roc = TestFixture.BuildGenericNameSyntax("Collection", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A collection of strings.");
}
@@ -242,7 +241,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromCollection()
public void GenerateGenericTypeComment_CreatesValidStringFromIDictionary()
{
var roc = TestFixture.BuildGenericNameSyntax("IDictionary", SyntaxKind.StringKeyword, SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A dictionary with a key of type string and a value of type string.");
}
@@ -250,7 +249,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromIDictionary()
public void GenerateGenericTypeComment_CreatesValidStringFromIDictionaryOfInt()
{
var roc = TestFixture.BuildGenericNameSyntax("IDictionary", SyntaxKind.IntKeyword, SyntaxKind.IntKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A dictionary with a key of type integer and a value of type integer.");
}
@@ -259,7 +258,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromDictionary()
{
var roc = TestFixture.BuildGenericNameSyntax("Dictionary", SyntaxKind.StringKeyword, SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A dictionary with a key of type string and a value of type string.");
}
@@ -269,7 +268,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromDictionaryWithListV
var list = TestFixture.BuildGenericNameSyntax("IEnumerable", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax("Dictionary", SyntaxKind.StringKeyword, list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A dictionary with a key of type string and a value of type list of strings.");
}
@@ -280,7 +279,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromDictionaryWithListO
var list2 = TestFixture.BuildGenericNameSyntax("List", list);
var roc = TestFixture.BuildGenericNameSyntax("Dictionary", SyntaxKind.StringKeyword, list2);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("A dictionary with a key of type string and a value of type list of a list of strings.");
}
@@ -292,7 +291,7 @@ public void GenericTypeDefResult_CreatesValidStringFromString()
{
var method = TestFixture.BuildMethodDeclarationSyntax("TResult", "Tester");
_options.IncludeStartingWordInText = true;
- var comment = _returnCommentBuilder.BuildComment(method.ReturnType, _options);
+ var comment = _returnCommentBuilder.BuildComment(method.ReturnType, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("a ");
}
@@ -301,15 +300,15 @@ public void GenericTypeDefResult_CreatesValidStringFromString()
#region Task & ActionResult & ValueTask
[Theory]
- [InlineData("Task", "a")]
- [InlineData("ValueTask", "a")]
- [InlineData("ActionResult", "an")]
+ [InlineData("Task", "a")]
+ [InlineData("ValueTask", "a")]
+ [InlineData("ActionResult", "an")]
public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfString(string type, string prefix, bool hasPeriod = false)
{
var roc = TestFixture.BuildGenericNameSyntax(type, SyntaxKind.StringKeyword);
_options.TryToIncludeCrefsForReturnTypes = true;
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be($"{prefix} of type " + (hasPeriod ? "." : ""));
}
@@ -317,11 +316,11 @@ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfString(string
[InlineData("Task", "a")]
[InlineData("ValueTask", "a")]
[InlineData("ActionResult", "an")]
- public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfList(string type, string prefix, bool hasPeriod = false)
+ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfList(string type, string prefix, bool hasPeriod = false)
{
var list = TestFixture.BuildGenericNameSyntax("IList", SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax(type, list);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be($"{prefix} of a list of strings" + (hasPeriod ? "." : ""));
}
@@ -329,12 +328,12 @@ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfList(string t
[InlineData("Task", "a")]
[InlineData("ValueTask", "a")]
[InlineData("ActionResult", "an")]
- public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfDictionary(string type, string prefix, bool hasPeriod = false)
+ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfDictionary(string type, string prefix, bool hasPeriod = false)
{
var list = TestFixture.BuildGenericNameSyntax("IEnumerable", SyntaxKind.StringKeyword);
var dict = TestFixture.BuildGenericNameSyntax("Dictionary", SyntaxKind.StringKeyword, list);
var roc = TestFixture.BuildGenericNameSyntax(type, dict);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be($"{prefix} of a dictionary with a key of type string and a value of type list of strings" + (hasPeriod ? "." : ""));
}
@@ -346,7 +345,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfCustomDoubleG
{
var custom = TestFixture.BuildGenericNameSyntax("CustomDoubleGenericType", SyntaxKind.StringKeyword, SyntaxKind.StringKeyword);
var roc = TestFixture.BuildGenericNameSyntax(type, custom);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be($"{prefix} of type CustomDoubleGenericType" + (hasPeriod ? "." : ""));
}
@@ -357,7 +356,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfCustomDoubleG
public void GenerateGenericTypeComment_CreatesValidStringFromTaskOfCustomClass(string type, string prefix, bool hasPeriod = false)
{
var roc = SyntaxFactory.ParseTypeName($"{type}");
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be($"{prefix} of type " + (hasPeriod ? "." : ""));
}
@@ -377,7 +376,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromUnknown()
{
var roc = TestFixture.BuildGenericNameSyntax("Span", SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("Span");
}
@@ -386,7 +385,7 @@ public void GenerateGenericTypeComment_CreatesValidStringFromUnknownGeneric()
{
var roc = TestFixture.BuildGenericNameSyntax("CustomClass", SyntaxKind.StringKeyword, SyntaxKind.StringKeyword);
- var comment = _returnCommentBuilder.BuildComment(roc, _options);
+ var comment = _returnCommentBuilder.BuildComment(roc, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("CustomClass");
}
@@ -402,7 +401,7 @@ public void IdentifierNameSyntaxComment_CreatesValidTypeParamRef()
returnType.Should().NotBeNull();
- var comment = _returnCommentBuilder.BuildComment(returnType, _options);
+ var comment = _returnCommentBuilder.BuildComment(returnType, _options, _testFixture.MockSettings.WordMaps);
comment.Should().Be("a ");
}
diff --git a/CodeDocumentor.Test/Helper/TranslatorTests.cs b/CodeDocumentor.Test/Helper/TranslatorTests.cs
index 2eaa850..d629766 100644
--- a/CodeDocumentor.Test/Helper/TranslatorTests.cs
+++ b/CodeDocumentor.Test/Helper/TranslatorTests.cs
@@ -1,8 +1,8 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Models;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
@@ -43,16 +43,12 @@ public TranslatorTests(TestFixture fixture, ITestOutputHelper output)
[InlineData("To UpperCase", "Converts to UpperCase")]
public void TranslateText_ReturnsTranslatedStrings(string input, string output)
{
- _testFixure.RegisterCallback(_testFixure.CurrentTestName, (o) =>
- {
- var temp = o.WordMaps.ToList();
- temp.Add(new WordMap { Word = "You're", Translation = "You Are" });
- temp.Add(new WordMap { Word = "This is long", Translation = "How long is this" });
- temp.AddRange(Constants.INTERNAL_WORD_MAPS);
- o.WordMaps = temp.ToArray();
- });
- Translator.Initialize(CodeDocumentorPackage.DIContainer().GetInstance());
- var translated = input.ApplyUserTranslations();
+ var temp = _testFixure.MockSettings.WordMaps.ToList();
+ temp.Add(new WordMap { Word = "You're", Translation = "You Are" });
+ temp.Add(new WordMap { Word = "This is long", Translation = "How long is this" });
+ temp.AddRange(Constants.INTERNAL_WORD_MAPS);
+ _testFixure.MockSettings.WordMaps = temp.ToArray();
+ var translated = input.ApplyUserTranslations(_testFixure.MockSettings.WordMaps);
translated.Should().Be(output);
}
}
diff --git a/CodeDocumentor.Test/Helper/WordExtensionsTests.cs b/CodeDocumentor.Test/Helper/WordExtensionsTests.cs
index a2bbeaa..70a853d 100644
--- a/CodeDocumentor.Test/Helper/WordExtensionsTests.cs
+++ b/CodeDocumentor.Test/Helper/WordExtensionsTests.cs
@@ -1,4 +1,4 @@
-using CodeDocumentor.Helper;
+using System;
using FluentAssertions;
using Xunit;
diff --git a/CodeDocumentor.Test/Methods/MethodUnitTests.cs b/CodeDocumentor.Test/Methods/MethodUnitTests.cs
index 146bba3..1bd2d3a 100644
--- a/CodeDocumentor.Test/Methods/MethodUnitTests.cs
+++ b/CodeDocumentor.Test/Methods/MethodUnitTests.cs
@@ -48,6 +48,7 @@ public async Task NoDiagnosticsShow(string testCode)
[Theory]
[InlineData("BasicTestCode", "BasicTestFixCode", 9, 21)]
+ [InlineData("InterfacePrivateMethods", "InterfacePrivateMethodsFix", 9, 22)]
[InlineData("MethodWithParameterTestCode", "MethodWithParameterTestFixCode", 9, 21)]
[InlineData("MethodWithBooleanParameterTestCode", "MethodWithBooleanParameterTestFixCode", 9, 21)]
[InlineData("MethodWithNullableStructParameterTestCode", "MethodWithNullableStructParameterTestFixCode", 9, 21)]
@@ -67,11 +68,9 @@ public async Task ShowMethodDiagnosticAndFix(string testCode, string fixCode, in
{
var fix = _fixture.LoadTestFile($"./Methods/TestFiles/{fixCode}.cs");
var test = _fixture.LoadTestFile($"./Methods/TestFiles/{testCode}.cs");
-
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.UseNaturalLanguageForReturnNode = false;
- o.TryToIncludeCrefsForReturnTypes = false;
+ _fixture.MockSettings.SetClone(new TestSettings {
+ UseNaturalLanguageForReturnNode = false,
+ TryToIncludeCrefsForReturnTypes = false
});
var expected = new DiagnosticResult
{
@@ -89,8 +88,37 @@ public async Task ShowMethodDiagnosticAndFix(string testCode, string fixCode, in
await VerifyCSharpFixAsync(test, fix, TestFixture.DIAG_TYPE_PUBLIC_ONLY);
}
+ [Theory]
+ [InlineData("InterfacePrivateMethods", "InterfacePrivateMethodsFix", 9, 22)]
+ public async Task ShowMethodDiagnosticAndFixForPrivate(string testCode, string fixCode, int line, int column)
+ {
+ var fix = _fixture.LoadTestFile($"./Methods/TestFiles/{fixCode}.cs");
+ var test = _fixture.LoadTestFile($"./Methods/TestFiles/{testCode}.cs");
+ _fixture.MockSettings.SetClone(new TestSettings
+ {
+ UseNaturalLanguageForReturnNode = false,
+ TryToIncludeCrefsForReturnTypes = false
+ });
+ var expected = new DiagnosticResult
+ {
+ Id = MethodAnalyzerSettings.DiagnosticId,
+ Message = MethodAnalyzerSettings.MessageFormat,
+ Severity = DiagnosticSeverity.Warning,
+ Locations =
+ new[] {
+ new DiagnosticResultLocation("Test0.cs", line, column)
+ }
+ };
+
+ await VerifyCSharpDiagnosticAsync(test, TestFixture.DIAG_TYPE_PRIVATE, expected);
+
+ await VerifyCSharpFixAsync(test, fix, TestFixture.DIAG_TYPE_PRIVATE);
+ }
+
[Theory]
+ [InlineData("MethodWithNullableReturnTestCode", "MethodWithNullableReturnTestFixCode", 9, 30)]
+ [InlineData("MethodWithNullableStringReturnTestCode", "MethodWithNullableStringReturnTestFixCode", 9, 24)]
[InlineData("MethodWithStringReturnTestCode", "MethodWithStringReturnTestFixCode", 9, 23)]
[InlineData("MethodWithReturnTestCode", "MethodWithReturnTestFixCode", 9, 29)]
[InlineData("MethodWithObjectReturnTestCode", "MethodWithObjectReturnTestFixCode", 9, 23)]
@@ -105,11 +133,12 @@ public async Task ShowMethodDiagnosticAndFixWhenCrefsIsTrue(string testCode, str
var fix = _fixture.LoadTestFile($"./Methods/TestFiles/Crefs/{fixCode}.cs");
var test = _fixture.LoadTestFile($"./Methods/TestFiles/Crefs/{testCode}.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
+ _fixture.MockSettings.SetClone(new TestSettings
{
- o.UseNaturalLanguageForReturnNode = useNaturalLanguageForReturnNode;
- o.TryToIncludeCrefsForReturnTypes = true;
+ UseNaturalLanguageForReturnNode = useNaturalLanguageForReturnNode,
+ TryToIncludeCrefsForReturnTypes = true
});
+
var expected = new DiagnosticResult
{
Id = MethodAnalyzerSettings.DiagnosticId,
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestCode.cs
new file mode 100644
index 0000000..cd5a4c5
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestCode.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ public Dictionary? ShowMethodWithReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestFixCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestFixCode.cs
new file mode 100644
index 0000000..8bbf94f
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableDictionaryReturnTestFixCode.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ ///
+ /// Show method with return tester.
+ ///
+ /// ]]>
+ public Dictionary? ShowMethodWithReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestCode.cs
new file mode 100644
index 0000000..5e46490
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestCode.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ public MethodTester? ShowMethodWithReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestFixCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestFixCode.cs
new file mode 100644
index 0000000..af173fb
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableReturnTestFixCode.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ ///
+ /// Show method with return tester.
+ ///
+ /// A
+ public MethodTester? ShowMethodWithReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestCode.cs
new file mode 100644
index 0000000..be31c4e
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestCode.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ public string? ShowMethodWithStringReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestFixCode.cs b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestFixCode.cs
new file mode 100644
index 0000000..92ab2c6
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/Crefs/MethodWithNullableStringReturnTestFixCode.cs
@@ -0,0 +1,18 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp40
+{
+ public class MethodTester
+ {
+ ///
+ /// Show method with string return tester.
+ ///
+ /// A
+ public string? ShowMethodWithStringReturnTester()
+ {
+ return null;
+ }
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethods.cs b/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethods.cs
new file mode 100644
index 0000000..8dba277
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethods.cs
@@ -0,0 +1,11 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp4
+{
+ public interface IInterfaceTesterPrivateMethod
+ {
+ Task GetNamesAsync(string name);
+ }
+}
diff --git a/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethodsFix.cs b/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethodsFix.cs
new file mode 100644
index 0000000..a44fc63
--- /dev/null
+++ b/CodeDocumentor.Test/Methods/TestFiles/InterfacePrivateMethodsFix.cs
@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace ConsoleApp4
+{
+ public interface IInterfaceTesterPrivateMethod
+ {
+ ///
+ /// Get the names asynchronously.
+ ///
+ /// The name.
+ /// ]]>
+ Task GetNamesAsync(string name);
+ }
+}
diff --git a/CodeDocumentor.Test/Properties/PropertyUnitTests.cs b/CodeDocumentor.Test/Properties/PropertyUnitTests.cs
index 6fb2ed2..55d0d3b 100644
--- a/CodeDocumentor.Test/Properties/PropertyUnitTests.cs
+++ b/CodeDocumentor.Test/Properties/PropertyUnitTests.cs
@@ -65,10 +65,9 @@ public async Task ShowPropertyDiagnosticAndFix(string testCode, string fixCode,
{
var fix = _fixture.LoadTestFile($"./Properties/TestFiles/{fixCode}.cs");
var test = _fixture.LoadTestFile($"./Properties/TestFiles/{testCode}.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- _fixture.SetPublicProcessingOption(o, diagType);
- });
+ var clone = new TestSettings();
+ _fixture.SetPublicProcessingOption(clone, diagType);
+ _fixture.MockSettings.SetClone(clone);
var expected = new DiagnosticResult
{
Id = PropertyAnalyzerSettings.DiagnosticId,
@@ -93,12 +92,14 @@ public async Task ShowPropertyDiagnosticAndFixWithValueTypeEnabled(string testCo
{
var fix = _fixture.LoadTestFile($"./Properties/TestFiles/{fixCode}.cs");
var test = _fixture.LoadTestFile($"./Properties/TestFiles/{testCode}.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
+ var clone = new TestSettings
{
- _fixture.SetPublicProcessingOption(o, diagType);
- o.IncludeValueNodeInProperties = true;
- o.TryToIncludeCrefsForReturnTypes = tryToIncludeCrefsForReturnTypes;
- });
+ IncludeValueNodeInProperties = true,
+ TryToIncludeCrefsForReturnTypes = tryToIncludeCrefsForReturnTypes
+ };
+ _fixture.SetPublicProcessingOption(clone, diagType);
+ _fixture.MockSettings.SetClone(clone);
+
var expected = new DiagnosticResult
{
Id = PropertyAnalyzerSettings.DiagnosticId,
diff --git a/CodeDocumentor.Test/Records/RecordUnitTests.cs b/CodeDocumentor.Test/Records/RecordUnitTests.cs
index 889226b..dc3f9f2 100644
--- a/CodeDocumentor.Test/Records/RecordUnitTests.cs
+++ b/CodeDocumentor.Test/Records/RecordUnitTests.cs
@@ -68,10 +68,10 @@ public async Task ShowRecordDiagnosticAndFix(string testCode, string fixCode, in
{
var fix = _fixture.LoadTestFile($"./Records/TestFiles/{fixCode}");
var test = _fixture.LoadTestFile($"./Records/TestFiles/{testCode}");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- _fixture.SetPublicProcessingOption(o, diagType);
- });
+ var clone = new TestSettings();
+ _fixture.SetPublicProcessingOption(clone, diagType);
+ _fixture.MockSettings.SetClone(clone);
+
var expected = new DiagnosticResult
{
Id = RecordAnalyzerSettings.DiagnosticId,
@@ -93,10 +93,10 @@ public async Task SkipsRecordDiagnosticAndFixWhenPublicOnlyTrue()
{
var fix = _fixture.LoadTestFile("./Records/TestFiles/RecordTester.cs");
var test = _fixture.LoadTestFile("./Records/TestFiles/RecordTester.cs");
- _fixture.RegisterCallback(_fixture.CurrentTestName, (o) =>
- {
- o.IsEnabledForPublicMembersOnly = true;
- });
+ var clone = new TestSettings {
+ IsEnabledForPublicMembersOnly = true
+ };
+ _fixture.MockSettings.SetClone(clone);
await VerifyCSharpDiagnosticAsync(test, TestFixture.DIAG_TYPE_PUBLIC_ONLY);
diff --git a/CodeDocumentor.Test/TestFixture.cs b/CodeDocumentor.Test/TestFixture.cs
index a59f6ba..ef038ac 100644
--- a/CodeDocumentor.Test/TestFixture.cs
+++ b/CodeDocumentor.Test/TestFixture.cs
@@ -5,17 +5,14 @@
using System.IO;
using System.Linq;
using System.Reflection;
-using CodeDocumentor.Builders;
-using CodeDocumentor.Helper;
-using CodeDocumentor.Managers;
-using CodeDocumentor.Services;
+using CodeDocumentor.Analyzers;
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Common.Models;
using CodeDocumentor.Test.TestHelpers;
-using CodeDocumentor.Vsix2022;
using FluentAssertions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
-using SimpleInjector;
using Xunit;
using Xunit.Abstractions;
@@ -50,7 +47,8 @@ public class TestFixture
public string CurrentTestName { get; set; }
- protected static ConcurrentDictionary> RegisteredCallBacks = new ConcurrentDictionary>();
+ public TestSettings MockSettings;
+ protected static ConcurrentDictionary> RegisteredCallBacks = new ConcurrentDictionary>();
public TestFixture()
{
@@ -61,37 +59,12 @@ public void Initialize(ITestOutputHelper output)
{
CurrentTestName = output.GetTestName();
- CodeDocumentorPackage.ContainerFactory = () =>
- {
- var _testContainer = new Container();
- _testContainer.Register(() =>
- {
- var os = new TestOptionsService();
- if (CurrentTestName != null && RegisteredCallBacks.TryGetValue(CurrentTestName, out var callback))
- {
- callback.Invoke(os);
- }
- Translator.Initialize(os);
- return os;
- }, Lifestyle.Transient);
- _testContainer.Register();
- _testContainer.RegisterSingleton();
- _testContainer.Verify();
- return _testContainer;
- };
- }
-
- public void RegisterCallback(string name, Action callback)
- {
- if (RegisteredCallBacks.ContainsKey(name))
- {
- RegisteredCallBacks[name] = callback;
- return;
- }
- RegisteredCallBacks.TryAdd(name, callback);
+ MockSettings = new TestSettings();
+ BaseCodeFixProvider.SetSettings(MockSettings);
+ BaseDiagnosticAnalyzer.SetSettings(MockSettings);
}
- public void SetPublicProcessingOption(IOptionsService o, string diagType)
+ public void SetPublicProcessingOption(ISettings o, string diagType)
{
if (diagType == DIAG_TYPE_PRIVATE)
{
diff --git a/CodeDocumentor.Test/TestHelpers/TestOptionsService.cs b/CodeDocumentor.Test/TestHelpers/TestSettings.cs
similarity index 61%
rename from CodeDocumentor.Test/TestHelpers/TestOptionsService.cs
rename to CodeDocumentor.Test/TestHelpers/TestSettings.cs
index 3919e5a..120e3f1 100644
--- a/CodeDocumentor.Test/TestHelpers/TestOptionsService.cs
+++ b/CodeDocumentor.Test/TestHelpers/TestSettings.cs
@@ -1,14 +1,17 @@
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
-using System.Runtime;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Common.Models;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor.Test.TestHelpers
{
[SuppressMessage("XMLDocumentation", "")]
- public class TestOptionsService : IOptionsService
+ public class TestSettings : ISettings
{
+ private ISettings _clonedSettings;
+
public bool ExcludeAsyncSuffix { get; set; }
public bool IncludeValueNodeInProperties { get; set; }
@@ -35,8 +38,69 @@ public class TestOptionsService : IOptionsService
public DiagnosticSeverity? PropertyDiagnosticSeverity { get; set; }
public DiagnosticSeverity? RecordDiagnosticSeverity { get; set; }
public bool IsEnabledForNonPublicFields { get; set; }
+ public bool UseEditorConfigForSettings { get; set; }
+
+ public void SetClone(ISettings settings)
+ {
+ _clonedSettings = settings;
+ }
+
+ public ISettings Clone()
+ {
+ if (_clonedSettings != null)
+ {
+ return _clonedSettings;
+ }
+ var newSettings = new Settings
+ {
+ ClassDiagnosticSeverity = ClassDiagnosticSeverity,
+ ConstructorDiagnosticSeverity = ConstructorDiagnosticSeverity,
+ DefaultDiagnosticSeverity = DefaultDiagnosticSeverity,
+
+ EnumDiagnosticSeverity = EnumDiagnosticSeverity,
+
+ ExcludeAsyncSuffix = ExcludeAsyncSuffix,
+
+ FieldDiagnosticSeverity = FieldDiagnosticSeverity,
+
+ IncludeValueNodeInProperties = IncludeValueNodeInProperties,
+
+ InterfaceDiagnosticSeverity = InterfaceDiagnosticSeverity,
+
+ IsEnabledForNonPublicFields = IsEnabledForNonPublicFields,
+
+ IsEnabledForPublicMembersOnly = IsEnabledForPublicMembersOnly,
+
+ MethodDiagnosticSeverity = MethodDiagnosticSeverity,
+
+ PreserveExistingSummaryText = PreserveExistingSummaryText,
+
+ PropertyDiagnosticSeverity = PropertyDiagnosticSeverity,
+
+ RecordDiagnosticSeverity = RecordDiagnosticSeverity,
+
+ TryToIncludeCrefsForReturnTypes = TryToIncludeCrefsForReturnTypes,
+
+ UseNaturalLanguageForReturnNode = UseNaturalLanguageForReturnNode,
+
+ UseToDoCommentsOnSummaryError = UseNaturalLanguageForReturnNode
+ };
+ var clonedMaps = new List();
+ foreach (var item in WordMaps)
+ {
+ clonedMaps.Add(new WordMap
+ {
+ Translation = item.Translation,
+ Word = item.Word,
+ WordEvaluator = item.WordEvaluator
+ });
+ }
+ newSettings.WordMaps = clonedMaps.ToArray();
+ return newSettings;
+
+ }
- public void SetDefaults(IOptionPageGrid options)
+ public void SetDefaults(ISettings options)
{
IsEnabledForPublicMembersOnly = options.IsEnabledForPublicMembersOnly;
UseNaturalLanguageForReturnNode = options.UseNaturalLanguageForReturnNode;
@@ -56,7 +120,7 @@ public void SetDefaults(IOptionPageGrid options)
RecordDiagnosticSeverity = options.RecordDiagnosticSeverity;
}
- public void Update(Vsix2022.Settings settings)
+ public void Update(Settings settings)
{
IsEnabledForPublicMembersOnly = settings.IsEnabledForPublicMembersOnly;
UseNaturalLanguageForReturnNode = settings.UseNaturalLanguageForReturnNode;
diff --git a/CodeDocumentor.sln b/CodeDocumentor.sln
index 7c2c405..3460881 100644
--- a/CodeDocumentor.sln
+++ b/CodeDocumentor.sln
@@ -41,6 +41,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{
.github\workflows\dotnet.yml = .github\workflows\dotnet.yml
EndProjectSection
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeDocumentor.Common", "CodeDocumentor.Common\CodeDocumentor.Common.csproj", "{7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -75,6 +77,18 @@ Global
{0D6E3633-F45F-4883-AC62-DEC9F714AA9B}.Release|x64.Build.0 = Release|Any CPU
{0D6E3633-F45F-4883-AC62-DEC9F714AA9B}.Release|x86.ActiveCfg = Release|x86
{0D6E3633-F45F-4883-AC62-DEC9F714AA9B}.Release|x86.Build.0 = Release|x86
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|x64.Build.0 = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Debug|x86.Build.0 = Debug|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|Any CPU.Build.0 = Release|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|x64.ActiveCfg = Release|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|x64.Build.0 = Release|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|x86.ActiveCfg = Release|Any CPU
+ {7CC64CDF-A7FF-463B-8F05-C37A6C0A820C}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/CodeDocumentor/Analyzers/BaseAnalyzerSettings.cs b/CodeDocumentor/Analyzers/BaseAnalyzerSettings.cs
index 3e060cb..e71ad46 100644
--- a/CodeDocumentor/Analyzers/BaseAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/BaseAnalyzerSettings.cs
@@ -1,6 +1,6 @@
-using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor.Analyzers
@@ -12,33 +12,37 @@ internal class BaseAnalyzerSettings
///
internal const string Category = Constants.CATEGORY;
+ protected IEventLogger EventLogger = ServiceLocator.Logger;
- internal static DiagnosticSeverity LookupSeverity(string diagnosticId)
+ internal DiagnosticSeverity LookupSeverity(string diagnosticId, ISettings settings)
{
+ if (settings == null)
+ {
+ return Constants.DefaultDiagnosticSeverityOnError;
+ }
return TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
switch (diagnosticId)
{
case Constants.DiagnosticIds.CLASS_DIAGNOSTIC_ID:
- return optionsService.ClassDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.ClassDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.CONSTRUCTOR_DIAGNOSTIC_ID:
- return optionsService.ConstructorDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.ConstructorDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.INTERFACE_DIAGNOSTIC_ID:
- return optionsService.InterfaceDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.InterfaceDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.ENUM_DIAGNOSTIC_ID:
- return optionsService.EnumDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.EnumDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.FIELD_DIAGNOSTIC_ID:
- return optionsService.FieldDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.FieldDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.METHOD_DIAGNOSTIC_ID:
- return optionsService.MethodDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.MethodDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.PROPERTY_DIAGNOSTIC_ID:
- return optionsService.PropertyDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.PropertyDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
case Constants.DiagnosticIds.RECORD_DIAGNOSTIC_ID:
- return optionsService.RecordDiagnosticSeverity ?? optionsService.DefaultDiagnosticSeverity;
+ return settings.RecordDiagnosticSeverity ?? settings.DefaultDiagnosticSeverity;
}
return Constants.DefaultDiagnosticSeverityOnError;
- }, (_) => Constants.DefaultDiagnosticSeverityOnError, eventId: Constants.EventIds.ANALYZER);
+ }, diagnosticId, EventLogger, (_) => Constants.DefaultDiagnosticSeverityOnError, eventId: Constants.EventIds.ANALYZER);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Files/BaseCodeFixProvider.cs b/CodeDocumentor/Analyzers/BaseCodeFixProvider.cs
similarity index 68%
rename from CodeDocumentor/Analyzers/Files/BaseCodeFixProvider.cs
rename to CodeDocumentor/Analyzers/BaseCodeFixProvider.cs
index cc92d49..e9071a8 100644
--- a/CodeDocumentor/Analyzers/Files/BaseCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/BaseCodeFixProvider.cs
@@ -1,9 +1,12 @@
using System.Collections.Generic;
using System.Collections.Immutable;
-using System.Diagnostics;
+#if DEBUG
+#endif
using System.Threading.Tasks;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -11,8 +14,25 @@
namespace CodeDocumentor
{
+
public abstract class BaseCodeFixProvider : CodeFixProvider
{
+ protected DocumentationHeaderHelper DocumentationHeaderHelper = ServiceLocator.DocumentationHeaderHelper;
+
+ protected static IEventLogger EventLogger = ServiceLocator.Logger;
+
+ //expose this for some of the static helpers for producing ALl File comments
+ private static ISettings _settings;
+
+ public static void SetSettings(ISettings settings)
+ {
+ _settings = settings;
+ }
+
+ protected static ISettings StaticSettings =>
+ //we serve up a fresh new instance from the static, and use that instead, keeps everything testable and decoupled from the static
+ _settings?.Clone();
+
///
/// The title.
///
@@ -44,10 +64,10 @@ public override FixAllProvider GetFixAllProvider()
/// A Task.
protected async Task RegisterFileCodeFixesAsync(CodeFixContext context, Diagnostic diagnostic)
{
- //#if DEBUG
- // Debug.WriteLine("!!!DISABLING FILE CODE FIX. EITHER TESTS ARE RUNNING OR DEBUGGER IS ATTACHED!!!");
- // return;
- //#endif
+#if DEBUG
+ //Debug.WriteLine("!!!DISABLING FILE CODE FIX. EITHER TESTS ARE RUNNING OR DEBUGGER IS ATTACHED!!!");
+ //return;
+#endif
//build it up, but check for counts if anything actually needs to be shown
var tempDoc = context.Document;
var root = await tempDoc.GetSyntaxRootAsync(context.CancellationToken);
@@ -55,22 +75,23 @@ protected async Task RegisterFileCodeFixesAsync(CodeFixContext context, Diagnost
{
return;
}
+ var settings = await context.BuildSettingsAsync(StaticSettings);
TryHelper.Try(() =>
{
var _nodesTempToReplace = new Dictionary();
//Order Matters
var neededCommentCount = 0;
- neededCommentCount += PropertyCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += ConstructorCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += EnumCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += FieldCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += MethodCodeFixProvider.BuildComments(root, _nodesTempToReplace);
+ neededCommentCount += PropertyCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += ConstructorCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += EnumCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += FieldCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += MethodCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
root = root.ReplaceNodes(_nodesTempToReplace.Keys, (n1, n2) => _nodesTempToReplace[n1]);
_nodesTempToReplace.Clear();
- neededCommentCount += InterfaceCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += ClassCodeFixProvider.BuildComments(root, _nodesTempToReplace);
- neededCommentCount += RecordCodeFixProvider.BuildComments(root, _nodesTempToReplace);
+ neededCommentCount += InterfaceCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += ClassCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
+ neededCommentCount += RecordCodeFixProvider.BuildComments(settings, root, _nodesTempToReplace);
var newRoot = root.ReplaceNodes(_nodesTempToReplace.Keys, (n1, n2) => _nodesTempToReplace[n1]);
if (neededCommentCount == 0)
{
@@ -83,7 +104,7 @@ protected async Task RegisterFileCodeFixesAsync(CodeFixContext context, Diagnost
createChangedDocument: (c) => Task.Run(() => context.Document.WithSyntaxRoot(newRoot), c),
equivalenceKey: FILE_FIX_TITLE),
diagnostic);
- }, eventId: Constants.EventIds.FILE_FIXER, category: Constants.EventIds.Categories.BUILD_COMMENTS);
+ }, diagnostic.Id, EventLogger, eventId: Constants.EventIds.FILE_FIXER, category: Constants.EventIds.Categories.BUILD_COMMENTS);
}
}
}
diff --git a/CodeDocumentor/Analyzers/BaseDiagnosticAnalyzer.cs b/CodeDocumentor/Analyzers/BaseDiagnosticAnalyzer.cs
new file mode 100644
index 0000000..df7df27
--- /dev/null
+++ b/CodeDocumentor/Analyzers/BaseDiagnosticAnalyzer.cs
@@ -0,0 +1,23 @@
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Helper;
+using CodeDocumentor.Locators;
+using Microsoft.CodeAnalysis.Diagnostics;
+
+namespace CodeDocumentor
+{
+ public abstract class BaseDiagnosticAnalyzer : DiagnosticAnalyzer
+ {
+ protected DocumentationHeaderHelper DocumentationHeaderHelper = ServiceLocator.DocumentationHeaderHelper;
+
+ private static ISettings _settings;
+
+ public static void SetSettings(ISettings settings)
+ {
+ _settings = settings;
+ }
+
+ protected static ISettings StaticSettings =>
+ //we serve up a fresh new instance from the static, and use that instead, keeps everything testable and decoupled from the static
+ _settings?.Clone();
+ }
+}
diff --git a/CodeDocumentor/Analyzers/Classes/ClassAnalyzer.cs b/CodeDocumentor/Analyzers/Classes/ClassAnalyzer.cs
index 5d560c8..d6ee047 100644
--- a/CodeDocumentor/Analyzers/Classes/ClassAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Classes/ClassAnalyzer.cs
@@ -12,8 +12,15 @@ namespace CodeDocumentor
/// The class analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class ClassAnalyzer : DiagnosticAnalyzer
+ public class ClassAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly ClassAnalyzerSettings _analyzerSettings;
+
+ public ClassAnalyzer()
+ {
+ _analyzerSettings = new ClassAnalyzerSettings();
+ }
+
///
/// Gets the supported diagnostics.
///
@@ -21,7 +28,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(ClassAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -40,7 +47,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ public void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is ClassDeclarationSyntax node))
{
@@ -55,8 +62,9 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
+ var settings = context.BuildSettings(StaticSettings);
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => ClassAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment, settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Classes/ClassAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Classes/ClassAnalyzerSettings.cs
index c5099a7..26cf225 100644
--- a/CodeDocumentor/Analyzers/Classes/ClassAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Classes/ClassAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,11 +22,19 @@ internal class ClassAnalyzerSettings: BaseAnalyzerSettings
///
internal const string Title = "The class must have a documentation header.";
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
{
- return new DiagnosticDescriptor(ClassAnalyzerSettings.DiagnosticId, ClassAnalyzerSettings.Title,
- ClassAnalyzerSettings.MessageFormat, ClassAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Classes/ClassCodeFixProvider.cs b/CodeDocumentor/Analyzers/Classes/ClassCodeFixProvider.cs
index fd756be..68f8c30 100644
--- a/CodeDocumentor/Analyzers/Classes/ClassCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Classes/ClassCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -48,18 +48,17 @@ public sealed override FixAllProvider GetFixAllProvider()
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
-
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
-
var declaration = root?.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType().FirstOrDefault();
if (declaration == null)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
{
return;
}
@@ -67,7 +66,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -82,14 +81,14 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- internal static Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, ClassDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ internal Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, ClassDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, ClassAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
///
@@ -97,16 +96,15 @@ internal static Task AddDocumentationHeaderAsync(Document document, Sy
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.ClassDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly
+ if (settings.IsEnabledForPublicMembersOnly
&& PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
{
continue;
@@ -115,22 +113,22 @@ internal static int BuildComments(SyntaxNode root, Dictionary();
- var comment = CommentHelper.CreateClassComment(declarationSyntax.Identifier.ValueText);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
- var list = builder.WithSummary(declarationSyntax, comment, optionsService.PreserveExistingSummaryText)
+ var commentHelper = ServiceLocator.CommentHelper;
+ var comment = commentHelper.CreateClassComment(declarationSyntax.Identifier.ValueText, settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
+ var list = builder.WithSummary(declarationSyntax, comment, settings.PreserveExistingSummaryText)
.WithTypeParamters(declarationSyntax)
- .WithParameters(declarationSyntax)
+ .WithParameters(declarationSyntax, settings.WordMaps)
.WithExisting(declarationSyntax, Constants.REMARKS)
.WithExisting(declarationSyntax, Constants.EXAMPLE)
.Build();
diff --git a/CodeDocumentor/Analyzers/Classes/NonPublicClassAnalyzer.cs b/CodeDocumentor/Analyzers/Classes/NonPublicClassAnalyzer.cs
index 2a6cf03..93d301d 100644
--- a/CodeDocumentor/Analyzers/Classes/NonPublicClassAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Classes/NonPublicClassAnalyzer.cs
@@ -1,9 +1,6 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -15,8 +12,14 @@ namespace CodeDocumentor
/// The class analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicClassAnalyzer : DiagnosticAnalyzer
+ public class NonPublicClassAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly ClassAnalyzerSettings _analyzerSettings;
+
+ public NonPublicClassAnalyzer()
+ {
+ _analyzerSettings = new ClassAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -24,10 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(ClassAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -46,26 +46,25 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var node = context.Node as ClassDeclarationSyntax;
if (!PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
+ var settings = context.BuildSettings(StaticSettings);
- if (optionsService.IsEnabledForPublicMembersOnly)
+ if (settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => ClassAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment || settings.IsEnabledForPublicMembersOnly, settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzer.cs b/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzer.cs
index 23da02a..17b4853 100644
--- a/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzer.cs
@@ -1,8 +1,6 @@
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -14,8 +12,14 @@ namespace CodeDocumentor
/// The constructor analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class ConstructorAnalyzer : DiagnosticAnalyzer
+ public class ConstructorAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly ConstructorAnalyzerSettings _analyzerSettings;
+
+ public ConstructorAnalyzer()
+ {
+ _analyzerSettings = new ConstructorAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -23,7 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(ConstructorAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -42,7 +46,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is ConstructorDeclarationSyntax node))
{
@@ -52,19 +56,17 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(node))
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
-
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => ConstructorAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment, settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzerSettings.cs
index 91cf70e..d7704f8 100644
--- a/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Constructors/ConstructorAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -20,12 +21,21 @@ internal class ConstructorAnalyzerSettings: BaseAnalyzerSettings
/// The title.
///
internal const string Title = "The constructor must have a documentation header.";
+
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(ConstructorAnalyzerSettings.DiagnosticId, ConstructorAnalyzerSettings.Title,
- ConstructorAnalyzerSettings.MessageFormat, ConstructorAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Constructors/ConstructorCodeFixProvider.cs b/CodeDocumentor/Analyzers/Constructors/ConstructorCodeFixProvider.cs
index 110d1fc..469679d 100644
--- a/CodeDocumentor/Analyzers/Constructors/ConstructorCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Constructors/ConstructorCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,8 +57,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
{
return;
}
@@ -66,7 +66,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -79,16 +79,15 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
/// The root.
/// The nodes to replace.
/// An int.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.ConstructorDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
{
continue;
}
@@ -96,18 +95,18 @@ internal static int BuildComments(SyntaxNode root, Dictionary
/// The declaration syntax.
/// A DocumentationCommentTriviaSyntax.
- private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTriviaSyntax(ConstructorDeclarationSyntax declarationSyntax)
+ private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTriviaSyntax(ISettings settings, ConstructorDeclarationSyntax declarationSyntax)
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- var comment = CommentHelper.CreateConstructorComment(declarationSyntax.Identifier.ValueText, declarationSyntax.IsPrivate());
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
- var list = builder.WithSummary(declarationSyntax, comment, optionsService.PreserveExistingSummaryText)
- .WithParameters(declarationSyntax)
+ var commentHelper = ServiceLocator.CommentHelper;
+ var comment = commentHelper.CreateConstructorComment(declarationSyntax.Identifier.ValueText, declarationSyntax.IsPrivate(), settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
+ var list = builder.WithSummary(declarationSyntax, comment, settings.PreserveExistingSummaryText)
+ .WithParameters(declarationSyntax, settings.WordMaps)
.WithExisting(declarationSyntax, Constants.REMARKS)
.WithExisting(declarationSyntax, Constants.EXAMPLE)
.Build();
@@ -139,14 +138,14 @@ private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTrivia
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, ConstructorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, ConstructorDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, ConstructorAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Constructors/NonPublicConstructorAnalyzer.cs b/CodeDocumentor/Analyzers/Constructors/NonPublicConstructorAnalyzer.cs
index c0fb4ad..1236ad7 100644
--- a/CodeDocumentor/Analyzers/Constructors/NonPublicConstructorAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Constructors/NonPublicConstructorAnalyzer.cs
@@ -1,9 +1,6 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -12,8 +9,14 @@
namespace CodeDocumentor
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicConstructorAnalyzer : DiagnosticAnalyzer
+ public class NonPublicConstructorAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly ConstructorAnalyzerSettings _analyzerSettings;
+
+ public NonPublicConstructorAnalyzer()
+ {
+ _analyzerSettings = new ConstructorAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -21,10 +24,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(ConstructorAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -43,25 +43,24 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var node = context.Node as ConstructorDeclarationSyntax;
if (!PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly)
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => ConstructorAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment, settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Enums/EnumAnalyzer.cs b/CodeDocumentor/Analyzers/Enums/EnumAnalyzer.cs
index ccee19e..4a11fde 100644
--- a/CodeDocumentor/Analyzers/Enums/EnumAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Enums/EnumAnalyzer.cs
@@ -12,12 +12,18 @@ namespace CodeDocumentor
/// The enum analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class EnumAnalyzer : DiagnosticAnalyzer
+ public class EnumAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly EnumAnalyzerSettings _analyzerSettings;
+
+ public EnumAnalyzer()
+ {
+ _analyzerSettings = new EnumAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(EnumAnalyzerSettings.GetRule());
+ public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
///
/// Initializes action.
@@ -34,20 +40,19 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is EnumDeclarationSyntax node))
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
-
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => EnumAnalyzerSettings.GetRule(alreadyHasComment));
+ var settings = context.BuildSettings(StaticSettings);
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment, settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Enums/EnumAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Enums/EnumAnalyzerSettings.cs
index 2a70561..ef5a325 100644
--- a/CodeDocumentor/Analyzers/Enums/EnumAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Enums/EnumAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,14 +22,22 @@ internal class EnumAnalyzerSettings : BaseAnalyzerSettings
///
internal const string Title = "The enum must have a documentation header.";
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
///
/// The diagnostic descriptor rule.
///
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(EnumAnalyzerSettings.DiagnosticId, EnumAnalyzerSettings.Title,
- EnumAnalyzerSettings.MessageFormat, EnumAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Enums/EnumCodeFixProvider.cs b/CodeDocumentor/Analyzers/Enums/EnumCodeFixProvider.cs
index a369a0b..49b7b5c 100644
--- a/CodeDocumentor/Analyzers/Enums/EnumCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Enums/EnumCodeFixProvider.cs
@@ -4,9 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -56,11 +57,12 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
+ var settings = await context.BuildSettingsAsync(StaticSettings);
var displayTitle = declaration.HasSummary() ? TitleRebuild : Title;
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -72,7 +74,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.EnumDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
@@ -84,21 +86,21 @@ internal static int BuildComments(SyntaxNode root, Dictionary();
+ var builder = ServiceLocator.DocumentationBuilder;
var summaryNodes = builder.WithSummary(comment).Build();
var commentTrivia = SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, summaryNodes);
@@ -114,14 +116,14 @@ private static EnumDeclarationSyntax BuildNewDeclaration(EnumDeclarationSyntax d
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, EnumDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, EnumDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, EnumAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Fields/FieldAnalyzer.cs b/CodeDocumentor/Analyzers/Fields/FieldAnalyzer.cs
index 87eb1b7..0b24e4c 100644
--- a/CodeDocumentor/Analyzers/Fields/FieldAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Fields/FieldAnalyzer.cs
@@ -2,8 +2,6 @@
using System.Linq;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -15,8 +13,14 @@ namespace CodeDocumentor
/// The field analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class FieldAnalyzer : DiagnosticAnalyzer
+ public class FieldAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly FieldAnalyzerSettings _analyzerSettings;
+
+ public FieldAnalyzer()
+ {
+ _analyzerSettings = new FieldAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -24,7 +28,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(FieldAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -43,14 +47,14 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is FieldDeclarationSyntax node))
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (!optionsService.IsEnabledForNonPublicFields && PrivateMemberVerifier.IsPrivateMember(node))
+ var settings = context.BuildSettings(StaticSettings);
+ if (!settings.IsEnabledForNonPublicFields && PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
@@ -60,7 +64,6 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
@@ -68,7 +71,7 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
}
var field = node.DescendantNodes().OfType().First();
- context.BuildDiagnostic(node, field.Identifier, (alreadyHasComment) => FieldAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, field.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Fields/FieldAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Fields/FieldAnalyzerSettings.cs
index 68f1f3f..a0d21c9 100644
--- a/CodeDocumentor/Analyzers/Fields/FieldAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Fields/FieldAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,14 +22,22 @@ internal class FieldAnalyzerSettings:BaseAnalyzerSettings
///
internal const string Title = "The field must have a documentation header.";
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
///
/// The diagnostic descriptor rule.
///
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(FieldAnalyzerSettings.DiagnosticId, FieldAnalyzerSettings.Title, FieldAnalyzerSettings.MessageFormat,
- FieldAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat,
+ Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Fields/FieldCodeFixProvider.cs b/CodeDocumentor/Analyzers/Fields/FieldCodeFixProvider.cs
index c80d82f..6ac9174 100644
--- a/CodeDocumentor/Analyzers/Fields/FieldCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Fields/FieldCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,8 +57,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
{
return;
}
@@ -66,7 +66,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -78,16 +78,15 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.FieldDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
{
continue;
}
@@ -95,22 +94,22 @@ internal static int BuildComments(SyntaxNode root, Dictionary().FirstOrDefault();
- var comment = CommentHelper.CreateFieldComment(field?.Identifier.ValueText);
+ var commentHelper = ServiceLocator.CommentHelper;
+ var comment = commentHelper.CreateFieldComment(field?.Identifier.ValueText, settings.ExcludeAsyncSuffix, settings.WordMaps);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
+ var builder = ServiceLocator.DocumentationBuilder;
var summaryNodes = builder.WithSummary(comment).Build();
var commentTrivia = SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, summaryNodes);
@@ -126,14 +125,14 @@ private static FieldDeclarationSyntax BuildNewDeclaration(FieldDeclarationSyntax
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, FieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, FieldDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, FieldAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Fields/NonPublicFieldAnalyzer.cs b/CodeDocumentor/Analyzers/Fields/NonPublicFieldAnalyzer.cs
index c59a354..2bedf19 100644
--- a/CodeDocumentor/Analyzers/Fields/NonPublicFieldAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Fields/NonPublicFieldAnalyzer.cs
@@ -1,10 +1,7 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -13,8 +10,14 @@
namespace CodeDocumentor
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicFieldAnalyzer : DiagnosticAnalyzer
+ public class NonPublicFieldAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly FieldAnalyzerSettings _analyzerSettings;
+
+ public NonPublicFieldAnalyzer()
+ {
+ _analyzerSettings = new FieldAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -22,10 +25,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(FieldAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -44,7 +44,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var node = context.Node as FieldDeclarationSyntax;
@@ -57,12 +57,11 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly)
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
@@ -70,7 +69,7 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
}
var field = node.DescendantNodes().OfType().First();
- context.BuildDiagnostic(node, field.Identifier, (alreadyHasComment) => FieldAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, field.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzer.cs b/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzer.cs
index ec38241..a9a6768 100644
--- a/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzer.cs
@@ -1,8 +1,6 @@
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -14,12 +12,18 @@ namespace CodeDocumentor
/// The interface analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class InterfaceAnalyzer : DiagnosticAnalyzer
+ public class InterfaceAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly InterfaceAnalyzerSettings _analyzerSettings;
+
+ public InterfaceAnalyzer()
+ {
+ _analyzerSettings = new InterfaceAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
- public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(InterfaceAnalyzerSettings.GetRule());
+ public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
///
/// Initializes action.
@@ -36,24 +40,23 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is InterfaceDeclarationSyntax node))
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(node))
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => InterfaceAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzerSettings.cs
index 18d5168..dc4e98d 100644
--- a/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Interfaces/InterfaceAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -22,14 +23,22 @@ internal class InterfaceAnalyzerSettings:BaseAnalyzerSettings
///
internal const string Title = "The interface must have a documentation header.";
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
///
/// The diagnostic descriptor rule.
///
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(InterfaceAnalyzerSettings.DiagnosticId, InterfaceAnalyzerSettings.Title,
- InterfaceAnalyzerSettings.MessageFormat, InterfaceAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Interfaces/InterfaceCodeFixProvider.cs b/CodeDocumentor/Analyzers/Interfaces/InterfaceCodeFixProvider.cs
index 827e1e9..58d1455 100644
--- a/CodeDocumentor/Analyzers/Interfaces/InterfaceCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Interfaces/InterfaceCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,11 +57,12 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
+ var settings =await context.BuildSettingsAsync(StaticSettings);
var displayTitle = declaration.HasSummary() ? TitleRebuild : Title;
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -73,7 +74,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.InterfaceDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
@@ -85,20 +86,20 @@ internal static int BuildComments(SyntaxNode root, Dictionary();
- var comment = CommentHelper.CreateInterfaceComment(declarationSyntax.Identifier.ValueText);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
- var list = builder.WithSummary(declarationSyntax, comment, optionsService.PreserveExistingSummaryText)
+ var commentHelper = ServiceLocator.CommentHelper;
+ var comment = commentHelper.CreateInterfaceComment(declarationSyntax.Identifier.ValueText, settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
+ var list = builder.WithSummary(declarationSyntax, comment, settings.PreserveExistingSummaryText)
.WithTypeParamters(declarationSyntax)
.Build();
@@ -117,14 +118,14 @@ private static InterfaceDeclarationSyntax BuildNewDeclaration(InterfaceDeclarati
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, InterfaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, InterfaceDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, InterfaceAnalyzerSettings.DiagnosticId , EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Methods/MethodAnalyzer.cs b/CodeDocumentor/Analyzers/Methods/MethodAnalyzer.cs
index 67c3b19..5fcdf17 100644
--- a/CodeDocumentor/Analyzers/Methods/MethodAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Methods/MethodAnalyzer.cs
@@ -12,8 +12,14 @@ namespace CodeDocumentor
/// The method analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class MethodAnalyzer : DiagnosticAnalyzer
+ public class MethodAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly MethodAnalyzerSettings _analyzerSettings;
+
+ public MethodAnalyzer()
+ {
+ _analyzerSettings = new MethodAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -21,7 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(MethodAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -40,24 +46,27 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is MethodDeclarationSyntax node))
{
return;
}
- if (PrivateMemberVerifier.IsPrivateMember(node))
+
+ //NOTE: Since interfaces declarations do not have accessors, we allow documenting all the time.
+ var isPrivate = PrivateMemberVerifier.IsPrivateMember(node);
+ var isOwnedByInterface = node.IsOwnedByInterface();
+ if (isPrivate && !isOwnedByInterface)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
-
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => MethodAnalyzerSettings.GetRule(alreadyHasComment));
+ var settings = context.BuildSettings(StaticSettings);
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Methods/MethodAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Methods/MethodAnalyzerSettings.cs
index 0d2eecd..92ef6fd 100644
--- a/CodeDocumentor/Analyzers/Methods/MethodAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Methods/MethodAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,14 +22,22 @@ internal class MethodAnalyzerSettings : BaseAnalyzerSettings
///
internal const string Title = "The method must have a documentation header.";
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
///
/// The diagnostic descriptor rule.
///
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(MethodAnalyzerSettings.DiagnosticId, MethodAnalyzerSettings.Title,
- MethodAnalyzerSettings.MessageFormat, MethodAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Methods/MethodCodeFixProvider.cs b/CodeDocumentor/Analyzers/Methods/MethodCodeFixProvider.cs
index 516e6ea..a01cde0 100644
--- a/CodeDocumentor/Analyzers/Methods/MethodCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Methods/MethodCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,8 +57,13 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+ if (
+ //NOTE: Since interfaces declarations do not have accessors, we allow documenting all the time.
+ !declaration.IsOwnedByInterface() &&
+ settings.IsEnabledForPublicMembersOnly &&
+ PrivateMemberVerifier.IsPrivateMember(declaration)
+ )
{
return;
}
@@ -66,7 +71,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -78,36 +83,38 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.MethodDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
+ if (
+ !declarationSyntax.IsOwnedByInterface() &&
+ settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax)
+ )
{
continue;
}
- //if method is already commented dont redo it, user should update methods indivually
+ //if method is already commented dont redo it, user should update methods individually
if (declarationSyntax.HasSummary())
{
continue;
}
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
nodesToReplace.TryAdd(declarationSyntax, newDeclaration);
neededCommentCount++;
}
- }, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.BUILD_COMMENTS);
+ }, MethodAnalyzerSettings.DiagnosticId, EventLogger, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.BUILD_COMMENTS);
return neededCommentCount;
}
- private static MethodDeclarationSyntax BuildNewDeclaration(MethodDeclarationSyntax declarationSyntax)
+ private static MethodDeclarationSyntax BuildNewDeclaration(ISettings settings, MethodDeclarationSyntax declarationSyntax)
{
var leadingTrivia = declarationSyntax.GetLeadingTrivia();
- var commentTrivia = CreateDocumentationCommentTriviaSyntax(declarationSyntax);
+ var commentTrivia = CreateDocumentationCommentTriviaSyntax(settings, declarationSyntax);
return declarationSyntax.WithLeadingTrivia(leadingTrivia.UpsertLeadingTrivia(commentTrivia));
}
@@ -116,19 +123,24 @@ private static MethodDeclarationSyntax BuildNewDeclaration(MethodDeclarationSynt
///
/// The declaration syntax.
/// A DocumentationCommentTriviaSyntax.
- private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTriviaSyntax(MethodDeclarationSyntax declarationSyntax)
+ private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTriviaSyntax(ISettings settings, MethodDeclarationSyntax declarationSyntax)
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- var summaryText = CommentHelper.CreateMethodComment(declarationSyntax.Identifier.ValueText, declarationSyntax.ReturnType);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
+ var commentHelper = ServiceLocator.CommentHelper;
+ var summaryText = commentHelper.CreateMethodComment(declarationSyntax.Identifier.ValueText,
+ declarationSyntax.ReturnType,
+ settings.UseToDoCommentsOnSummaryError,
+ settings.TryToIncludeCrefsForReturnTypes,
+ settings.ExcludeAsyncSuffix,
+ settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
- var list = builder.WithSummary(declarationSyntax, summaryText, optionsService.PreserveExistingSummaryText)
+ var list = builder.WithSummary(declarationSyntax, summaryText, settings.PreserveExistingSummaryText)
.WithTypeParamters(declarationSyntax)
- .WithParameters(declarationSyntax)
+ .WithParameters(declarationSyntax, settings.WordMaps)
.WithExceptionTypes(declarationSyntax)
.WithExisting(declarationSyntax, Constants.REMARKS)
.WithExisting(declarationSyntax, Constants.EXAMPLE)
- .WithReturnType(declarationSyntax)
+ .WithReturnType(declarationSyntax, settings.UseNaturalLanguageForReturnNode, settings.TryToIncludeCrefsForReturnTypes, settings.WordMaps)
.Build();
return SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, list);
@@ -142,14 +154,14 @@ private static DocumentationCommentTriviaSyntax CreateDocumentationCommentTrivia
/// The declaration syntax.
/// The cancellation token.
/// A Task.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, MethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, MethodDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, MethodAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Methods/NonPublicMethodAnalyzer.cs b/CodeDocumentor/Analyzers/Methods/NonPublicMethodAnalyzer.cs
index 014c6fa..f864a0d 100644
--- a/CodeDocumentor/Analyzers/Methods/NonPublicMethodAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Methods/NonPublicMethodAnalyzer.cs
@@ -1,9 +1,6 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -12,8 +9,14 @@
namespace CodeDocumentor
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicMethodAnalyzer : DiagnosticAnalyzer
+ public class NonPublicMethodAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly MethodAnalyzerSettings _analyzerSettings;
+
+ public NonPublicMethodAnalyzer()
+ {
+ _analyzerSettings = new MethodAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -21,10 +24,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(MethodAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -43,7 +43,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var node = context.Node as MethodDeclarationSyntax;
@@ -51,18 +51,18 @@ private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly)
+ var settings = context.BuildSettings(StaticSettings);
+ //NOTE: Since interfaces declarations do not have accessors, we allow documenting all the time.
+ if (!node.IsOwnedByInterface() && settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => MethodAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Properties/NonPublicPropertyAnalyzer.cs b/CodeDocumentor/Analyzers/Properties/NonPublicPropertyAnalyzer.cs
index 1991ab6..1609966 100644
--- a/CodeDocumentor/Analyzers/Properties/NonPublicPropertyAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Properties/NonPublicPropertyAnalyzer.cs
@@ -1,9 +1,6 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -15,8 +12,14 @@ namespace CodeDocumentor
/// The property analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicPropertyAnalyzer : DiagnosticAnalyzer
+ public class NonPublicPropertyAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly PropertyAnalyzerSettings _analyzerSettings;
+
+ public NonPublicPropertyAnalyzer()
+ {
+ _analyzerSettings = new PropertyAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -24,10 +27,8 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(PropertyAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
+
}
}
@@ -46,7 +47,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is PropertyDeclarationSyntax node))
{
@@ -56,19 +57,18 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly)
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => PropertyAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Properties/PropertyAnalyzer.cs b/CodeDocumentor/Analyzers/Properties/PropertyAnalyzer.cs
index ed7e911..96f6d5d 100644
--- a/CodeDocumentor/Analyzers/Properties/PropertyAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Properties/PropertyAnalyzer.cs
@@ -12,8 +12,14 @@ namespace CodeDocumentor
/// The property analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class PropertyAnalyzer : DiagnosticAnalyzer
+ public class PropertyAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly PropertyAnalyzerSettings _analyzerSettings;
+
+ public PropertyAnalyzer()
+ {
+ _analyzerSettings = new PropertyAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -21,7 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(PropertyAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -40,7 +46,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is PropertyDeclarationSyntax node))
{
@@ -50,14 +56,13 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
-
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => PropertyAnalyzerSettings.GetRule(alreadyHasComment));
+ var settings = context.BuildSettings(StaticSettings);
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Properties/PropertyAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Properties/PropertyAnalyzerSettings.cs
index 8ccf59a..d5279bd 100644
--- a/CodeDocumentor/Analyzers/Properties/PropertyAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Properties/PropertyAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,14 +22,22 @@ internal class PropertyAnalyzerSettings: BaseAnalyzerSettings
///
internal const string Title = "The property must have a documentation header.";
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
///
/// The diagnostic descriptor rule.
///
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
{
- return new DiagnosticDescriptor(PropertyAnalyzerSettings.DiagnosticId, PropertyAnalyzerSettings.Title,
- PropertyAnalyzerSettings.MessageFormat, PropertyAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Properties/PropertyCodeFixProvider.cs b/CodeDocumentor/Analyzers/Properties/PropertyCodeFixProvider.cs
index 31bdc63..2e9261a 100644
--- a/CodeDocumentor/Analyzers/Properties/PropertyCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Properties/PropertyCodeFixProvider.cs
@@ -4,10 +4,11 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
+using CodeDocumentor.Common.Models;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,8 +58,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
{
return;
}
@@ -66,7 +67,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -78,16 +79,15 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.PropertyDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
{
continue;
}
@@ -95,33 +95,35 @@ internal static int BuildComments(SyntaxNode root, Dictionary();
- var propertyComment = CommentHelper.CreatePropertyComment(declarationSyntax.Identifier.ValueText, isBoolean, hasSetter);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
+
+ var commentHelper = ServiceLocator.CommentHelper;
+ var propertyComment = commentHelper.CreatePropertyComment(declarationSyntax.Identifier.ValueText, isBoolean,
+ hasSetter, settings.ExcludeAsyncSuffix, settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
var returnOptions = new ReturnTypeBuilderOptions
{
- TryToIncludeCrefsForReturnTypes = optionsService.TryToIncludeCrefsForReturnTypes,
- GenerateReturnStatement = optionsService.IncludeValueNodeInProperties,
+ TryToIncludeCrefsForReturnTypes = settings.TryToIncludeCrefsForReturnTypes,
+ GenerateReturnStatement = settings.IncludeValueNodeInProperties,
ReturnGenericTypeAsFullString = false,
IncludeStartingWordInText = true,
UseProperCasing = true
};
- var list = builder.WithSummary(declarationSyntax, propertyComment, optionsService.PreserveExistingSummaryText)
- .WithPropertyValueTypes(declarationSyntax, returnOptions)
+ var list = builder.WithSummary(declarationSyntax, propertyComment, settings.PreserveExistingSummaryText)
+ .WithPropertyValueTypes(declarationSyntax, returnOptions, settings.WordMaps)
.WithExisting(declarationSyntax, Constants.REMARKS)
.WithExisting(declarationSyntax, Constants.EXAMPLE)
.Build();
@@ -141,14 +143,14 @@ private static PropertyDeclarationSyntax BuildNewDeclaration(PropertyDeclaration
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- private Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ private Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, PropertyDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, PropertyAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Records/NonPublicRecordAnalyzer.cs b/CodeDocumentor/Analyzers/Records/NonPublicRecordAnalyzer.cs
index 62f431a..949d78f 100644
--- a/CodeDocumentor/Analyzers/Records/NonPublicRecordAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Records/NonPublicRecordAnalyzer.cs
@@ -1,9 +1,6 @@
-using System.Collections.Generic;
using System.Collections.Immutable;
using CodeDocumentor.Builders;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -15,8 +12,14 @@ namespace CodeDocumentor
/// The class analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class NonPublicRecordAnalyzer : DiagnosticAnalyzer
+ public class NonPublicRecordAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly RecordAnalyzerSettings _analyzerSettings;
+
+ public NonPublicRecordAnalyzer()
+ {
+ _analyzerSettings = new RecordAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -24,10 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- return optionsService.IsEnabledForPublicMembersOnly
- ? new List().ToImmutableArray()
- : ImmutableArray.Create(RecordAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -46,25 +46,24 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var node = context.Node as RecordDeclarationSyntax;
if (!PrivateMemberVerifier.IsPrivateMember(node))
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly)
+ var settings = context.BuildSettings(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly)
{
return;
}
-
var excludeAnanlyzer = DocumentationHeaderHelper.HasAnalyzerExclusion(node);
if (excludeAnanlyzer)
{
return;
}
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => RecordAnalyzerSettings.GetRule(alreadyHasComment));
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Records/RecordAnalyzer.cs b/CodeDocumentor/Analyzers/Records/RecordAnalyzer.cs
index 25e2d86..8e90d74 100644
--- a/CodeDocumentor/Analyzers/Records/RecordAnalyzer.cs
+++ b/CodeDocumentor/Analyzers/Records/RecordAnalyzer.cs
@@ -12,8 +12,14 @@ namespace CodeDocumentor
/// The class analyzer.
///
[DiagnosticAnalyzer(LanguageNames.CSharp)]
- public class RecordAnalyzer : DiagnosticAnalyzer
+ public class RecordAnalyzer : BaseDiagnosticAnalyzer
{
+ private readonly RecordAnalyzerSettings _analyzerSettings;
+
+ public RecordAnalyzer()
+ {
+ _analyzerSettings = new RecordAnalyzerSettings();
+ }
///
/// Gets the supported diagnostics.
///
@@ -21,7 +27,7 @@ public override ImmutableArray SupportedDiagnostics
{
get
{
- return ImmutableArray.Create(RecordAnalyzerSettings.GetRule());
+ return ImmutableArray.Create(_analyzerSettings.GetSupportedDiagnosticRule());
}
}
@@ -40,7 +46,7 @@ public override void Initialize(AnalysisContext context)
/// Analyzes node.
///
/// The context.
- internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
+ internal void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if (!(context.Node is RecordDeclarationSyntax node))
{
@@ -55,8 +61,8 @@ internal static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
return;
}
-
- context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => RecordAnalyzerSettings.GetRule(alreadyHasComment));
+ var settings = context.BuildSettings(StaticSettings);
+ context.BuildDiagnostic(node, node.Identifier, (alreadyHasComment) => _analyzerSettings.GetRule(alreadyHasComment,settings));
}
}
}
diff --git a/CodeDocumentor/Analyzers/Records/RecordAnalyzerSettings.cs b/CodeDocumentor/Analyzers/Records/RecordAnalyzerSettings.cs
index 5433fcf..98e2d76 100644
--- a/CodeDocumentor/Analyzers/Records/RecordAnalyzerSettings.cs
+++ b/CodeDocumentor/Analyzers/Records/RecordAnalyzerSettings.cs
@@ -1,5 +1,6 @@
using CodeDocumentor.Analyzers;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using Microsoft.CodeAnalysis;
namespace CodeDocumentor
@@ -21,11 +22,19 @@ internal class RecordAnalyzerSettings: BaseAnalyzerSettings
///
internal const string Title = "The record must have a documentation header.";
- internal static DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity = false)
+ internal DiagnosticDescriptor GetSupportedDiagnosticRule()
{
- return new DiagnosticDescriptor(RecordAnalyzerSettings.DiagnosticId, RecordAnalyzerSettings.Title,
- RecordAnalyzerSettings.MessageFormat, RecordAnalyzerSettings.Category,
- hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId), true);
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ DiagnosticSeverity.Info,
+ true);
+ }
+
+ internal DiagnosticDescriptor GetRule(bool hideDiagnosticSeverity, ISettings settings)
+ {
+ return new DiagnosticDescriptor(DiagnosticId, Title,
+ MessageFormat, Category,
+ hideDiagnosticSeverity ? DiagnosticSeverity.Hidden : LookupSeverity(DiagnosticId, settings), true);
}
}
}
diff --git a/CodeDocumentor/Analyzers/Records/RecordCodeFixProvider.cs b/CodeDocumentor/Analyzers/Records/RecordCodeFixProvider.cs
index 72ba155..9fdc32b 100644
--- a/CodeDocumentor/Analyzers/Records/RecordCodeFixProvider.cs
+++ b/CodeDocumentor/Analyzers/Records/RecordCodeFixProvider.cs
@@ -4,10 +4,10 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
-using CodeDocumentor.Builders;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Interfaces;
using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
@@ -57,8 +57,8 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
return;
}
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
- if (optionsService.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
+ var settings = await context.BuildSettingsAsync(StaticSettings);
+ if (settings.IsEnabledForPublicMembersOnly && PrivateMemberVerifier.IsPrivateMember(declaration))
{
return;
}
@@ -66,7 +66,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.RegisterCodeFix(
CodeAction.Create(
title: displayTitle,
- createChangedDocument: c => AddDocumentationHeaderAsync(context.Document, root, declaration, c),
+ createChangedDocument: c => AddDocumentationHeaderAsync(settings, context.Document, root, declaration, c),
equivalenceKey: displayTitle),
diagnostic);
@@ -81,14 +81,14 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
/// The declaration syntax.
/// The cancellation token.
/// A Document.
- internal Task AddDocumentationHeaderAsync(Document document, SyntaxNode root, RecordDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
+ internal Task AddDocumentationHeaderAsync(ISettings settings, Document document, SyntaxNode root, RecordDeclarationSyntax declarationSyntax, CancellationToken cancellationToken)
{
return Task.Run(() => TryHelper.Try(() =>
{
- var newDeclaration = BuildNewDeclaration(declarationSyntax);
+ var newDeclaration = BuildNewDeclaration(settings, declarationSyntax);
var newRoot = root.ReplaceNode(declarationSyntax, newDeclaration);
return document.WithSyntaxRoot(newRoot);
- }, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
+ }, RecordAnalyzerSettings.DiagnosticId, EventLogger, (_) => document, eventId: Constants.EventIds.FIXER, category: Constants.EventIds.Categories.ADD_DOCUMENTATION_HEADER), cancellationToken);
}
///
@@ -96,16 +96,15 @@ internal Task AddDocumentationHeaderAsync(Document document, SyntaxNod
///
/// The root.
/// The nodes to replace.
- internal static int BuildComments(SyntaxNode root, Dictionary nodesToReplace)
+ internal static int BuildComments(ISettings settings, SyntaxNode root, Dictionary nodesToReplace)
{
var declarations = root.DescendantNodes().Where(w => w.IsKind(SyntaxKind.RecordDeclaration)).OfType().ToArray();
var neededCommentCount = 0;
TryHelper.Try(() =>
{
- var optionsService = CodeDocumentorPackage.DIContainer().GetInstance();
foreach (var declarationSyntax in declarations)
{
- if (optionsService.IsEnabledForPublicMembersOnly
+ if (settings.IsEnabledForPublicMembersOnly
&& PrivateMemberVerifier.IsPrivateMember(declarationSyntax))
{
continue;
@@ -114,21 +113,21 @@ internal static int BuildComments(SyntaxNode root, Dictionary();
- var comment = CommentHelper.CreateRecordComment(declarationSyntax.Identifier.ValueText);
- var builder = CodeDocumentorPackage.DIContainer().GetInstance();
+ var commentHelper = ServiceLocator.CommentHelper;
+ var comment = commentHelper.CreateRecordComment(declarationSyntax.Identifier.ValueText, settings.WordMaps);
+ var builder = ServiceLocator.DocumentationBuilder;
- var list = builder.WithSummary(declarationSyntax, comment, optionsService.PreserveExistingSummaryText)
+ var list = builder.WithSummary(declarationSyntax, comment, settings.PreserveExistingSummaryText)
.WithTypeParamters(declarationSyntax)
.WithExisting(declarationSyntax, Constants.REMARKS)
.WithExisting(declarationSyntax, Constants.EXAMPLE)
diff --git a/CodeDocumentor/ApplicationRegistrations.cs b/CodeDocumentor/ApplicationRegistrations.cs
deleted file mode 100644
index 8f0aacb..0000000
--- a/CodeDocumentor/ApplicationRegistrations.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-using CodeDocumentor.Builders;
-using CodeDocumentor.Managers;
-using CodeDocumentor.Services;
-using SimpleInjector;
-
-namespace CodeDocumentor
-{
- public static class ApplicationRegistrations
- {
- public static void RegisterServices(this Container container)
- {
- container.RegisterSingleton(() =>
- {
- var opts = new OptionsService();
- return opts;
- });
- //NOTE keep these in sync with unit test container
- container.RegisterSingleton();
- container.Register();
- }
- }
-}
diff --git a/CodeDocumentor/Builders/DiagnosticBuilder.cs b/CodeDocumentor/Builders/DiagnosticBuilder.cs
index 522bf3c..77796a5 100644
--- a/CodeDocumentor/Builders/DiagnosticBuilder.cs
+++ b/CodeDocumentor/Builders/DiagnosticBuilder.cs
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using CodeDocumentor.Helper;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -27,8 +28,9 @@ public static void BuildDiagnostic(this SyntaxNodeAnalysisContext context, CShar
.OfType()
.FirstOrDefault();
- var alreadyHasComment = commentTriviaSyntax != null && CommentHelper.HasComment(commentTriviaSyntax);
-
+ var commentHelper = ServiceLocator.CommentHelper;
+ var alreadyHasComment = commentTriviaSyntax != null && commentHelper.HasComment(commentTriviaSyntax);
+ var settings = context.BuildSettings(null);
try
{
context.ReportDiagnostic(Diagnostic.Create(getRuleCallback.Invoke(alreadyHasComment), identifier.GetLocation()));
diff --git a/CodeDocumentor/Builders/DocumentationBuilder.cs b/CodeDocumentor/Builders/DocumentationBuilder.cs
index 91d9f0f..573a1e3 100644
--- a/CodeDocumentor/Builders/DocumentationBuilder.cs
+++ b/CodeDocumentor/Builders/DocumentationBuilder.cs
@@ -1,8 +1,10 @@
using System.Collections.Generic;
using System.Linq;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Models;
using CodeDocumentor.Constructors;
using CodeDocumentor.Helper;
-using CodeDocumentor.Vsix2022;
+using CodeDocumentor.Locators;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -11,8 +13,9 @@ namespace CodeDocumentor.Builders
{
public class DocumentationBuilder
{
+ private readonly DocumentationHeaderHelper _documentationHeaderHelper = ServiceLocator.DocumentationHeaderHelper;
private XmlElementSyntax _currentElement;
- private List _list = new List();
+ private readonly List _list = new List();
internal SyntaxList Build()
{
@@ -27,7 +30,7 @@ internal DocumentationBuilder Reset()
internal DocumentationBuilder WithExceptionTypes(MethodDeclarationSyntax declarationSyntax)
{
- var exceptions = DocumentationHeaderHelper.GetExceptions(declarationSyntax.Body?.ToFullString());
+ var exceptions = _documentationHeaderHelper.GetExceptions(declarationSyntax.Body?.ToFullString());
if (exceptions.Any())
{
@@ -56,14 +59,15 @@ internal DocumentationBuilder WithExisting(CSharpSyntaxNode declarationSyntax, s
return this;
}
- internal DocumentationBuilder WithParameters(BaseMethodDeclarationSyntax declarationSyntax)
+ internal DocumentationBuilder WithParameters(BaseMethodDeclarationSyntax declarationSyntax, WordMap[] wordMaps)
{
if (declarationSyntax?.ParameterList?.Parameters.Any() == true)
{
+ var commentHelper = ServiceLocator.CommentHelper;
foreach (var parameter in declarationSyntax.ParameterList.Parameters)
{
- var parameterComment = CommentHelper.CreateParameterComment(parameter);
- var parameterElement = DocumentationHeaderHelper.CreateParameterElementSyntax(parameter.Identifier.ValueText, parameterComment);
+ var parameterComment = commentHelper.CreateParameterComment(parameter, wordMaps);
+ var parameterElement = _documentationHeaderHelper.CreateParameterElementSyntax(parameter.Identifier.ValueText, parameterComment);
Reset().WithTripleSlashSpace()
.WithElement(parameterElement)
@@ -73,15 +77,16 @@ internal DocumentationBuilder WithParameters(BaseMethodDeclarationSyntax declara
return this;
}
- internal DocumentationBuilder WithParameters(TypeDeclarationSyntax declarationSyntax)
+ internal DocumentationBuilder WithParameters(TypeDeclarationSyntax declarationSyntax, WordMap[] wordMaps)
{
if (declarationSyntax?.ParameterList?.Parameters.Any() == true)
{
+ var commentHelper = ServiceLocator.CommentHelper;
foreach (var parameter in declarationSyntax.ParameterList.Parameters)
{
- var parameterComment = CommentHelper.CreateParameterComment(parameter);
+ var parameterComment = commentHelper.CreateParameterComment(parameter,wordMaps);
- var parameterElement = DocumentationHeaderHelper.CreateParameterElementSyntax(parameter.Identifier.ValueText, parameterComment);
+ var parameterElement = _documentationHeaderHelper.CreateParameterElementSyntax(parameter.Identifier.ValueText, parameterComment);
Reset().WithTripleSlashSpace()
.WithElement(parameterElement)
@@ -92,12 +97,12 @@ internal DocumentationBuilder WithParameters(TypeDeclarationSyntax declarationSy
}
internal DocumentationBuilder WithPropertyValueTypes(BasePropertyDeclarationSyntax declarationSyntax,
- ReturnTypeBuilderOptions options)
+ ReturnTypeBuilderOptions options, WordMap[] wordMaps)
{
if (options.GenerateReturnStatement)
{
- var returnComment = new ReturnCommentConstruction(declarationSyntax.Type, options).Comment;
- var returnElement = DocumentationHeaderHelper.CreateReturnElementSyntax(returnComment, "value");
+ var returnComment = new ReturnCommentConstruction(declarationSyntax.Type, options, wordMaps).Comment;
+ var returnElement = _documentationHeaderHelper.CreateReturnElementSyntax(returnComment, "value");
Reset().WithTripleSlashSpace()
.WithElement(returnElement) //this already contains the rest of the /// for all the line ...
@@ -106,14 +111,20 @@ internal DocumentationBuilder WithPropertyValueTypes(BasePropertyDeclarationSynt
return this;
}
- internal DocumentationBuilder WithReturnType(MethodDeclarationSyntax declarationSyntax)
+ internal DocumentationBuilder WithReturnType(MethodDeclarationSyntax declarationSyntax,
+ bool useNaturalLanguageForReturnNode,
+ bool tryToIncludeCrefsForReturnTypes,
+ WordMap[] wordMaps)
{
- var returnType = declarationSyntax.ReturnType.ToString();
+ var returnType = declarationSyntax.ReturnType.ToString().Replace("?",string.Empty);
if (returnType != "void")
{
- var commentConstructor = new ReturnCommentConstruction(declarationSyntax.ReturnType);
+ var commentConstructor = new ReturnCommentConstruction(declarationSyntax.ReturnType,
+ useNaturalLanguageForReturnNode,
+ tryToIncludeCrefsForReturnTypes,
+ wordMaps);
var returnComment = commentConstructor.Comment;
- var returnElement = DocumentationHeaderHelper.CreateReturnElementSyntax(returnComment);
+ var returnElement = _documentationHeaderHelper.CreateReturnElementSyntax(returnComment);
Reset().WithTripleSlashSpace()
.WithElement(returnElement) //this already contains the rest of the /// for all the line ...
@@ -157,7 +168,7 @@ internal DocumentationBuilder WithTypeParamters(TypeDeclarationSyntax declaratio
{
foreach (var parameter in declarationSyntax.TypeParameterList.Parameters)
{
- var typeElement = DocumentationHeaderHelper.CreateElementWithAttributeSyntax("typeparam", "name", parameter.Identifier.ValueText);
+ var typeElement = _documentationHeaderHelper.CreateElementWithAttributeSyntax("typeparam", "name", parameter.Identifier.ValueText);
Reset().WithTripleSlashSpace()
.WithElement(typeElement) //this already contains the rest of the /// for all the line ...
.WithLineEndTextSyntax();
@@ -172,7 +183,7 @@ internal DocumentationBuilder WithTypeParamters(MethodDeclarationSyntax declarat
{
foreach (var parameter in declarationSyntax.TypeParameterList.Parameters)
{
- var typeElement = DocumentationHeaderHelper.CreateElementWithAttributeSyntax("typeparam", "name", parameter.Identifier.ValueText);
+ var typeElement = _documentationHeaderHelper.CreateElementWithAttributeSyntax("typeparam", "name", parameter.Identifier.ValueText);
Reset().WithTripleSlashSpace()
.WithElement(typeElement) //this already contains the rest of the /// for all the line ...
.WithLineEndTextSyntax();
diff --git a/CodeDocumentor/CodeDocumentor.Package.cs b/CodeDocumentor/CodeDocumentor.Package.cs
index 7392fb3..8203255 100644
--- a/CodeDocumentor/CodeDocumentor.Package.cs
+++ b/CodeDocumentor/CodeDocumentor.Package.cs
@@ -1,14 +1,13 @@
using System;
+using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
-using CodeDocumentor.Helper;
-using CodeDocumentor.Services;
-using CodeDocumentor.Settings;
+using CodeDocumentor.Common;
+using CodeDocumentor.Common.Models;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Threading;
-using SimpleInjector;
using Task = System.Threading.Tasks.Task;
[assembly: InternalsVisibleTo("CodeDocumentor.Test")]
@@ -40,54 +39,13 @@ namespace CodeDocumentor.Vsix2022
[InstalledProductRegistration("#110", "#112", VsixOptions.Version, IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[ProvideOptionPage(typeof(OptionPageGrid), OptionPageGrid.Category, OptionPageGrid.SubCategory, 1000, 1001, true)]
- [ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
+ //[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
[ProvideAutoLoad(UIContextGuids80.SolutionExists, PackageAutoLoadFlags.BackgroundLoad)]
+ [ComVisible(true)]
public sealed class CodeDocumentorPackage : AsyncPackage
{
- public static Func ContainerFactory { get; set; }
-
- public static Container DIContainer()
- {
- if (ContainerFactory != null)
- {
- return ContainerFactory();
- }
- if (_DIContainer == null)
- {
- _DIContainer = new Container();
- _DIContainer.RegisterServices();
- _DIContainer.Verify();
- }
- return _DIContainer;
- }
-
-#pragma warning disable IDE1006 // Naming Styles
- internal static IOptionPageGrid _options;
-#pragma warning restore IDE1006 // Naming Styles
-
-#pragma warning disable IDE1006 // Naming Styles
- private static Container _DIContainer;
-#pragma warning restore IDE1006 // Naming Styles
-
#region Package Members
- ///
- /// Gets the options.
- ///
- /// An IOptionPageGrid.
- public static IOptionPageGrid Options
- {
- get
- {
- return _options;
- }
- internal set
- {
- //This is used for testing
- _options = value;
- }
- }
-
///
/// Initialization of the package; this method is called right after the package is sited, so this is the place
/// where you can put all the initialization code that rely on services provided by VisualStudio.
@@ -106,11 +64,41 @@ protected override async Task InitializeAsync(CancellationToken cancellationToke
// initialization that requires the UI thread after switching to the UI thread.
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
- _options = (OptionPageGrid)GetDialogPage(typeof(OptionPageGrid));
+ //var hasCodeDocumentorInEditorConfig = await SlnHasEditorConfigAsync(hasCodeDocumentorInEditorConfig);
+
+ //When .editorconfig settings are available, we will use those,
+ //but we still bootstrap all the static injections, because we can only read the .editorconfig settings at runtime from the contexts
+ var options = (OptionPageGrid)GetDialogPage(typeof(OptionPageGrid));
+ var settings = new Settings();
+ settings.SetFromOptionsGrid(options);
+ BaseCodeFixProvider.SetSettings(settings);
+ BaseDiagnosticAnalyzer.SetSettings(settings);
+
+ }
+
+ private async System.Threading.Tasks.Task SlnHasEditorConfigAsync(bool hasCodeDocumentorInEditorConfig)
+ {
+ var solutionService = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution;
+ if (solutionService != null)
+ {
+ solutionService.GetSolutionInfo(out string solutionDir, out _, out _);
+
+ if (!string.IsNullOrEmpty(solutionDir))
+ {
+ // Look for .editorconfig in the solution directory
+ var editorConfigPath = System.IO.Path.Combine(solutionDir, ".editorconfig");
+ if (System.IO.File.Exists(editorConfigPath))
+ {
+ // Read the .editorconfig file
+ var lines = System.IO.File.ReadAllLines(editorConfigPath);
+ // Check for a specific value, e.g., "my_setting = true"
+ hasCodeDocumentorInEditorConfig = lines.Any(line => line.Trim().StartsWith("codedocumentor_", StringComparison.OrdinalIgnoreCase));
+
+ }
+ }
+ }
- var optService = DIContainer().GetInstance();
- optService.SetDefaults(_options);
- Translator.Initialize(optService);
+ return hasCodeDocumentorInEditorConfig;
}
#endregion
diff --git a/CodeDocumentor/CodeDocumentor.csproj b/CodeDocumentor/CodeDocumentor.csproj
index 96e9b0c..6b133ee 100644
--- a/CodeDocumentor/CodeDocumentor.csproj
+++ b/CodeDocumentor/CodeDocumentor.csproj
@@ -1,4 +1,4 @@
-
+
17.0
@@ -54,7 +54,8 @@
-
+
+
@@ -66,20 +67,19 @@
-
-
+
+
+
+
+
-
-
-
-
@@ -89,61 +89,47 @@
-
-
-
-
-
Component
-
-
-
-
-
-
+
+ 4.13.0
+
+
compile; build; native; contentfiles; analyzers; buildtransitive
runtime; build; native; contentfiles; analyzers; buildtransitive
all
-
- 13.0.3
-
-
- 5.4.4
-
8.0.0
-
+
-
@@ -162,7 +148,15 @@
true
-
+
+
+
+
+
+ {7cc64cdf-a7ff-463b-8f05-c37a6c0a820c}
+ CodeDocumentor.Common
+
+
-- [CodeDocumentor](#codedocumentor)
- - [Installation](#installation)
- - [Table of Contents](#table-of-contents)
- - [Instruction](#instruction)
- - [Known Issues](#known-issues)
- - [Comment Ordering](#comment-ordering)
- - [Supported Comment Refactorings](#supported-comment-refactorings)
- - [Settings](#settings)
- - [Word Translations](#word-translations)
- - [Recommended Settings](#recommended-settings)
- - [Also Supports](#also-supports)
- - [Excluding ErrorList Messages](#excluding-errorlist-messages)
- - [Available DiagnosticId Codes](#available-diagnosticid-codes)
- - [Supported Members](#supported-members)
- - [Attribute](#attribute)
+- [Instruction](#instruction)
+- [Known Issues](#known-issues)
+- [Comment Ordering](#comment-ordering)
+- [Supported Comment Refactorings](#supported-comment-refactorings)
+- [Settings](#settings)
+ - [Word Translations](#word-translations)
+ - [Recommended Settings](#recommended-settings)
+- [Also Supports](#also-supports)
+ - [One Word Methods](#one-word-methods)
- [Example](#example)
- - [Usage Examples](#usage-examples)
- - [Errors and Crashes](#errors-and-crashes)
- - [Changelog](#changelog)
- - [Example Cref Support](#example-cref-support)
- - [Special Thanks](#special-thanks)
+- [Excluding ErrorList Messages](#excluding-errorlist-messages)
+ - [Available DiagnosticId Codes](#available-diagnosticid-codes)
+ - [Supported Members](#supported-members)
+ - [Attribute](#attribute)
+ - [Example](#example-1)
+- [Usage Examples](#usage-examples)
+ - [Example Cref Support](#example-cref-support)
+- [Errors and Crashes](#errors-and-crashes)
+- [Using .editorconfig for settings](#using-editorconfig-for-settings)
+- [Changelog](#changelog)
+- [Special Thanks](#special-thanks)
@@ -52,16 +52,22 @@ Download and install the VSIX from the [VS Marketplace](https://marketplace.visu
## Known Issues
-- As of VS2022 verison 17.6.x there is some bug that makes extension analyzers not being to work work properly if you have *Run code analysis in seperate process*
+Microsoft is not going to make any changes to truly allow analyzers to run out of process. Even with .editorconfig support, it will not work if you want to have any user level settings collection from Visual Studio > Options.
+
+- As of VS2022 version 17.6.x there is some bug that makes extension analyzers not being to work work properly if you have *Run code analysis in seperate process*

**Please disable this setting to allow CodeDocumentor to work correctly.**
-- As of VS2022 Version 17.8.6. Out of process works but ONLY if you deselect _Run code analysis on latest .NET_.
+- As of VS2022 Version 17.8.6. Out of process works but ONLY if you deselect *_Run code analysis on latest .NET_*.

+- As of VS2022 Version 17.14.13. Out of process does not work AGAIN. you need to deselect *_Run code analysis in separate process*.
+ 
+ **Please disable this setting to allow CodeDocumentor to work correctly.**
+
## Comment Ordering
@@ -105,7 +111,7 @@ To adjust these defaults go to Tools > Options > CodeDocumentor
| Method Diagnostics | Allows setting a new default diagnostic level for evaluation for methods. A restart of Visual Studio is required on change. |
| Property Diagnostics | Allows setting a new default diagnostic level for evaluation for properties. A restart of Visual Studio is required on change. |
| Record Diagnostics | Allows setting a new default diagnostic level for evaluation for records. A restart of Visual Studio is required on change. |
-
+| Use .editorconfig for settings options | This will convert existing extension options to .editorconfig values stored in %USERPROFILE%. This allows CodeDocumentor to run out of process.|
@@ -256,6 +262,20 @@ How fast comments can be added

+### Example Cref Support
+
+```csharp
+///
+/// Creates and return a of type of type asynchronously.
+///
+/// The client data transfer object.
+///
+/// A of type of type
+internal Task> CreateAsync(CreateClientDto clientDto)
+{
+throw new ArgumentException("test");
+}
+```
## Errors and Crashes
@@ -269,6 +289,14 @@ All errors are written to the EventLog in windows. Check there for causes, and u

+## Using .editorconfig for settings
+
+To convert existing settings to .editorconfig go to Tools > Options > CodeDocumentor and select **Use .editorconfig for settings options**.
+This will convert the existing Visual Studio Option Settings to editor config format and copy them to your clipboard.
+Paste this into a new or existing .editorconfig file in your solution.
+
+**NOTE**: Event with using .editroconfig as your settings, Out of Process still can not be used, because the extension needs to support backward compatibility of using the Visual Studio Options.
+
## Changelog
@@ -279,21 +307,8 @@ All errors are written to the EventLog in windows. Check there for causes, and u
| | Added support for `````` tags in summary and return nodes | |
| | Bug fixes | |
| 02/1/2024 | Added support for ArgumentNullException.ThrowIf statements | 2.0.1.1 |
+| 09/01/2025 | Added support for storing settings in a solution level .editorconfig | 3.0.0.0 |
-#### Example Cref Support
-
-```csharp
-///
-/// Creates and return a of type of type asynchronously.
-///
-/// The client data transfer object.
-///
-/// A of type of type
-internal Task> CreateAsync(CreateClientDto clientDto)
-{
-throw new ArgumentException("test");
-}
-```
## Special Thanks
This was forked and modified from [jinyafeng](https://github.com/jinyafeng/DocumentationAssistant)
diff --git a/TestProject/Sample/.editorconfig b/TestProject/Sample/.editorconfig
new file mode 100644
index 0000000..fb2dc21
--- /dev/null
+++ b/TestProject/Sample/.editorconfig
@@ -0,0 +1,40 @@
+# Editor configuration, see http://editorconfig.org
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+indent_style = space
+indent_size = 2
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.md]
+max_line_length = off
+trim_trailing_whitespace = false
+
+[*.php]
+end_of_line = crlf
+indent_size = 4
+insert_final_newline = false
+
+[*.cs]
+# CodeDocumentor settings
+codedocumentor_class_diagram_severity = Warning
+codedocumentor_constructor_diagram_severity = Warning
+codedocumentor_default_diagram_severity = Warning
+codedocumentor_enum_diagram_severity = Warning
+codedocumentor_field_diagram_severity = Warning
+codedocumentor_interface_diagram_severity = Warning
+codedocumentor_method_diagram_severity = Warning
+codedocumentor_property_diagram_severity = Warning
+codedocumentor_record_diagram_severity = Warning
+codedocumentor_exclude_async_suffix = False
+codedocumentor_include_value_node_in_properties = False
+codedocumentor_is_enabled_for_public_members_only = False
+codedocumentor_is_enabled_for_non_public_fields = False
+codedocumentor_preserve_existing_summary_text = True
+codedocumentor_try_to_include_crefs_for_return_types = True
+codedocumentor_use_natural_language_for_return_node = False
+codedocumentor_use_todo_comments_on_summary_error = True
+codedocumentor_wordmap = int:integer|Int32:integer|Int64:integer|OfList:OfLists|OfEnumerable:OfLists|IEnumerable:List|IList:List|IReadOnlyList:Read Only List|ICollection:Collection|OfCollection:OfCollections|IReadOnlyCollection:Read Only Collection|IReadOnlyDictionary:Read Only Dictionary
diff --git a/TestProject/Sample/Sample.sln b/TestProject/Sample/Sample.sln
index 9294b44..c63d806 100644
--- a/TestProject/Sample/Sample.sln
+++ b/TestProject/Sample/Sample.sln
@@ -5,6 +5,11 @@ VisualStudioVersion = 17.0.31912.275
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sample", "Sample\Sample.csproj", "{A3BBEBB1-7614-4446-A87D-8E9F0A3CAAE6}"
EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8EC462FD-D22E-90A8-E5CE-7E832BA40C5D}"
+ ProjectSection(SolutionItems) = preProject
+ .editorconfig = .editorconfig
+ EndProjectSection
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
diff --git a/TestProject/Sample/Sample/CodeDocumentor/ClassConstructors.cs b/TestProject/Sample/Sample/CodeDocumentor/ClassConstructors.cs
index c5d8e25..a6c214b 100644
--- a/TestProject/Sample/Sample/CodeDocumentor/ClassConstructors.cs
+++ b/TestProject/Sample/Sample/CodeDocumentor/ClassConstructors.cs
@@ -1,11 +1,11 @@
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
-using System.Threading.Tasks;
namespace Sample.CodeDocumentor
{
+
public class ClassConstructors(string test, int testInt)
{
}
diff --git a/TestProject/Sample/Sample/CodeDocumentor/FieldOCRTestSingleClass.cs b/TestProject/Sample/Sample/CodeDocumentor/FieldOCRTestSingleClass.cs
index 68649ec..ba8f38e 100644
--- a/TestProject/Sample/Sample/CodeDocumentor/FieldOCRTestSingleClass.cs
+++ b/TestProject/Sample/Sample/CodeDocumentor/FieldOCRTestSingleClass.cs
@@ -6,109 +6,106 @@
namespace Sample.CodeDocumentor
{
+ ///
+ /// The interface interface.
+ ///
+ ///
+ interface IInterface
+ {
+
+ string DoWork();
+ }
+
+ ///
+ /// The test types.
+ ///
+ ///
+ public class TestTypes
+ {
+
+ }
+
+ public class InhertitTestTypes : TestTypes
+ {
+ private class Tester { }
+ }
+
+
+
+
+
+ ///
+ /// The field OCR test single class.
+ ///
+ internal class FieldOCRTestSingleClass : IInterface
+ {
///
- /// The interface interface.
+ /// test field.
///
- ///
- interface IInterface
- {
- ///
- /// Does the work.
- ///
- /// A string.
- string DoWork();
- }
+ private static string _testField;
+ ///
+ /// Gets or Sets the test property.
+ ///
+ public int TestProperty { get; set; }
///
- /// The test types.
+ /// Initializes a new instance of the class.
///
- ///
- public class TestTypes
+ public FieldOCRTestSingleClass()
{
}
- public class InhertitTestTypes : TestTypes
+ ///
+ /// Does the work.
+ ///
+ /// A string.
+ public string DoWork()
{
-
+ return "";
+ }
+ ///
+ /// Does the work with params.
+ ///
+ /// The test.
+ /// The we.
+ /// A bool.
+ internal bool DoWorkWithParams(string test, string we)
+ {
+ return true;
}
+ internal string WorkWithTypes(string test, string we)
+ {
+ return "";
+ }
+ internal string WorkWithTypesWithException(string test, string we)
+ {
+ throw new ArgumentException("");
+ }
-
- ///
- /// The field OCR test single class.
- ///
- internal class FieldOCRTestSingleClass : IInterface
+ internal string WorkWithTypesWithInlineException(string test, string we)
{
- ///
- /// test field.
- ///
- private static string _testField;
- ///
- /// Gets or Sets the test property.
- ///
- public int TestProperty { get; set; }
-
- ///
- /// Initializes a new instance of the class.
- ///
- public FieldOCRTestSingleClass()
- {
-
- }
-
- ///
- /// Does the work.
- ///
- /// A string.
- public string DoWork()
- {
- return "";
- }
- ///
- /// Does the work with params.
- ///
- /// The test.
- /// The we.
- /// A bool.
- internal bool DoWorkWithParams(string test, string we)
- {
- return true;
- }
-
- internal string WorkWithTypes(string test, string we)
- {
- return "";
- }
-
- internal string WorkWithTypesWithException(string test, string we)
- {
- throw new ArgumentException("");
- }
-
-
- internal string WorkWithTypesWithInlineException(string test, string we)
- {
- ArgumentException.ThrowIfNullOrEmpty(test, nameof(test));
- ArgumentNullException.ThrowIfNull(we, nameof(we));
- throw new Exception("test");
- }
+ ArgumentException.ThrowIfNullOrEmpty(test, nameof(test));
+ ArgumentNullException.ThrowIfNull(we, nameof(we));
+ throw new Exception("test");
}
+ }
+ ///
+ /// The test record.
+ ///
+ internal record TestRecord
+ {
///
- /// The test record.
+ /// test field.
///
- internal record TestRecord
- {
- ///
- /// test field.
- ///
- private static string _testField;
- ///
- /// Gets or Sets the test property.
- ///
- public int TestProperty { get; set; }
- }
+ private static string _testField;
+ ///
+ /// Gets or Sets the test property.
+ ///
+ public int TestProperty { get; set; }
+ }
}
diff --git a/TestProject/Sample/Sample/CodeDocumentor/ITestPublicInteraceMethods.cs b/TestProject/Sample/Sample/CodeDocumentor/ITestPublicInteraceMethods.cs
new file mode 100644
index 0000000..2f28e00
--- /dev/null
+++ b/TestProject/Sample/Sample/CodeDocumentor/ITestPublicInteraceMethods.cs
@@ -0,0 +1,10 @@
+using System.Threading.Tasks;
+
+namespace Sample.CodeDocumentor
+{
+
+ public interface ITestPublicInteraceMethods
+ {
+ Task GetNamesAsync(string name);
+ }
+}