From 3ddd8a3c1296862d97924fcf1d30b5a96055e773 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sun, 29 Jun 2025 17:08:32 +0200 Subject: [PATCH 1/8] refactoring: split reader from dict to implement different readers + minor fixes --- .gitignore | 4 + source/forms/DeclarationDictApiDialog.cls | 2 +- source/modules/CodeModulGenerator.cls | 2 +- .../modules/CodemoduleDeclarationReader.cls | 225 ++++++++++++++++++ source/modules/DeclarationDict.cls | 223 +---------------- source/modules/FileTools.bas | 6 +- source/modules/_AddInAPI.bas | 83 ++++--- source/vcs-options.json | 2 +- 8 files changed, 288 insertions(+), 259 deletions(-) create mode 100644 source/modules/CodemoduleDeclarationReader.cls diff --git a/.gitignore b/.gitignore index fe82cce..38de702 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,7 @@ vcs-index.json # Ignore log files generated by the VCS Add-in # Comment out the following line if you wish to include log files in git. *.log + +# others +*.dll +*.zip \ No newline at end of file diff --git a/source/forms/DeclarationDictApiDialog.cls b/source/forms/DeclarationDictApiDialog.cls index bd46d20..d14bec7 100644 --- a/source/forms/DeclarationDictApiDialog.cls +++ b/source/forms/DeclarationDictApiDialog.cls @@ -203,7 +203,7 @@ Private Sub RefreshDiffData() Else With Me.lbDictData Set .Recordset = m_WordListRecordset - .Value = Me.lbDictData.Column(0, 0) + .Value = .Column(0, Abs(.ColumnHeads)) End With FillWordVariationsList End If diff --git a/source/modules/CodeModulGenerator.cls b/source/modules/CodeModulGenerator.cls index 60eace2..aa99f4a 100644 --- a/source/modules/CodeModulGenerator.cls +++ b/source/modules/CodeModulGenerator.cls @@ -7,7 +7,7 @@ Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False -Option Compare Database +Option Compare Text Option Explicit Private m_VBComponent As VBComponent diff --git a/source/modules/CodemoduleDeclarationReader.cls b/source/modules/CodemoduleDeclarationReader.cls new file mode 100644 index 0000000..e2245d2 --- /dev/null +++ b/source/modules/CodemoduleDeclarationReader.cls @@ -0,0 +1,225 @@ +VERSION 1.0 CLASS +BEGIN + MultiUse = -1 'True +END +Attribute VB_Name = "CodemoduleDeclarationReader" +Attribute VB_GlobalNameSpace = False +Attribute VB_Creatable = False +Attribute VB_PredeclaredId = False +Attribute VB_Exposed = False +Option Compare Text +Option Explicit + +Private m_DeclDict As DeclarationDict + +Public Sub ImportVBProject(ByVal VBProject2Import As VBProject, ByVal DeclDict As DeclarationDict) + + Dim vbc As VBComponent + + For Each vbc In VBProject2Import.VBComponents + ImportVBComponent vbc, DeclDict + Next + +End Sub + +Public Sub ImportVBComponent(ByVal VBComponent2Import As VBComponent, ByVal DeclDict As DeclarationDict) + ImportCodeModule VBComponent2Import.CodeModule, DeclDict +End Sub + +Public Sub ImportCodeModule(ByVal CodeModule2Import As CodeModule, ByVal DeclDict As DeclarationDict) + If CodeModule2Import.CountOfLines > 0 Then + ImportCode CodeModule2Import.Lines(1, CodeModule2Import.CountOfLines), DeclDict + End If +End Sub + +Public Sub ImportCode(ByVal Code As String, ByVal DeclDict As DeclarationDict) + + Dim RegEx As RegExp + Set RegEx = NewRegExp + + Set m_DeclDict = DeclDict + + Code = PrepareCode(Code, RegEx) + + Const ProcIndex As Long = 0 + Const EnumTypeIndex As Long = 1 + + Dim Patterns(2) As String + + Patterns(ProcIndex) = "(?:\r|\n|^)\s*(?:Sub|Function|Property Get|Property Let|Property Set|Event)\s+([^\r\n]*)" + Patterns(EnumTypeIndex) = "(?:\r|\n|^)\s*(?:Enum|Type)([\s\S]*?)(?:End\s+(?:Enum|Type))" + Patterns(2) = "(?:\r|\n|^)\s*(?:Dim|ReDim|Private|Friend|Public|Const|Static|Global|Implements)\s+([^\r\n]*)" + + Dim i As Long + For i = 0 To UBound(Patterns) + RegEx.Pattern = Patterns(i) + AddFromCode Code, RegEx, i = ProcIndex, i = EnumTypeIndex + Next + +End Sub + +Private Function NewRegExp() As RegExp + + Dim RegEx As RegExp + + Set RegEx = New RegExp + RegEx.IgnoreCase = True + RegEx.Global = True + + Set NewRegExp = RegEx + +End Function + +Private Function PrepareCode(ByVal Code As String, ByVal RegEx As RegExp) As String + + Code = Replace(Code, " _" & vbNewLine, " ") + +#If DebugPrintEnabled Then + DebugPrint Code, True, "PrepareCode - after Replace ' _' & vbNewLine" +#End If + + With RegEx + + ' clear all strings + .Pattern = """[^""\r\n]*""" + Code = .Replace(Code, "") + + ' remove comments + '.Pattern = "'(.*)[\r\n]" + .Pattern = "'(.*)([\r\n]|$)" + Code = .Replace(Code, "$2") + +#If DebugPrintEnabled Then + DebugPrint Code, True, "PrepareCode- after remove comments" +#End If + + ' treat line labels as dim (but not line numbers) + .Pattern = "([\r\n]|^)([^0-9\r\n]\S*):(\s|[\r\n]|$)" + Code = .Replace(Code, "$1Dim $2:$3") + + ' dim a as String: a = 5 => insert line break + .Pattern = "(\:\s)" + Code = .Replace(Code, vbNewLine) + + ' remove Withevents + .Pattern = "(Public|Private|Friend|Global)\sWithEvents\s" + Code = .Replace(Code, "$1 ") + + ' API declaration => convert to normal procedure declaration + .Pattern = "(?:Declare PtrSafe)\s(Function|Sub)\s" + Code = .Replace(Code, "Declare $1 ") + + RegEx.Pattern = "(?:Declare)\s(Function|Sub)\s([^ ]*)[^(]*\(" + Code = .Replace(Code, "$1 $2(") + + ' remove Static before Function, Sub, Property, .. + .Pattern = "(?:Static)+\s(Function|Sub|Property)\s" + Code = .Replace(Code, "$1 ") + + ' remove Public, Private, Friend before Function, Sub, Property, .. + .Pattern = "(?:Public|Private|Friend|Global)\s(Function|Sub|Property|Event|Enum|Type|Const)\s" + Code = .Replace(Code, "$1 ") + + End With + +#If DebugPrintEnabled Then + DebugPrint Code, True, "PrepareCode - completed" +#End If + + PrepareCode = Code + +End Function + +Private Sub AddFromCode(ByVal Code As String, ByVal RegEx As RegExp, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) + + Dim Match As Match + Dim i As Long + + For Each Match In RegEx.Execute(Code) + For i = 0 To Match.SubMatches.Count - 1 + AddWordFromDeclaration Match.SubMatches(i), IsProcedure, IsEnumTypeBlock + Next + Next + +End Sub + +Private Sub AddWordFromDeclaration(ByRef Declarations As String, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) + + Dim Word As String + Dim i As Long + Dim Pos As Long + Dim PosX As Long + + Dim DeclArray() As String + + If IsEnumTypeBlock Then + Declarations = Replace(Declarations, vbCr, ",") + Declarations = Replace(Declarations, vbLf, vbNullString) + End If + + Declarations = Trim(Declarations) + + If IsProcedure Then + ' Debug.Print Declarations + Declarations = Replace(Declarations, "()", vbNullString) + Declarations = Replace(Declarations, "Optional ", vbNullString) + Declarations = Replace(Declarations, "ByRef ", vbNullString) + Declarations = Replace(Declarations, "ByVal ", vbNullString) + Declarations = Replace(Declarations, "ParamArray ", vbNullString) + + Pos = InStr(1, Declarations, "(") + If Pos > 0 Then + Mid(Declarations, Pos, 1) = "," + End If + Declarations = Replace(Declarations, ")", vbNullString) + End If + + Do While InStr(1, Declarations, " ") > 0 + Declarations = Replace(Declarations, " ", " ") + Loop + + If Not (IsProcedure Or IsEnumTypeBlock) Then + Do While Declarations Like "*(*,*)*" + ' prevent multi-dimensional Dim from transforming into new declarations (might be numeric) + Pos = InStr(1, Declarations, "(") + PosX = InStr(Pos, Declarations, ")") + Declarations = Left(Declarations, Pos - 1) & " " & Mid(Declarations, PosX + 1) + Loop + End If + + DeclArray = Split(Trim(Declarations), ",") + + For i = LBound(DeclArray) To UBound(DeclArray) + Word = Trim(DeclArray(i)) + Pos = CutPos(Word) + If Pos > 1 Then + Word = Trim(Left(Word, Pos - 1)) + End If + If Len(Word) > 0 Then + m_DeclDict.AddWord Word + End If + Next + +End Sub + +Private Function CutPos(ByVal Expression As String) As Long + + Dim Pos As Long + Dim PosX As Long + + Const CutChars As String = " ()" + + Dim i As Long + + For i = 1 To Len(CutChars) + PosX = InStr(1, Expression, Mid(CutChars, i, 1)) + If PosX > 0 Then + If Pos = 0 Or PosX < Pos Then + Pos = PosX + End If + End If + Next + + CutPos = Pos + +End Function diff --git a/source/modules/DeclarationDict.cls b/source/modules/DeclarationDict.cls index b743ce9..d0ed720 100644 --- a/source/modules/DeclarationDict.cls +++ b/source/modules/DeclarationDict.cls @@ -7,7 +7,7 @@ Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = False Attribute VB_Exposed = False -Option Compare Database +Option Compare Text Option Explicit #Const DebugPrintEnabled = 0 @@ -121,7 +121,9 @@ Public Sub AddWord(ByVal Word As String) If Not m_Words.Exists(Word) Then m_Words.Add Word, Word m_WordVariations.Add Word, GetNewDict(BinaryCompare) - RaiseInsert = True + m_WordVariations.Item(Word).Add Word, Word + RaiseEvent WordInserted(Word) + Exit Sub End If Set SubDict = m_WordVariations.Item(Word) @@ -139,224 +141,12 @@ Public Sub AddWord(ByVal Word As String) End If End With - If RaiseInsert Then - RaiseEvent WordInserted(Word) - ElseIf RaiseChanged Then + If RaiseChanged Then RaiseEvent WordChanged(Word) End If End Sub -Public Sub ImportVBProject(ByVal VBProject2Import As VBProject) - - Dim vbc As VBComponent - - For Each vbc In VBProject2Import.VBComponents - ImportVBComponent vbc - Next - -End Sub - -Public Sub ImportVBComponent(ByVal VBComponent2Import As VBComponent) - ImportCodeModule VBComponent2Import.CodeModule -End Sub - -Public Sub ImportCodeModule(ByVal CodeModule2Import As CodeModule) - If CodeModule2Import.CountOfLines > 0 Then - ImportCode CodeModule2Import.Lines(1, CodeModule2Import.CountOfLines) - End If -End Sub - -Public Sub ImportCode(ByVal Code As String) - - Dim RegEx As RegExp - Set RegEx = NewRegExp - - Code = PrepareCode(Code, RegEx) - - Const ProcIndex As Long = 0 - Const EnumTypeIndex As Long = 1 - - Dim Patterns(2) As String - - Patterns(ProcIndex) = "(?:\r|\n|^)\s*(?:Sub|Function|Property Get|Property Let|Property Set|Event)\s+([^\r\n]*)" - Patterns(EnumTypeIndex) = "(?:\r|\n|^)\s*(?:Enum|Type)([\s\S]*?)(?:End\s+(?:Enum|Type))" - Patterns(2) = "(?:\r|\n|^)\s*(?:Dim|ReDim|Private|Friend|Public|Const|Static|Global|Implements)\s+([^\r\n]*)" - - Dim i As Long - For i = 0 To UBound(Patterns) - RegEx.Pattern = Patterns(i) - AddFromCode Code, RegEx, i = ProcIndex, i = EnumTypeIndex - Next - -End Sub - -Private Function NewRegExp() As RegExp - - Dim RegEx As RegExp - - Set RegEx = New RegExp - RegEx.IgnoreCase = True - RegEx.Global = True - - Set NewRegExp = RegEx - -End Function - -Private Function PrepareCode(ByVal Code As String, ByVal RegEx As RegExp) As String - - Code = Replace(Code, " _" & vbNewLine, " ") - -#If DebugPrintEnabled Then - DebugPrint Code, True, "PrepareCode - after Replace ' _' & vbNewLine" -#End If - - With RegEx - - ' clear all strings - .Pattern = """[^""\r\n]*""" - Code = .Replace(Code, "") - - ' remove comments - '.Pattern = "'(.*)[\r\n]" - .Pattern = "'(.*)([\r\n]|$)" - Code = .Replace(Code, "$2") - -#If DebugPrintEnabled Then - DebugPrint Code, True, "PrepareCode- after remove comments" -#End If - - ' treat line labels as dim (but not line numbers) - .Pattern = "([\r\n]|^)([^0-9\r\n]\S*):(\s|[\r\n]|$)" - Code = .Replace(Code, "$1Dim $2:$3") - - ' dim a as String: a = 5 => insert line break - .Pattern = "(\:\s)" - Code = .Replace(Code, vbNewLine) - - ' remove Withevents - .Pattern = "(Public|Private|Friend|Global)\sWithEvents\s" - Code = .Replace(Code, "$1 ") - - ' API declaration => convert to normal procedure declaration - .Pattern = "(?:Declare PtrSafe)\s(Function|Sub)\s" - Code = .Replace(Code, "Declare $1 ") - - RegEx.Pattern = "(?:Declare)\s(Function|Sub)\s([^ ]*)[^(]*\(" - Code = .Replace(Code, "$1 $2(") - - ' remove Static before Function, Sub, Property, .. - .Pattern = "(?:Static)+\s(Function|Sub|Property)\s" - Code = .Replace(Code, "$1 ") - - ' remove Public, Private, Friend before Function, Sub, Property, .. - .Pattern = "(?:Public|Private|Friend|Global)\s(Function|Sub|Property|Event|Enum|Type|Const)\s" - Code = .Replace(Code, "$1 ") - - End With - -#If DebugPrintEnabled Then - DebugPrint Code, True, "PrepareCode - completed" -#End If - - PrepareCode = Code - -End Function - -Private Sub AddFromCode(ByVal Code As String, ByVal RegEx As RegExp, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) - - Dim Match As Match - Dim i As Long - - For Each Match In RegEx.Execute(Code) - For i = 0 To Match.SubMatches.Count - 1 - AddWordFromDeclaration Match.SubMatches(i), IsProcedure, IsEnumTypeBlock - Next - Next - -End Sub - -Private Sub AddWordFromDeclaration(ByRef Declarations As String, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) - - Dim Word As String - Dim i As Long - Dim Pos As Long - Dim PosX As Long - - Dim DeclArray() As String - - If IsEnumTypeBlock Then - Declarations = Replace(Declarations, vbCr, ",") - Declarations = Replace(Declarations, vbLf, vbNullString) - End If - - Declarations = Trim(Declarations) - - If IsProcedure Then - ' Debug.Print Declarations - Declarations = Replace(Declarations, "()", vbNullString) - Declarations = Replace(Declarations, "Optional ", vbNullString) - Declarations = Replace(Declarations, "ByRef ", vbNullString) - Declarations = Replace(Declarations, "ByVal ", vbNullString) - Declarations = Replace(Declarations, "ParamArray ", vbNullString) - - Pos = InStr(1, Declarations, "(") - If Pos > 0 Then - Mid(Declarations, Pos, 1) = "," - End If - Declarations = Replace(Declarations, ")", vbNullString) - End If - - Do While InStr(1, Declarations, " ") > 0 - Declarations = Replace(Declarations, " ", " ") - Loop - - If Not IsProcedure And Not IsEnumTypeBlock Then - Do While Declarations Like "*(*,*)*" - ' prevent multi-dimensional Dim from transforming into new declarations (might be numeric) - Pos = InStr(1, Declarations, "(") - PosX = InStr(Pos, Declarations, ")") - Declarations = Left(Declarations, Pos - 1) & " " & Mid(Declarations, PosX + 1) - Loop - End If - - DeclArray = Split(Trim(Declarations), ",") - - For i = LBound(DeclArray) To UBound(DeclArray) - Word = Trim(DeclArray(i)) - Pos = CutPos(Word) - If Pos > 1 Then - Word = Trim(Left(Word, Pos - 1)) - End If - If Len(Word) > 0 Then - AddWord Word - End If - Next - -End Sub - -Private Function CutPos(ByVal Expression As String) As Long - - Dim Pos As Long - Dim PosX As Long - - Const CutChars As String = " ()" - - Dim i As Long - - For i = 1 To Len(CutChars) - PosX = InStr(1, Expression, Mid(CutChars, i, 1)) - If PosX > 0 Then - If Pos = 0 Or PosX < Pos Then - Pos = PosX - End If - End If - Next - - CutPos = Pos - -End Function - Public Function ToString(Optional ByVal ShowAll As Boolean = False) As String Dim WordKey As Variant @@ -472,6 +262,9 @@ Public Sub FixLetterCase(ByVal WordWithNewLetterCase As String) With New CodeModulGenerator .CreateCodemodule vbext_ct_StdModule + If Left(WordWithNewLetterCase, 1) = "_" Then + WordWithNewLetterCase = "[" & WordWithNewLetterCase & "]" + End If .InsertDeclarationLine "Private " & WordWithNewLetterCase .RemoveCodemodule End With diff --git a/source/modules/FileTools.bas b/source/modules/FileTools.bas index 4bfebf0..92db18b 100644 --- a/source/modules/FileTools.bas +++ b/source/modules/FileTools.bas @@ -753,7 +753,7 @@ Public Sub AddToZipFile(ByVal ZipFile As String, ByVal FullFileName As String) End If With CreateObject("Shell.Application") - .NameSpace(ZipFile & "").CopyHere FullFileName & "" + .Namespace(ZipFile & "").CopyHere FullFileName & "" End With End Sub @@ -775,8 +775,8 @@ End Sub Public Function ExtractFromZipFile(ByVal ZipFile As String, ByVal Destination As String) As String With CreateObject("Shell.Application") - .NameSpace(Destination & "").CopyHere .NameSpace(ZipFile & "").Items - ExtractFromZipFile = .NameSpace(ZipFile & "").Items.Item(0).Name + .Namespace(Destination & "").CopyHere .Namespace(ZipFile & "").Items + ExtractFromZipFile = .Namespace(ZipFile & "").Items.Item(0).Name End With End Function diff --git a/source/modules/_AddInAPI.bas b/source/modules/_AddInAPI.bas index 9a57ac1..bdb1117 100644 --- a/source/modules/_AddInAPI.bas +++ b/source/modules/_AddInAPI.bas @@ -51,52 +51,59 @@ Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean Dim StoreDictData As Boolean Dim IntialCnt As Long - With New DeclarationDict - - If Len(DeclDictFilePath) = 0 Then - DeclDictFilePath = CurrentProject.Path & "\" & CurrentProject.Name & ".DeclarationDict.txt" - End If - - If Not .LoadFromFile(DeclDictFilePath) Then - .ImportVBProject CurrentVbProject - ' ... log info: first export - .ExportToFile DeclDictFilePath - RunVcsCheck = "Info: No dictionary data found. A new dictionary has been created." - Exit Function + Dim DeclDict As DeclarationDict + Set DeclDict = New DeclarationDict + + If Len(DeclDictFilePath) = 0 Then + DeclDictFilePath = CurrentProject.Path & "\" & CurrentProject.Name & ".DeclarationDict.txt" + End If + + If Not DeclDict.LoadFromFile(DeclDictFilePath) Then + ImportVBProject CurrentVbProject, DeclDict + ' ... log info: first export + DeclDict.ExportToFile DeclDictFilePath + RunVcsCheck = "Info: No dictionary data found. A new dictionary has been created." + Exit Function + End If + + IntialCnt = DeclDict.Count + ImportVBProject CurrentVbProject, DeclDict + + DiffCnt = DeclDict.DiffCount + If DiffCnt = 0 Then + If DeclDict.Count <> IntialCnt Then + StoreDictData = True End If + End If - IntialCnt = .Count - .ImportVBProject CurrentVbProject - - DiffCnt = .DiffCount - If DiffCnt = 0 Then - If .Count <> IntialCnt Then + If OpenDialogToFixLettercase Then + If DiffCnt > 0 Then + SetDeclarationDictTransferReference DeclDict + DoCmd.OpenForm "DeclarationDictApiDialog", , , , , acDialog + DiffCnt = DeclDict.DiffCount + If DiffCnt = 0 Then StoreDictData = True End If End If + End If - If OpenDialogToFixLettercase Then - If DiffCnt > 0 Then - SetDeclarationDictTransferReference .Self - DoCmd.OpenForm "DeclarationDictApiDialog", , , , , acDialog - DiffCnt = .DiffCount - If DiffCnt = 0 Then - StoreDictData = True - End If - End If - End If + If StoreDictData Then + DeclDict.ExportToFile DeclDictFilePath + End If - If StoreDictData Then - .ExportToFile DeclDictFilePath - End If + If DiffCnt > 0 Then + CheckMsg = DeclDict.DiffCount & " word" & IIf(DeclDict.DiffCount > 1, "s", vbNullString) & " with different letter case" + RunVcsCheck = "Failed: " & CheckMsg + Else + RunVcsCheck = True + End If - If DiffCnt > 0 Then - CheckMsg = .DiffCount & " word" & IIf(.DiffCount > 1, "s", vbNullString) & " with different letter case" - RunVcsCheck = "Failed: " & CheckMsg - Else - RunVcsCheck = True - End If +End Function + +Private Sub ImportVBProject(ByVal VbProjectToImport As VBIDE.VBProject, ByVal DeclDict As DeclarationDict) + With New CodemoduleDeclarationReader + .ImportVBProject VbProjectToImport, DeclDict End With -End Function +End Sub diff --git a/source/vcs-options.json b/source/vcs-options.json index c55c9fc..f66575f 100644 --- a/source/vcs-options.json +++ b/source/vcs-options.json @@ -1,6 +1,6 @@ { "Info": { - "AddinVersion": "4.1.2", + "AddinVersion": "4.1.3", "AccessVersion": "16.0 64-bit" }, "Options": { From 2607f7fc43ea0779ffe371f7a8940d28842f6228 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sun, 29 Jun 2025 17:19:04 +0200 Subject: [PATCH 2/8] Implemented: add members to dict (thanks to @hrschupp - see commit https://github.com/hrschupp/ACLibDeclarationDictionaryCore/commit/861031d695c236f3b7872f191e2d3a1570d35fca) --- .../modules/CodemoduleDeclarationReader.cls | 32 +++++++++++-------- source/modules/_AddInAPI.bas | 16 ++++++---- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/source/modules/CodemoduleDeclarationReader.cls b/source/modules/CodemoduleDeclarationReader.cls index e2245d2..47cfcd9 100644 --- a/source/modules/CodemoduleDeclarationReader.cls +++ b/source/modules/CodemoduleDeclarationReader.cls @@ -12,27 +12,27 @@ Option Explicit Private m_DeclDict As DeclarationDict -Public Sub ImportVBProject(ByVal VBProject2Import As VBProject, ByVal DeclDict As DeclarationDict) +Public Sub ImportVBProject(ByVal VBProject2Import As VBProject, ByVal DeclDict As DeclarationDict, Optional ByVal IncludeUsedMembers As Boolean = False) Dim vbc As VBComponent For Each vbc In VBProject2Import.VBComponents - ImportVBComponent vbc, DeclDict + ImportVBComponent vbc, DeclDict, IncludeUsedMembers Next End Sub -Public Sub ImportVBComponent(ByVal VBComponent2Import As VBComponent, ByVal DeclDict As DeclarationDict) - ImportCodeModule VBComponent2Import.CodeModule, DeclDict +Public Sub ImportVBComponent(ByVal VBComponent2Import As VBComponent, ByVal DeclDict As DeclarationDict, Optional ByVal IncludeUsedMembers As Boolean = False) + ImportCodeModule VBComponent2Import.CodeModule, DeclDict, IncludeUsedMembers End Sub -Public Sub ImportCodeModule(ByVal CodeModule2Import As CodeModule, ByVal DeclDict As DeclarationDict) +Public Sub ImportCodeModule(ByVal CodeModule2Import As CodeModule, ByVal DeclDict As DeclarationDict, Optional ByVal IncludeUsedMembers As Boolean = False) If CodeModule2Import.CountOfLines > 0 Then - ImportCode CodeModule2Import.Lines(1, CodeModule2Import.CountOfLines), DeclDict + ImportCode CodeModule2Import.Lines(1, CodeModule2Import.CountOfLines), DeclDict, IncludeUsedMembers End If End Sub -Public Sub ImportCode(ByVal Code As String, ByVal DeclDict As DeclarationDict) +Public Sub ImportCode(ByVal Code As String, ByVal DeclDict As DeclarationDict, Optional ByVal IncludeUsedMembers As Boolean = False) Dim RegEx As RegExp Set RegEx = NewRegExp @@ -43,17 +43,23 @@ Public Sub ImportCode(ByVal Code As String, ByVal DeclDict As DeclarationDict) Const ProcIndex As Long = 0 Const EnumTypeIndex As Long = 1 + Const DimIndex As Long = 2 - Dim Patterns(2) As String + Dim Patterns() As String + ReDim Patterns(2 + Abs(IncludeUsedMembers)) As String Patterns(ProcIndex) = "(?:\r|\n|^)\s*(?:Sub|Function|Property Get|Property Let|Property Set|Event)\s+([^\r\n]*)" Patterns(EnumTypeIndex) = "(?:\r|\n|^)\s*(?:Enum|Type)([\s\S]*?)(?:End\s+(?:Enum|Type))" Patterns(2) = "(?:\r|\n|^)\s*(?:Dim|ReDim|Private|Friend|Public|Const|Static|Global|Implements)\s+([^\r\n]*)" + If IncludeUsedMembers Then + 'see: https://github.com/hrschupp/ACLibDeclarationDictionaryCore/commit/861031d695c236f3b7872f191e2d3a1570d35fca#diff-0a954b2b22b447d5669ac2cc27824aef945ba74307ebf8c3c3c2c5dc67080afa + Patterns(3) = "(?:[.!])([^0-9\s.!_\(\)\[\]\r\n][^\s.!\(\)\[\]\r\n]*)(?:\s|[.!\(\)\[\]\r\n]|$)" + End If Dim i As Long For i = 0 To UBound(Patterns) RegEx.Pattern = Patterns(i) - AddFromCode Code, RegEx, i = ProcIndex, i = EnumTypeIndex + AddFromCode Code, RegEx, i = ProcIndex, i = EnumTypeIndex, i = DimIndex Next End Sub @@ -130,20 +136,20 @@ Private Function PrepareCode(ByVal Code As String, ByVal RegEx As RegExp) As Str End Function -Private Sub AddFromCode(ByVal Code As String, ByVal RegEx As RegExp, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) +Private Sub AddFromCode(ByVal Code As String, ByVal RegEx As RegExp, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean, ByVal IsDimBlock As Boolean) Dim Match As Match Dim i As Long For Each Match In RegEx.Execute(Code) For i = 0 To Match.SubMatches.Count - 1 - AddWordFromDeclaration Match.SubMatches(i), IsProcedure, IsEnumTypeBlock + AddWordFromDeclaration Match.SubMatches(i), IsProcedure, IsEnumTypeBlock, IsDimBlock Next Next End Sub -Private Sub AddWordFromDeclaration(ByRef Declarations As String, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean) +Private Sub AddWordFromDeclaration(ByRef Declarations As String, ByVal IsProcedure As Boolean, ByVal IsEnumTypeBlock As Boolean, ByVal IsDimBlock As Boolean) Dim Word As String Dim i As Long @@ -178,7 +184,7 @@ Private Sub AddWordFromDeclaration(ByRef Declarations As String, ByVal IsProcedu Declarations = Replace(Declarations, " ", " ") Loop - If Not (IsProcedure Or IsEnumTypeBlock) Then + If IsDimBlock Then Do While Declarations Like "*(*,*)*" ' prevent multi-dimensional Dim from transforming into new declarations (might be numeric) Pos = InStr(1, Declarations, "(") diff --git a/source/modules/_AddInAPI.bas b/source/modules/_AddInAPI.bas index bdb1117..e03605b 100644 --- a/source/modules/_AddInAPI.bas +++ b/source/modules/_AddInAPI.bas @@ -19,11 +19,11 @@ End Function ' Function: RunVcsCheckDialog '--------------------------------------------------------------------------------------- ' -' Equal to RunVcsCheck(True) +' Equal to RunVcsCheck(True, vbNullString, True) ' '--------------------------------------------------------------------------------------- Public Function RunVcsCheckDialog() As Variant - RunVcsCheckDialog = RunVcsCheck(True) + RunVcsCheckDialog = RunVcsCheck(True, , True) End Function @@ -43,7 +43,8 @@ End Function ' '--------------------------------------------------------------------------------------- Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean = False, _ - Optional ByVal DeclDictFilePath As String = vbNullString) As Variant + Optional ByVal DeclDictFilePath As String = vbNullString, _ + Optional ByVal IncludeUsedMembers As Boolean = False) As Variant Dim CheckMsg As String Dim DiffCnt As Long @@ -59,7 +60,7 @@ Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean End If If Not DeclDict.LoadFromFile(DeclDictFilePath) Then - ImportVBProject CurrentVbProject, DeclDict + ImportVBProject CurrentVbProject, DeclDict, IncludeUsedMembers ' ... log info: first export DeclDict.ExportToFile DeclDictFilePath RunVcsCheck = "Info: No dictionary data found. A new dictionary has been created." @@ -67,7 +68,7 @@ Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean End If IntialCnt = DeclDict.Count - ImportVBProject CurrentVbProject, DeclDict + ImportVBProject CurrentVbProject, DeclDict, IncludeUsedMembers DiffCnt = DeclDict.DiffCount If DiffCnt = 0 Then @@ -100,10 +101,11 @@ Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean End Function -Private Sub ImportVBProject(ByVal VbProjectToImport As VBIDE.VBProject, ByVal DeclDict As DeclarationDict) +Private Sub ImportVBProject(ByVal VbProjectToImport As VBIDE.VBProject, ByVal DeclDict As DeclarationDict, _ + Optional ByVal IncludeUsedMembers As Boolean = False) With New CodemoduleDeclarationReader - .ImportVBProject VbProjectToImport, DeclDict + .ImportVBProject VbProjectToImport, DeclDict, IncludeUsedMembers End With End Sub From 49c6b68dd60b3054ab9341c8bc8e981c104f8322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sun, 29 Jun 2025 17:25:50 +0200 Subject: [PATCH 3/8] upd. example file --- .gitignore | 5 ++++- Example_APIusage.accdb.src/modules/_LoadAddIn.bas | 6 ++++-- Example_APIusage.accdb.src/vcs-options.json | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 38de702..10ca69c 100644 --- a/.gitignore +++ b/.gitignore @@ -24,4 +24,7 @@ vcs-index.json # others *.dll -*.zip \ No newline at end of file +*.zip + +# don't commit dict files in this repository +*.accd[ab].DeclarationDict.txt \ No newline at end of file diff --git a/Example_APIusage.accdb.src/modules/_LoadAddIn.bas b/Example_APIusage.accdb.src/modules/_LoadAddIn.bas index 07ac9e2..4e02ab1 100644 --- a/Example_APIusage.accdb.src/modules/_LoadAddIn.bas +++ b/Example_APIusage.accdb.src/modules/_LoadAddIn.bas @@ -4,13 +4,15 @@ Option Explicit Public Sub LoadAddIn() -'API: RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean = False) +'API: Public Function RunVcsCheck(Optional ByVal OpenDialogToFixLettercase As Boolean = False, _ +' Optional ByVal DeclDictFilePath As String = vbNullString, _ +' Optional ByVal IncludeUsedMembers As Boolean = False) As Variant Dim AddInCallPath As String AddInCallPath = CurrentProject.Path & "\ACLibDeclarationDictCore.RunVcsCheck" Dim Result As Variant - Result = Application.Run(AddInCallPath, True) + Result = Application.Run(AddInCallPath, True, vbNullString, True) If Result = True Then Debug.Print "No problems with letter case" Else diff --git a/Example_APIusage.accdb.src/vcs-options.json b/Example_APIusage.accdb.src/vcs-options.json index ead0f48..0d34347 100644 --- a/Example_APIusage.accdb.src/vcs-options.json +++ b/Example_APIusage.accdb.src/vcs-options.json @@ -1,6 +1,6 @@ { "Info": { - "AddinVersion": "4.1.2", + "AddinVersion": "4.1.3", "AccessVersion": "16.0 64-bit" }, "Options": { From aa3bb78492d927fc0cebec7acecae01a1d0011c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Fri, 4 Jul 2025 16:24:32 +0200 Subject: [PATCH 4/8] minor code refactoring --- source/modVbProject.bas | 92 ++++++++++++++++++++++++++++++ source/modules/DeclarationDict.cls | 38 ++++++------ source/modules/FileTools.bas | 30 +--------- source/modules/modSort.bas | 2 +- 4 files changed, 114 insertions(+), 48 deletions(-) create mode 100644 source/modVbProject.bas diff --git a/source/modVbProject.bas b/source/modVbProject.bas new file mode 100644 index 0000000..c1a3705 --- /dev/null +++ b/source/modVbProject.bas @@ -0,0 +1,92 @@ +Attribute VB_Name = "modVbProject" +'--------------------------------------------------------------------------------------- +' Module: modVbProject +'--------------------------------------------------------------------------------------- +'/** +' +' VBProject ermitteln +' +' +' +' \ingroup base +'**/ +'--------------------------------------------------------------------------------------- +' +' %AppFolder%/source/modVbProject.bas +' _codelib/license.bas +' +'--------------------------------------------------------------------------------------- +' +Option Compare Text +Option Explicit +Option Private Module + +#Const EARLYBINDING = 1 + +Private m_CurrentVbProject As Object + +#If EARLYBINDING Then +Public Property Get CurrentVbProject() As VBIDE.VBProject +#Else +Public Property Get CurrentVbProject() As Object +#End If + +#If EARLYBINDING Then + Dim Proj As VBProject +#Else + Dim Proj As Object +#End If + Dim strCurrentDbName As String + + If m_CurrentVbProject Is Nothing Then + Set m_CurrentVbProject = Application.VBE.ActiveVBProject + If Application.VBE.VBProjects.Count > 1 Then + 'Prüfen, ob das richtige VbProject gewählt wurde (muss das von CurrentDb sein) + strCurrentDbName = UncPath(CurrentDb.Name) + If m_CurrentVbProject.FileName <> strCurrentDbName Then + Set m_CurrentVbProject = Nothing + For Each Proj In VBE.VBProjects + If Proj.FileName = strCurrentDbName Then + Set m_CurrentVbProject = Proj + Exit For + End If + Next + End If + End If + End If + + Set CurrentVbProject = m_CurrentVbProject + +End Property + + +#If EARLYBINDING Then +Public Property Get CodeVBProject() As VBIDE.VBProject +#Else +Public Property Get CodeVBProject() As Object +#End If + +#If EARLYBINDING Then + Dim Proj As VBProject +#Else + Dim Proj As Object +#End If + Dim strCodeDbName As String + Dim objCodeVbProject As Object + + Set objCodeVbProject = VBE.ActiveVBProject + 'Prüfen, ob das richtige VbProject gewählt wurde (muss das von CodeDb sein) + strCodeDbName = FileTools.UncPath(CodeDb.Name) + If objCodeVbProject.FileName <> strCodeDbName Then + Set objCodeVbProject = Nothing + For Each Proj In VBE.VBProjects + If Proj.FileName = strCodeDbName Then + Set objCodeVbProject = Proj + Exit For + End If + Next + End If + + Set CodeVBProject = objCodeVbProject + +End Property diff --git a/source/modules/DeclarationDict.cls b/source/modules/DeclarationDict.cls index d0ed720..3c36860 100644 --- a/source/modules/DeclarationDict.cls +++ b/source/modules/DeclarationDict.cls @@ -149,20 +149,20 @@ End Sub Public Function ToString(Optional ByVal ShowAll As Boolean = False) As String - Dim WordKey As Variant + Dim IdxWordKey As Variant Dim WordIndex As Long - Dim VariationsDict As Scripting.Dictionary + Dim IdxVariationsDict As Scripting.Dictionary Dim OutputString As String For WordIndex = 0 To m_Words.Count - 1 - WordKey = m_Words.Keys(WordIndex) - Set VariationsDict = m_Words.Item(WordKey) + IdxWordKey = m_Words.Keys(WordIndex) + Set IdxVariationsDict = m_Words.Item(IdxWordKey) - If VariationsDict.Count > (1 - Abs(ShowAll)) Then - OutputString = OutputString & vbNewLine & WordKey & ":" & GetWordVariationsOutputString(WordKey) + If IdxVariationsDict.Count > (1 - Abs(ShowAll)) Then + OutputString = OutputString & vbNewLine & IdxWordKey & ":" & GetWordVariationsOutputString(IdxWordKey) End If Next @@ -173,12 +173,12 @@ End Function Public Function ToDict(Optional ByVal ShowAll As Boolean = False) As Scripting.Dictionary - Dim WordKey As Variant + Dim IdxWordKey As Variant Dim WordIndex As Long Dim OutputWord As Boolean Dim VariationsString As String - Dim VariationsDict As Scripting.Dictionary + Dim IdxVariationsDict As Scripting.Dictionary Dim OutputDict As Scripting.Dictionary Set OutputDict = New Scripting.Dictionary @@ -187,19 +187,19 @@ Public Function ToDict(Optional ByVal ShowAll As Boolean = False) As Scripting.D For WordIndex = 0 To m_Words.Count - 1 - WordKey = m_Words.Keys(WordIndex) - Set VariationsDict = m_WordVariations.Item(WordKey) + IdxWordKey = m_Words.Keys(WordIndex) + Set IdxVariationsDict = m_WordVariations.Item(IdxWordKey) If Not ShowAll Then - OutputWord = IsChangedItem(WordKey, VariationsDict) + OutputWord = IsChangedItem(IdxWordKey, VariationsDict) End If If OutputWord Then - If VariationsDict.Count > 1 Then - VariationsString = GetWordVariationsOutputString(WordKey) + If IdxVariationsDict.Count > 1 Then + VariationsString = GetWordVariationsOutputString(IdxWordKey) Else VariationsString = vbNullString End If - OutputDict.Add WordKey, VariationsString + OutputDict.Add IdxWordKey, VariationsString End If Next @@ -220,19 +220,19 @@ Public Function GetWordVariations(ByVal Word As String, Optional ByVal IgnoreOri Dim VariantWord As String Dim AppendVariant As Boolean Dim i As Long, k As Long - Dim VariationsDict As Scripting.Dictionary + Dim WordVariationsDict As Scripting.Dictionary If StrComp(Word, m_Words.Item(Word), vbBinaryCompare) <> 0 Then Word = m_Words.Item(Word) End If - Set VariationsDict = m_WordVariations.Item(Word) - ReDim Variations(VariationsDict.Count - 1 - Abs(IgnoreOriginalWord)) + Set WordVariationsDict = m_WordVariations.Item(Word) + ReDim Variations(WordVariationsDict.Count - 1 - Abs(IgnoreOriginalWord)) AppendVariant = Not IgnoreOriginalWord - For i = 0 To VariationsDict.Count - 1 - VariantWord = VariationsDict.Keys(i) + For i = 0 To WordVariationsDict.Count - 1 + VariantWord = WordVariationsDict.Keys(i) If IgnoreOriginalWord Then AppendVariant = StrComp(Word, VariantWord, vbBinaryCompare) <> 0 End If diff --git a/source/modules/FileTools.bas b/source/modules/FileTools.bas index 92db18b..adaa21a 100644 --- a/source/modules/FileTools.bas +++ b/source/modules/FileTools.bas @@ -26,12 +26,12 @@ Option Private Module #If USELOCALIZATION_DE = 1 Then Private Const SELECTBOX_FILE_DIALOG_TITLE As String = "Datei auswählen" Private Const SELECTBOX_FOLDER_DIALOG_TITLE As String = "Ordner auswählen" -Private Const SELECTBOX_OPENTITLE As String = "auswählen" +Private Const SELECTBOX_OPENTITLE As String = "Auswählen" Private Const FILTERSTRING_ALL_FILES As String = "Alle Dateien (*.*)" #Else Private Const SELECTBOX_FILE_DIALOG_TITLE As String = "Select file" Private Const SELECTBOX_FOLDER_DIALOG_TITLE As String = "Select folder" -Private Const SELECTBOX_OPENTITLE As String = "auswählen" +Private Const SELECTBOX_OPENTITLE As String = "Select" Private Const FILTERSTRING_ALL_FILES As String = "All Files (*.*)" #End If @@ -43,8 +43,6 @@ Private Const SE_ERR_NOASSOC As Long = 31 Private Const VbaErrNo_FileNotFound As Long = 53 -#If VBA7 Then - Private Declare PtrSafe Function WNetGetConnection Lib "mpr.dll" Alias "WNetGetConnectionA" ( _ ByVal lpszLocalName As String, ByVal lpszRemoteName As String, cbRemoteName As Long) As Long @@ -66,30 +64,6 @@ Private Declare PtrSafe Function API_ShellExecuteA Lib "shell32.dll" Alias "Shel ByVal lpDirectory As String, _ ByVal nShowCmd As Long) As Long -#Else - -Private Declare Function WNetGetConnection Lib "mpr.dll" Alias "WNetGetConnectionA" ( _ - ByVal lpszLocalName As String, ByVal lpszRemoteName As String, cbRemoteName As Long) As Long - -Private Declare Function API_GetTempPath Lib "kernel32" Alias "GetTempPathA" ( _ - ByVal nBufferLength As Long, _ - ByVal lpBuffer As String) As Long - -Private Declare Function API_GetTempFilename Lib "kernel32" Alias "GetTempFileNameA" ( _ - ByVal lpszPath As String, _ - ByVal lpPrefixString As String, _ - ByVal wUnique As Long, _ - ByVal lpTempFileName As String) As Long - -Private Declare Function API_ShellExecuteA Lib "shell32.dll" Alias "ShellExecuteA" ( _ - ByVal Hwnd As Long, _ - ByVal lOperation As String, _ - ByVal lpFile As String, _ - ByVal lpParameters As String, _ - ByVal lpDirectory As String, _ - ByVal nShowCmd As Long) As Long - -#End If '--------------------------------------------------------------------------------------- ' Function: SelectFile diff --git a/source/modules/modSort.bas b/source/modules/modSort.bas index 51e5682..821becc 100644 --- a/source/modules/modSort.bas +++ b/source/modules/modSort.bas @@ -1,5 +1,5 @@ Attribute VB_Name = "modSort" -Option Compare Database +Option Compare Text Option Explicit Public Sub QuickSort(ByRef ArrToSort As Variant, ByVal FirstIndex As Long, ByVal LastIndex As Long) From dc3ab7af5391e1f69514d78c98b133593ae4d6c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sat, 21 Nov 2026 13:41:36 +0100 Subject: [PATCH 5/8] Fix ToString and GetWordVariations edge cases; adapt tests to reader ToString read the variations from m_Words instead of m_WordVariations and used the wrong output string variant. GetWordVariations failed with an invalid ReDim when no variation remained; it now returns an empty array. Tests now import code via CodemoduleDeclarationReader and cover ToString. --- .../DeclarationDictTests.cls | 50 +++++++++++++++---- source/modules/DeclarationDict.cls | 14 ++++-- 2 files changed, 52 insertions(+), 12 deletions(-) diff --git a/Tests/ACLibDeclarationDictCore/DeclarationDictTests.cls b/Tests/ACLibDeclarationDictCore/DeclarationDictTests.cls index 251812f..35d1deb 100644 --- a/Tests/ACLibDeclarationDictCore/DeclarationDictTests.cls +++ b/Tests/ACLibDeclarationDictCore/DeclarationDictTests.cls @@ -56,7 +56,10 @@ Public Sub ImportCode_InsertCodeLine_CheckKeys(ByVal Code As String, ByVal Expec Dim Actual As String - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With + 'm_DeclDict.ImportCode Code Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -73,7 +76,9 @@ Public Sub ImportCode_Issue4_MultiDimArrayDeclaration(ByVal Code As String, ByVa Dim Actual As String - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -89,7 +94,9 @@ Public Sub ImportCode_InsertCodeLines_CheckKeys(ByVal Code As String, ByVal Expe Dim Actual As String - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -101,7 +108,9 @@ Public Sub ImportCode_Issue3_RemovingCommentCorruptsLineEndings(ByVal Code As St Dim Actual As String - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -114,7 +123,9 @@ Public Sub ImportCode_Pullrequest8_LineLabel(ByVal Code As String, ByVal Expecte Dim Actual As String - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -135,7 +146,9 @@ Public Sub ImportCode_API_CheckKeys(ByVal Code As String, ByVal Expected As Stri ' RegEx.Pattern = "(?:Declare)\s(Function|Sub)\s([^ ]*)[^(]*\(" ' Actual = RegEx.Replace(Code, "$1 $2(") - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -156,7 +169,9 @@ Public Sub ImportCode_EnumCode_CheckKeys() Const Expected As String = "xyz|en1|en2|x|y" - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -177,7 +192,9 @@ Public Sub ImportCode_TypeCode_CheckKeys() Const Expected As String = "xyz|F1|F2|x|y" - m_DeclDict.ImportCode Code + With New CodemoduleDeclarationReader + .ImportCode Code, m_DeclDict + End With Actual = Join(m_DeclDict.WordsDict.Keys, "|") Assert.That Actual, Iz.EqualTo(Expected) @@ -211,7 +228,9 @@ Public Sub ImportClassCodeModule_CheckKeysExists() "TestPullrequest8_LineLabels", "ExitHere", "ErrHandler") - m_DeclDict.ImportVBComponent CurrentVbProject.VBComponents("DeclarationDictTestCodemodule") + With New CodemoduleDeclarationReader + .ImportVBComponent CurrentVbProject.VBComponents("DeclarationDictTestCodemodule"), m_DeclDict + End With Set ActualDict = m_DeclDict.WordsDict @@ -224,3 +243,16 @@ Public Sub ImportClassCodeModule_CheckKeysExists() End Sub +Public Sub ToString_AddWords_OutputVariations() + + m_DeclDict.AddWord "Test" + m_DeclDict.AddWord "test" + m_DeclDict.AddWord "xyz" + m_DeclDict.AddWord "xyz" + + Dim Actual As String + Actual = m_DeclDict.ToString(False) + + Assert.That Actual, Iz.EqualTo("Test:Test|test") + +End Sub diff --git a/source/modules/DeclarationDict.cls b/source/modules/DeclarationDict.cls index 3c36860..5c8fd5b 100644 --- a/source/modules/DeclarationDict.cls +++ b/source/modules/DeclarationDict.cls @@ -159,10 +159,10 @@ Public Function ToString(Optional ByVal ShowAll As Boolean = False) As String For WordIndex = 0 To m_Words.Count - 1 IdxWordKey = m_Words.Keys(WordIndex) - Set IdxVariationsDict = m_Words.Item(IdxWordKey) + Set IdxVariationsDict = m_WordVariations.Item(IdxWordKey) If IdxVariationsDict.Count > (1 - Abs(ShowAll)) Then - OutputString = OutputString & vbNewLine & IdxWordKey & ":" & GetWordVariationsOutputString(IdxWordKey) + OutputString = OutputString & vbNewLine & IdxWordKey & ":" & GetWordVariationsOutputString(IdxWordKey, False) End If Next @@ -221,13 +221,21 @@ Public Function GetWordVariations(ByVal Word As String, Optional ByVal IgnoreOri Dim AppendVariant As Boolean Dim i As Long, k As Long Dim WordVariationsDict As Scripting.Dictionary + Dim ResultCount As Long If StrComp(Word, m_Words.Item(Word), vbBinaryCompare) <> 0 Then Word = m_Words.Item(Word) End If Set WordVariationsDict = m_WordVariations.Item(Word) - ReDim Variations(WordVariationsDict.Count - 1 - Abs(IgnoreOriginalWord)) + + ResultCount = WordVariationsDict.Count - Abs(IgnoreOriginalWord) + If ResultCount < 1 Then + GetWordVariations = Split(vbNullString) ' leeres String-Array + Exit Function + End If + + ReDim Variations(ResultCount - 1) AppendVariant = Not IgnoreOriginalWord From 42945f01a9ff9b338d70c4f6d5e10d0fbf323aef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sat, 21 Nov 2026 13:41:36 +0100 Subject: [PATCH 6/8] Update VCS add-in options, gitignore and add agent docs --- .gitignore | 10 ++- source/AGENTS.md | 99 ++++++++++++++++++++ source/vcs-agent-docs/forms-reports.md | 105 ++++++++++++++++++++++ source/vcs-agent-docs/queries.md | 53 +++++++++++ source/vcs-agent-docs/testing.md | 110 +++++++++++++++++++++++ source/vcs-agent-docs/troubleshooting.md | 94 +++++++++++++++++++ source/vcs-agent-docs/vba-modules.md | 101 +++++++++++++++++++++ source/vcs-options.json | 66 +++++++++----- 8 files changed, 614 insertions(+), 24 deletions(-) create mode 100644 source/AGENTS.md create mode 100644 source/vcs-agent-docs/forms-reports.md create mode 100644 source/vcs-agent-docs/queries.md create mode 100644 source/vcs-agent-docs/testing.md create mode 100644 source/vcs-agent-docs/troubleshooting.md create mode 100644 source/vcs-agent-docs/vba-modules.md diff --git a/.gitignore b/.gitignore index 10ca69c..a747733 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -# gitattributes template for Microsoft Access database source files +# gitattributes template for Microsoft Access database source files # Website: https://github.com/joyfullservice/msaccess-vcs-addin # @@ -13,10 +13,14 @@ # The local VCS index file is paired with the binary database file # and should not be comitted to version control. -vcs-index.json +vcs-index.* # Ignore any dotenv files (used for external database connections) *.env +logs/ +test-results/ +.env.* +!.env*.example # Ignore log files generated by the VCS Add-in # Comment out the following line if you wish to include log files in git. @@ -27,4 +31,4 @@ vcs-index.json *.zip # don't commit dict files in this repository -*.accd[ab].DeclarationDict.txt \ No newline at end of file +*.accd[ab].DeclarationDict.txt diff --git a/source/AGENTS.md b/source/AGENTS.md new file mode 100644 index 0000000..f3d3495 --- /dev/null +++ b/source/AGENTS.md @@ -0,0 +1,99 @@ +# AGENTS.md - Working With Exported Microsoft Access Source Files + +This folder is a Microsoft Access database exported to text files by the MSAccess +VCS add-in. Editing these files is how you change the database, but edits only +take effect when the add-in imports them back in Access. You cannot run or test +this code directly, and the add-in is required to build a working database from it. + +This file and everything under `vcs-agent-docs/` are generated by the add-in and +**rewritten on every export**. Keep your own project notes elsewhere. + +## Non-negotiable rules + +1. **Do not change file encoding.** Source files are UTF-8, and most are UTF-8 + *with BOM* (bytes `EF BB BF`). Re-saving without the BOM makes import fail or + silently corrupt the object. +2. **Do not change line endings.** Access `LoadFromText` requires CRLF (`\r\n`). +3. **Do not edit** `vcs-index.idx` (binary change index), `.frx` files (binary OLE + data), or `.thmx` files (ZIP archives — edit the extracted contents instead). +4. **Do not rename a file** without changing the object name stored inside it. + File names must match object names exactly. +5. **Do not alter VBA scaffolding:** `Attribute VB_Name` lines, the + `VERSION`/`BEGIN`/`END` block at the top of a `.cls`, or module-level + `Attribute VB_*` lines. The code below them is yours to edit. + +## Which file do I edit? + +| To change | Edit | Read first | +|---|---|---| +| VBA in a standard module | `modules/.bas` | `vcs-agent-docs/vba-modules.md` | +| VBA in a class module | `modules/.cls` | `vcs-agent-docs/vba-modules.md` | +| Form or report code-behind | `forms/.cls`, `reports/.cls` | `vcs-agent-docs/vba-modules.md` | +| Form or report layout | `forms/.form`, `reports/.report` | `vcs-agent-docs/forms-reports.md` | +| Conditional formatting rules | the form's or report's companion `.json` | `vcs-agent-docs/forms-reports.md` | +| Query logic | `queries/.sql` — the sole source of truth for SQL | `vcs-agent-docs/queries.md` | +| Query properties or design layout | `queries/.json` | `vcs-agent-docs/queries.md` | +| A macro | `macros/.macro` | — | +| A table definition | `tbldefs/.xml` and `.json` | — | +| A connection string | `.env` at this folder's root (gitignored) | `vcs-agent-docs/troubleshooting.md` | +| Tests | a test module under `modules/` | `vcs-agent-docs/testing.md` | + +Export format 5.0.0 renamed several object types from the overloaded `.bas` +extension: forms to `.form`, reports to `.report`, macros to `.macro`, and queries +to `.sql` plus `.json`. Older projects still use `.bas` for these, so check which +extensions are actually present. Import accepts both. + +## File placement follows the `@Folder` annotation + +The add-in reads Rubberduck-style `'@Folder("Category")` annotations and exports +components into matching subdirectories, with dots as path separators: +`'@Folder("Components.ADP")` lands in `modules/Components/ADP/`. Components with no +annotation stay at the root of `modules/`, `forms/`, or `reports/`. Import scans +subdirectories recursively. + +**The annotation decides where the file belongs on disk, not the folder you happen +to be editing in.** This is the most common way agents corrupt a project: + +- For modules, the annotation is in the `.bas` or `.cls` itself. For forms and + reports it lives in the `.cls` code-behind only — not in `.form`/`.report`, + `.json`, or `.svg`. +- Before creating or moving a component, search the **entire** `modules/`, `forms/`, + or `reports/` tree for an existing file with the same base name (for modules, + match on `Attribute VB_Name`). Edit that file in place rather than creating a + second copy elsewhere. +- If two copies exist, such as `modules/modFoo.bas` and `modules/Tests/modFoo.bas`, + build imports **both** and the last one silently wins. No error is shown. +- Build removes a misplaced duplicate automatically when exactly one copy sits in + its annotation-derived folder. Ambiguous cases are left alone with a warning. + Removing a duplicate form or report deletes its whole source group together + (`.form`/`.report` plus `.cls`, `.json`, and `.svg`). + +To relocate a component, change its `'@Folder` annotation and let the next export +move the file. + +## Where the details live + +Each of these is short. Read the matching one before making that kind of change. + +| File | Read it before | +|---|---| +| `vcs-agent-docs/vba-modules.md` | Editing any `.bas` or `.cls`, or adding a member attribute | +| `vcs-agent-docs/forms-reports.md` | Editing a `.form` or `.report` layout, or conditional formatting | +| `vcs-agent-docs/queries.md` | Editing anything in `queries/` | +| `vcs-agent-docs/testing.md` | Writing, running, or filtering tests | +| `vcs-agent-docs/troubleshooting.md` | An import, build, or compile failed, or you need the log files | + +## How changes get back into Access + +Ask the user to run a **merge build** from the add-in ribbon, which imports changed +source files into the existing database. A **full build** creates a new database +from source instead, and **export** goes the other way, writing database objects +out to these files. When a source file and its database object have both changed, +the add-in detects the conflict and prompts the user to choose which version wins. + +## More information + +- [MSAccess VCS Add-in](https://github.com/joyfullservice/msaccess-vcs-addin) +- [Wiki: Export-Import File Types](https://github.com/joyfullservice/msaccess-vcs-addin/wiki/Export-Import-File-Types) +- [Wiki: Supported Objects](https://github.com/joyfullservice/msaccess-vcs-addin/wiki/Supported-Objects) +- [Wiki: Options](https://github.com/joyfullservice/msaccess-vcs-addin/wiki/Options) diff --git a/source/vcs-agent-docs/forms-reports.md b/source/vcs-agent-docs/forms-reports.md new file mode 100644 index 0000000..a6f0b2d --- /dev/null +++ b/source/vcs-agent-docs/forms-reports.md @@ -0,0 +1,105 @@ +# Form and Report Layout Files + +Covers `.form` and `.report` files (legacy projects use `.bas`) and their companion +`.json`. For the `.cls` code-behind, see `vba-modules.md`. + +## The SaveAsText format + +These files use Access's `SaveAsText` format. It is not VBA, and it is largely +undocumented: + +``` +Version =21 <- Access version marker +VersionRequired =20 +Begin Form <- Form or Report + RecordSelectors = NotDefault + Caption ="My Form Title" + Begin + Begin Label <- A control + Left =1234 + Top =567 + Width =2000 + Height =300 + Name ="lblTitle" + Caption ="Welcome" + End + Begin CommandButton + Name ="cmdOK" + Caption ="OK" + OnClick ="[Event Procedure]" + End + End +End +CodeBehindForm <- VBA section, when layout is not split +Attribute VB_Name = "Form_frmMyForm" +``` + +## What is safe to change + +Property edits are safe wherever you can infer the expected format from +neighboring values: caption text inside quotes, geometry such as `Left`, `Top`, +`Width`, and `Height`, colors, and font sizes. On forms (export format 5.1.0+), +layout-group geometry is rewritten to a 60-twip grid, so a track edit rewrites +sibling cells; do not drop `Left`/`Top`/`Width`/`Height` or `EmptyCell` spacers. +`LayoutCached*` is omitted on export. Guessing at a property whose format you +cannot infer breaks the layout or fails the import, so leave those alone, along +with the `Version` lines at the top. Keep `Begin`/`End` balanced throughout. + +## Adding, removing, and renaming controls + +Structural edits work if you copy rather than compose. The property set Access +expects for a control type is not something to invent, so use an existing +control of the same type in the same file as your template. + +To add a control: + +1. Copy an entire `Begin ` ... `End` block, including any nested + `Begin`/`End` subtree. An attached label lives *inside* its text box, combo + box, or check box, and an option group's buttons live inside the group. +2. Paste it into the intended section's inner `Begin` block. Appending at the + end of the section is the safest placement. +3. Give the new control, and every nested control copied with it, a `Name` that + is unique within the file. +4. Set the geometry. Raise the form `Width` and section `Height` if the new + control extends past them. On a Layout-view form, keep `LayoutGroup`, + `GroupTable`, and `RowStart`/`ColumnEnd` consistent with the row you copied. +5. Set `TabIndex` to a value not already used in that section. `TabIndex`, not + file order, determines tab order. +6. If you kept an event property such as `OnClick ="[Event Procedure]"`, add the + handler to the `.cls` code-behind. Access binds handlers by control name, so + `Private Sub cmdSave_Click()` pairs with `Name ="cmdSave"`. + +To remove a control, delete its whole block including nested children, then +remove its event handlers and any references to it from the `.cls`. + +Renaming means updating every reference to the old name: handler procedure names +and code in the `.cls`, and any key for that control in the companion `.json`. + +## Conditional formatting + +With **Decode conditional formatting to JSON** enabled (export format 5.0.0 and +later), the opaque `ConditionalFormat` and `ConditionalFormat14` hex blocks are +stripped out of each control and stored as readable rules in the companion `.json`, +under `Items.ConditionalFormatting` keyed by control name. Edit the rules there +rather than the hex. + +With the option disabled, the binary blocks stay inline in the layout file. Either +way the add-in rebuilds them on import. + +On import the JSON wins. If a control has a JSON entry, any stale inline block for +that control is stripped before the rebuilt block is injected, which keeps repeated +imports idempotent. A control with an inline block but no JSON entry is left +untouched. + +The binary layout and the exact boundary of what survives a decode/rebuild cycle +are documented in +[docs/access-conditional-format.md](https://github.com/joyfullservice/msaccess-vcs-addin/blob/dev/docs/access-conditional-format.md). + +## Recovering from a bad edit + +If a form or report looks wrong after import, the usual causes are an unbalanced +`Begin`/`End` pair or a mangled property value. Restore the `.form` or `.report` +file from git and redo the change in smaller steps. + +To check a structural edit, ask for a re-export after the merge build. A +`git diff` on the file then shows what Access normalized or dropped. diff --git a/source/vcs-agent-docs/queries.md b/source/vcs-agent-docs/queries.md new file mode 100644 index 0000000..1bc6a5c --- /dev/null +++ b/source/vcs-agent-docs/queries.md @@ -0,0 +1,53 @@ +# Query Source Files + +Each query in `queries/` is exported as two files: a `.sql` holding the statement, +and a `.json` holding everything that SQL cannot express. + +## Editing query logic + +Edit the `.sql`. It is the sole source of truth for the query's SQL text, and +changing it is the normal way to change what a query does. + +```sql +SELECT + CustomerID, + CustomerName, + Email +FROM tblCustomers +WHERE Active = True +ORDER BY CustomerName; +``` + +On import the add-in reads both files, generates a temporary `.qdef` in memory, and +hands it to `LoadFromText`. When the SQL is designer-compatible and the `.json` +carries layout data, the query imports in Design View format with table positions +preserved; otherwise it imports as SQL View. Making the SQL incompatible with the +designer — adding a `UNION` or a subquery, for example — causes the layout data to +be ignored and logs a warning, which is expected rather than an error. + +## The companion `.json` + +| Key | Meaning | +|-----|---------| +| `QueryType` | 0 Select, 16 Crosstab, 32 Delete, 48 Update, 64 Append | +| `Connect` | Connection string for pass-through queries, usually an `env:` reference | +| `QueryProperties` | Non-default query properties from the `LvProp` binary blob | +| `Columns` | Column metadata, sorted alphabetically for deterministic output | +| `DesignLayout` | Table positions and window dimensions; present only for queries last saved in Design View | +| `Description` | Object description from DAO document properties | +| `Hidden` | True when the query is hidden in the Navigation Pane | + +Edit these values directly when you need to change a property the SQL cannot carry. +Keep the file valid JSON. + +Pass-through `Connect` values use `env:` references rather than raw ODBC strings; +see `troubleshooting.md` for how those resolve. + +## Legacy files + +Older projects may still contain `.qdef` or `.bas` query files. Import still +accepts them. On export format 4.1.2 the `.bas` file is the import source; a +paired `.sql` is applied only when **Force import of original SQL for queries** +is enabled. To make `.sql` the source of truth, switch to export format 5.0+ +and run a full export — that writes `.sql` plus `.json` and removes the legacy +files. diff --git a/source/vcs-agent-docs/testing.md b/source/vcs-agent-docs/testing.md new file mode 100644 index 0000000..201e79b --- /dev/null +++ b/source/vcs-agent-docs/testing.md @@ -0,0 +1,110 @@ +# Automated Testing + +The add-in includes a test runner that discovers and executes tests in whatever +database is open. Tests assert with `TestAssert`, a drop-in replacement for +`Debug.Assert`. Nothing in the project needs a compile-time reference to the add-in. + +## Setup + +Run `VCS.InstallTestAssertModule` from the Immediate Window to inject the +`modTestAssert` module. `VCS.MigrateDebugAssert` converts existing `Debug.Assert` +calls in bulk. + +## Writing tests + +A test is a parameterless `Public Sub` in a test module: + +```vba +Option Compare Database +Option Explicit +Option Private Module +'@Folder("Tests") + +Public Sub TestDoubleInput() + TestAssert MyFunction(42) = 84, "MyFunction should double input" + TestAssert MyFunction(0) = 0, "Zero input returns zero" +End Sub +``` + +The second `TestAssert` argument is optional context that identifies which +assertion failed, which matters inside loops and shared helpers. + +A module counts as a test module if it carries `'@Folder("...Tests...")` (in +projects using `@Folder` at all) or its name contains `Test`. Within it, only +parameterless `Public Sub` procedures are registered, and only if the module has a +`TestAssert` call. To exclude a helper, make it `Private` or give it a parameter. + +**Class modules** work the same way and add per-test setup and teardown: every test +method gets a fresh instance, so `Class_Initialize` runs before it and +`Class_Terminate` after. Use parameterless `Public Sub` or `Public Function`. Name +test modules `modTest*` or `clsTest*`, and mark standard ones +`Option Private Module`. + +## Prompts during a run + +A run is unattended: a `MsgBox`, `InputBox`, or modal form in code a test reaches +stalls it until someone clicks. `modTestAssert.TestRunActive` is true for the whole +run, so guard anything that waits for a person: + +```vba +If Not TestRunActive Then MsgBox "Import complete.", vbInformation +``` + +Prefer guarding a prompt whose absence changes nothing; where a prompt decides +something, branch to the answer an unattended run should get. A `modTestAssert` +installed before this feature will not have the flag. + +## Running tests + +Run `?VCS.RunTests` from the Immediate Window, or use **Tools > Run Tests** on the +ribbon. After a completed run the runner can re-run only the failures. + +`RunTests` takes an optional `ParamArray` of filters. Each argument resolves in +priority order: exact module name, then suite or `@Folder` value (matching the full +path or its final segment, so `"SQL"` matches `"Tests.SQL"`), then procedure name or +full `Module.Procedure` key, then tag. Prefix an argument with `-` to exclude it. +Inclusions combine with OR, exclusions with AND, and a list containing only +exclusions starts from all tests. + +```vba +?VCS.RunTests("-slow") ' Everything except slow-tagged tests +?VCS.RunTests("Reporting", "-slow") ' The Reporting suite, skipping slow tests +?VCS.RunTests("TestInvoiceTotal") ' One specific procedure +``` + +`RunTests` returns a JSON summary with per-test status, assertion detail, and tags. + +## Tagging + +`'@Tag("name")` annotations categorize tests and are case-insensitive. A +module-level tag sits in the first ~30 lines, before any procedure, and applies to +every test in the module. A procedure-level tag sits at the very top of the +procedure body, before any executable line including `Dim`. The two sets merge. + +## Global suite hooks + +`modTestAssert` may define two optional once-per-run hooks: + +```vba +Public Sub GlobalTestSetup() ' Before the first test, when at least one is selected +Public Sub GlobalTestTeardown() ' After all tests; the results JSON already exists +``` + +`VCS.InstallTestAssertModule` writes empty stubs with inline guidance; if absent +the runner skips them silently. They do not run when no tests are discovered or a +filter matches nothing. An error inside a hook is non-fatal — it goes to the +console, the run continues, and teardown still executes. Per-test +`Class_Initialize` and `Class_Terminate` nest inside these hooks unchanged. + +## Where results land + +| File | Contents | +|------|----------| +| `logs/TestResults_.json` | Per-run results with per-assertion detail | +| `logs/TestRun_.log` | Full console output including timing | +| `test-results/test-state.json` | Merged current state; a partial run updates only the tests it executed and flags the rest `stale` | +| `test-results/test-results.xml` | JUnit XML projection of the state file | +| `test-results/test-results.html` | Self-contained HTML dashboard | + +Both folders are gitignored, so search tools will not find them. See +`troubleshooting.md` for how to list and read them. diff --git a/source/vcs-agent-docs/troubleshooting.md b/source/vcs-agent-docs/troubleshooting.md new file mode 100644 index 0000000..b4103c2 --- /dev/null +++ b/source/vcs-agent-docs/troubleshooting.md @@ -0,0 +1,94 @@ +# Troubleshooting and Logs + +## Reading the logs + +Every operation writes a timestamped log to the `logs/` subfolder. Check the most +recent one first; it carries the detailed output, timing, and error messages. + +| Pattern | Operation | +|---------|-----------| +| `Export_.log` | Export | +| `Build_.log` | Full build | +| `Merge_.log` | Merge build **and** single-object import | +| `TestRun_.log` | Test run console output | + +A single-object import that seems to have produced no log wrote a `Merge_*.log`. + +**`logs/` and `test-results/` are gitignored**, so tools that respect `.gitignore` +— glob, grep, and semantic search — will silently skip them. Use the shell: + +```powershell +Get-ChildItem -Path "logs" | Sort-Object LastWriteTime -Descending | Select-Object -First 3 +Get-ChildItem -Path "test-results" +``` + +## Import fails with no clear error + +Almost always the encoding changed. Confirm the file still begins with the bytes +`EF BB BF` and re-save it as UTF-8 with BOM. + +## Import fails or objects are corrupted after an edit + +Check the line endings. The file needs CRLF (`0D 0A`), not bare LF. Restore it from +git or re-save with CRLF. + +## Unresolved Git conflict markers + +After a `git merge`, `git stash pop`, or branch switch, a source file may still +contain lines starting with `<<<<<<<` or `>>>>>>>`. The add-in skips that file and +logs: + +`Unresolved Git conflict markers in '' (line N). Resolve the conflict in this +file, then merge again.` + +Open the named file, resolve every conflict section, remove the marker lines, save, +and run merge again. + +## "Object not found" after import + +The `Attribute VB_Name` inside the file no longer matches the filename, usually +because the file was renamed without updating the name stored in it. Make them +agree, without the extension. + +## VBA compile error after import + +Typical causes are a syntax error introduced by an edit, a missing declaration, or +a reference to something that does not exist. + +The compile tools available over MCP report only success or failure — never the +failing module or line. When `vcs_compile_vba` returns `success: false`, or +`vcs_check_vba_compiled` returns `compiled: false`: + +1. Stop. Do not edit more source files or guess at a fix. +2. Ask the user to open the database in Access, open the VBA editor, and choose + **Debug > Compile**. Access jumps to the first error. +3. Ask them to paste the few lines around it. The snippet is usually enough; the + error text is optional. +4. Propose a targeted fix, then re-import and re-compile. + +Working in Access directly, the highlighted line after **Debug > Compile** tells +you the same thing. + +## XML parse error + +Invalid syntax such as an unclosed tag, or an unescaped special character. Validate +the structure and check how special characters are encoded. + +## Build prompts for SQL authentication + +Linked tables and pass-through queries store `env:conn_*` references rather than raw +ODBC strings, in `tbldefs/*.json`, the `Connect` value in `queries/*.json`, and +`db-connection.json`. At build time the add-in resolves each reference against the +`.env` file at this folder's root, which is per-developer and gitignored. + +A prompt means the key is missing from the resolved configuration or the server is +unreachable. Search the build log for `Connection key not found in .env file:`. + +`db-connection.json` only **primes** Access's ODBC cache during import, running one +temporary query per connection so later linked-table imports reuse the cached +credentials. It stores `env:` keys, not connection strings, so do not treat it as a +registry of connections. + +Per-environment layering through an `APP_ENV` selector is supported and documented +in the +[Connections wiki page](https://github.com/joyfullservice/msaccess-vcs-addin/wiki/Connections). diff --git a/source/vcs-agent-docs/vba-modules.md b/source/vcs-agent-docs/vba-modules.md new file mode 100644 index 0000000..3da8b3d --- /dev/null +++ b/source/vcs-agent-docs/vba-modules.md @@ -0,0 +1,101 @@ +# VBA Module Source Files + +Covers `.bas` and `.cls` files in `modules/`, and the `.cls` code-behind files in +`forms/` and `reports/`. + +## Standard modules (`.bas`) + +``` +Attribute VB_Name = "ModuleName" <- Required: must match the filename +'--------------------------------------------------------------------------------------- +' Module : ModuleName <- Optional comment header +' Purpose : Description here +'--------------------------------------------------------------------------------------- +Option Compare Database <- Optional +Option Explicit <- Optional + +Public Sub MySub() + ' Code starts after any Option statements +End Sub +``` + +Add and edit procedures, functions, and declarations freely. Leave the +`Attribute VB_Name` line alone; it must equal the filename without its extension. + +`Option` statements are not required. Some projects omit them entirely, so match +whatever the surrounding modules do rather than adding them. + +## Class modules (`.cls`) + +``` +VERSION 1.0 CLASS <- Required header block +BEGIN + MultiUse = -1 'True +END +Attribute VB_Name = "ClassName" <- Required: must match the filename +Attribute VB_GlobalNameSpace = False <- Required (legacy, but must be present) +Attribute VB_Creatable = False +Attribute VB_PredeclaredId = False <- True gives the class a default instance +Attribute VB_Exposed = False <- True exposes it to other projects +Option Compare Database <- Optional +Option Explicit <- Optional + +Private m_Value As String + +Public Property Get Value() As String +Attribute Value.VB_Description = "Returns the value" <- Member attribute + Value = m_Value +End Property +``` + +Edit the code and comment headers. Leave the `VERSION` block and the module-level +`Attribute VB_*` lines exactly as they are. + +## Member attributes + +Attributes can also appear **inside** procedures and properties, carrying metadata +that the VBA editor hides but the Object Browser displays. They go on the line +immediately after the `Sub`, `Function`, or `Property` declaration: + +```vba +Public Function GetItem(Index As Long) As Variant +Attribute GetItem.VB_Description = "Returns item at specified index" +Attribute GetItem.VB_UserMemId = 0 + GetItem = m_Items(Index) +End Function +``` + +| Attribute | Effect | +|-----------|--------| +| `Attribute [Member].VB_Description = "text"` | Description shown in the Object Browser | +| `Attribute [Member].VB_UserMemId = 0` | Makes this the class's default member | +| `Attribute [Member].VB_UserMemId = -4` | Returns an enumerator, enabling `For Each` | + +Reword the description text if it is wrong. Do not change the attribute syntax or +the member name it refers to; the name must match the procedure it sits under. + +## Form and report code-behind + +When the **Split Layout from VBA** option is on, a form's or report's code lives in +its own `.cls` beside the layout file: + +``` +VERSION 1.0 CLASS +BEGIN + MultiUse = -1 'True +END +Attribute VB_Name = "Form_frmMyForm" <- Must be "Form_" (or "Report_") + object name +Attribute VB_GlobalNameSpace = False +Attribute VB_Creatable = True +Attribute VB_PredeclaredId = True +Attribute VB_Exposed = False +Option Compare Database + +Private Sub Form_Load() + ' Event handler code +End Sub +``` + +Edit event handlers and procedures here as you would in any class module. When the +option is off, the code is instead inside the `.form` or `.report` file under a +`CodeBehindForm` line. diff --git a/source/vcs-options.json b/source/vcs-options.json index f66575f..a712fa4 100644 --- a/source/vcs-options.json +++ b/source/vcs-options.json @@ -1,15 +1,25 @@ { "Info": { - "AddinVersion": "4.1.3", + "AddinVersion": "5.1.0", "AccessVersion": "16.0 64-bit" }, "Options": { "ExportFolder": "\\source", - "ShowDebug": false, "UseFastSave": true, - "UseMergeBuild": false, - "UseGitIntegration": false, + "SplitLayoutFromVBA": true, + "ExportFormatVersion": "4.1.2", + "RunBeforeExport": "", + "RunAfterExport": "", + "SanitizeLevel": 2, + "SanitizeColors": 1, + "SaveQuerySQL": true, + "FormatSQL": true, + "UseDeterministicQueryExport": true, + "SaveTableSQL": true, "SavePrintVars": false, + "DecodeConditionalFormatting": true, + "ExtractThemeFiles": false, + "UseEnvForConnections": 0, "ExportPrintSettings": { "Orientation": true, "PaperSize": true, @@ -32,15 +42,19 @@ "PaperWidth": false, "TTOption": false }, - "SaveQuerySQL": true, - "FormatSQL": true, + "ExportLayoutSvg": false, + "LayoutSvgImageEmbed": "Small", + "LayoutSvgScaleMode": "Universal", + "ExportAfterMerge": false, "ForceImportOriginalQuerySQL": false, - "SaveTableSQL": true, - "SplitLayoutFromVBA": true, - "StripPublishOption": true, - "SanitizeColors": 1, - "SanitizeLevel": 2, - "ExtractThemeFiles": false, + "UseMergeBuild": false, + "MergeTableData": true, + "SkipReopenBeforeMerge": false, + "RunBeforeBuild": "", + "RunAfterBuild": "", + "RunBeforeMerge": "", + "RunAfterMerge": "", + "ValidateAfterBuild": "", "TablesToExportData": { "USysAPI": { "Format": "XML Format" @@ -54,16 +68,26 @@ }, "SchemaExports": { }, - "RunBeforeExport": "", - "RunAfterExport": "", - "RunBeforeBuild": "", - "RunAfterBuild": "", - "RunBeforeMerge": "", - "RunAfterMerge": "", - "ShowVCSLegacy": true, + "McpAllowImport": true, + "McpAllowCallVBA": true, + "McpAllowExecuteSQL": true, + "McpAllowRunVBA": false, + "DefaultTestFilter": "", + "ShowDebug": false, + "BreakOnError": false, + "MaxLogFiles": 20, + "StripPublishOption": true, + "PreserveRubberDuckID": false, + "SaveAllDocumentProperties": false, + "SaveLinkedTableDef": false, "HashAlgorithm": "SHA256", "UseShortHash": true, - "BreakOnError": false, - "PreserveRubberDuckID": false + "UseGitIntegration": false, + "ShowVCSLegacy": true, + "UseWebTestRunner": true, + "ExportTestResultsJUnit": true, + "ExportTestResultsHtml": true, + "ExportPerfJson": false, + "McpProgressIntervalMs": 500 } } From 11b5eaea7e3300f3fa42a84e608fa3374f18e344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sat, 21 Nov 2026 13:45:44 +0100 Subject: [PATCH 7/8] Switch VCS export to format 5.1.0 Forms and reports are now exported as .form/.report (plus .json layout), table definition properties are sorted, and SummaryInfo uses typed values. --- source/dbs-properties.json | 4 +- source/documents.json | 20 ++- ...alog.bas => DeclarationDictApiDialog.form} | 136 ++++-------------- source/forms/DeclarationDictApiDialog.json | 62 ++++++++ .../{InfoFormAPI.bas => InfoFormAPI.form} | 10 +- ...InfoReportAPI.bas => InfoReportAPI.report} | 0 source/tbldefs/USysAPI.xml | 72 +++++----- source/vcs-options.json | 2 +- 8 files changed, 148 insertions(+), 158 deletions(-) rename source/forms/{DeclarationDictApiDialog.bas => DeclarationDictApiDialog.form} (68%) create mode 100644 source/forms/DeclarationDictApiDialog.json rename source/forms/{InfoFormAPI.bas => InfoFormAPI.form} (95%) rename source/reports/{InfoReportAPI.bas => InfoReportAPI.report} (100%) diff --git a/source/dbs-properties.json b/source/dbs-properties.json index 4528173..c12a5db 100644 --- a/source/dbs-properties.json +++ b/source/dbs-properties.json @@ -101,7 +101,7 @@ "Type": 4 }, "NavPane Width": { - "Value": 678, + "Value": 540, "Type": 4 }, "Never Cache": { @@ -205,7 +205,7 @@ "Type": 2 }, "Version": { - "Value": "14.0", + "Value": "12.0", "Type": 12 }, "WebDesignMode": { diff --git a/source/documents.json b/source/documents.json index f7097aa..758ccf9 100644 --- a/source/documents.json +++ b/source/documents.json @@ -6,10 +6,22 @@ "Items": { "Databases": { "SummaryInfo": { - "Author": "Josef Pötzl", - "Comments": "* List of declarations\r\n* Save to / load from table or file\r\n* Compare and repair letter case", - "Company": "access-codelib.net", - "Title": "ACLib Declaration Dictionary" + "Author": { + "Type": 10, + "Value": "Josef Pötzl" + }, + "Comments": { + "Type": 10, + "Value": "* List of declarations\r\n* Save to / load from table or file\r\n* Compare and repair letter case" + }, + "Company": { + "Type": 10, + "Value": "access-codelib.net" + }, + "Title": { + "Type": 10, + "Value": "ACLib Declaration Dictionary" + } } } } diff --git a/source/forms/DeclarationDictApiDialog.bas b/source/forms/DeclarationDictApiDialog.form similarity index 68% rename from source/forms/DeclarationDictApiDialog.bas rename to source/forms/DeclarationDictApiDialog.form index 05feb0c..1db0cf3 100644 --- a/source/forms/DeclarationDictApiDialog.bas +++ b/source/forms/DeclarationDictApiDialog.form @@ -13,13 +13,13 @@ Begin Form DatasheetGridlinesBehavior =3 Cycle =1 GridY =10 - Width =10148 + Width =10140 DatasheetFontHeight =11 ItemSuffix =88 - Left =5811 - Top =3026 - Right =24429 - Bottom =14117 + Left =1000 + Top =1000 + Right =50000 + Bottom =50000 RecSrcDt = Begin 0x1b36415d9252e640 End @@ -142,7 +142,7 @@ Begin Form GridlineShade =65.0 End Begin Section - Height =4649 + Height =4620 Name ="Detail" AlternateBackThemeColorIndex =1 AlternateBackShade =95.0 @@ -168,19 +168,15 @@ Begin Form AllowValueListEdits =0 InheritValueList =0 - LayoutCachedLeft =60 - LayoutCachedTop =57 - LayoutCachedWidth =5476 - LayoutCachedHeight =4593 End Begin ListBox RowSourceTypeInt =1 OverlapFlags =85 IMESentenceMode =3 - Left =5674 - Top =1397 + Left =5640 + Top =1380 Width =4380 - Height =1354 + Height =1320 TabIndex =3 ForeColor =0 Name ="lbVariations" @@ -196,10 +192,6 @@ Begin Form AllowValueListEdits =0 InheritValueList =0 - LayoutCachedLeft =5674 - LayoutCachedTop =1397 - LayoutCachedWidth =10054 - LayoutCachedHeight =2751 RowStart =4 RowEnd =4 ColumnEnd =1 @@ -214,36 +206,20 @@ Begin Form OverlapFlags =85 TextAlign =1 IMESentenceMode =3 - Left =5674 + Left =5640 Top =60 Width =4380 - Height =317 + Height =300 FontWeight =700 TabIndex =1 Name ="txtWord" ControlSource ="=[lbDictData]" Format ="@;;\"(select item)\"" - ConditionalFormat = Begin - 0x0100000086000000010000000100000000000000000000001200000001000000 , - 0xbfbfbf00ffffff00000000000000000000000000000000000000000000000000 , - 0x0000000000000000000000000000000000000000000000000000000000000000 , - 0x5b0074007800740057006f00720064005d0020004900730020004e0075006c00 , - 0x6c0000000000 - End GroupTable =1 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =60 - LayoutCachedWidth =10054 - LayoutCachedHeight =377 ColumnEnd =1 LayoutGroup =1 - ConditionalFormat14 = Begin - 0x010001000000010000000000000001000000bfbfbf00ffffff00110000005b00 , - 0x74007800740057006f00720064005d0020004900730020004e0075006c006c00 , - 0x000000000000000000000000000000000000000000 - End GroupTable =1 End Begin CommandButton @@ -271,22 +247,13 @@ Begin Form OverlapFlags =85 TextAlign =1 IMESentenceMode =3 - Left =5674 - Top =737 + Left =5640 + Top =720 Width =4380 Height =300 TabIndex =2 Name ="txtCurrentLetterCase" Format ="@;;---" - ConditionalFormat = Begin - 0x01000000dc000000020000000100000000000000000000001200000001000000 , - 0xbfbfbf00ffffff000100000000000000130000003d00000001010000ba141900 , - 0xffffff0000000000000000000000000000000000000000000000000000000000 , - 0x5b0074007800740057006f00720064005d0020004900730020004e0075006c00 , - 0x6c000000000053007400720043006f006d00700028005b007400780074005700 , - 0x6f00720064005d002c005b00740078007400430075007200720065006e007400 , - 0x560061006c00750065005d002c00300029003c003e00300000000000 - End GroupTable =1 TopPadding =0 GridlineWidthLeft =0 @@ -295,30 +262,17 @@ Begin Form GridlineWidthBottom =0 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =737 - LayoutCachedWidth =10054 - LayoutCachedHeight =1037 RowStart =2 RowEnd =2 ColumnEnd =1 LayoutGroup =1 - ConditionalFormat14 = Begin - 0x010002000000010000000000000001000000bfbfbf00ffffff00110000005b00 , - 0x74007800740057006f00720064005d0020004900730020004e0075006c006c00 , - 0x0000000000000000000000000000000000000000000100000000000000010100 , - 0x00ba141900ffffff002900000053007400720043006f006d00700028005b0074 , - 0x007800740057006f00720064005d002c005b0074007800740043007500720072 , - 0x0065006e007400560061006c00750065005d002c00300029003c003e00300000 , - 0x0000000000000000000000000000000000000000 - End GroupTable =1 End Begin Label OverlapFlags =85 TextAlign =1 - Left =5674 - Top =437 + Left =5640 + Top =420 Width =4380 Height =300 Name ="Label19" @@ -326,10 +280,6 @@ Begin Form GroupTable =1 BottomPadding =0 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =437 - LayoutCachedWidth =10054 - LayoutCachedHeight =737 RowStart =1 RowEnd =1 ColumnEnd =1 @@ -339,8 +289,8 @@ Begin Form Begin Label OverlapFlags =85 TextAlign =1 - Left =5674 - Top =1097 + Left =5640 + Top =1080 Width =4380 Height =300 Name ="Label20" @@ -348,10 +298,6 @@ Begin Form GroupTable =1 BottomPadding =0 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =1097 - LayoutCachedWidth =10054 - LayoutCachedHeight =1397 RowStart =3 RowEnd =3 ColumnEnd =1 @@ -365,44 +311,28 @@ Begin Form OverlapFlags =85 TextAlign =1 IMESentenceMode =3 - Left =5674 - Top =3111 - Width =3403 - Height =343 + Left =5640 + Top =3120 + Width =3420 + Height =360 TabIndex =4 Name ="txtSelectedLetterCase" ControlSource ="=[lbVariations]" Format ="@;;---" - ConditionalFormat = Begin - 0x0100000086000000010000000100000000000000000000001200000001000000 , - 0xbfbfbf00ffffff00000000000000000000000000000000000000000000000000 , - 0x0000000000000000000000000000000000000000000000000000000000000000 , - 0x5b0074007800740057006f00720064005d0020004900730020004e0075006c00 , - 0x6c0000000000 - End GroupTable =1 TopPadding =0 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =3111 - LayoutCachedWidth =9077 - LayoutCachedHeight =3454 RowStart =6 RowEnd =6 LayoutGroup =1 - ConditionalFormat14 = Begin - 0x010001000000010000000000000001000000bfbfbf00ffffff00110000005b00 , - 0x74007800740057006f00720064005d0020004900730020004e0075006c006c00 , - 0x000000000000000000000000000000000000000000 - End GroupTable =1 End Begin Label OverlapFlags =85 TextAlign =1 - Left =5674 - Top =2777 + Left =5640 + Top =2760 Width =4380 Height =300 Name ="Label45" @@ -410,10 +340,6 @@ Begin Form GroupTable =1 TopPadding =0 HorizontalAnchor =1 - LayoutCachedLeft =5674 - LayoutCachedTop =2777 - LayoutCachedWidth =10054 - LayoutCachedHeight =3077 RowStart =5 RowEnd =5 ColumnEnd =1 @@ -423,10 +349,10 @@ Begin Form Begin CommandButton Enabled = NotDefault OverlapFlags =85 - Left =9137 - Top =3111 - Width =917 - Height =343 + Left =9120 + Top =3120 + Width =900 + Height =360 TabIndex =5 Name ="cmdChangeLetterCase" Caption ="Commit" @@ -435,10 +361,6 @@ Begin Form TopPadding =0 HorizontalAnchor =1 - LayoutCachedLeft =9137 - LayoutCachedTop =3111 - LayoutCachedWidth =10054 - LayoutCachedHeight =3454 RowStart =6 RowEnd =6 ColumnStart =1 @@ -464,10 +386,6 @@ Begin Form FontSize =8 Name ="lblVersionInfo" HorizontalAnchor =2 - LayoutCachedLeft =5555 - LayoutCachedTop =4370 - LayoutCachedWidth =10105 - LayoutCachedHeight =4593 End End End diff --git a/source/forms/DeclarationDictApiDialog.json b/source/forms/DeclarationDictApiDialog.json new file mode 100644 index 0000000..7c630d8 --- /dev/null +++ b/source/forms/DeclarationDictApiDialog.json @@ -0,0 +1,62 @@ +{ + "Info": { + "Class": "clsDbForm", + "Description": "DeclarationDictApiDialog Conditional Formatting" + }, + "Items": { + "ConditionalFormatting": { + "txtWord": { + "Rules": [ + { + "Type": "Expression", + "Enabled": true, + "FontBold": false, + "FontItalic": false, + "FontUnderline": false, + "ForeColor": "RGB(191,191,191)", + "BackColor": "RGB(255,255,255)", + "Expression1": "[txtWord] Is Null" + } + ] + }, + "txtCurrentLetterCase": { + "Rules": [ + { + "Type": "Expression", + "Enabled": true, + "FontBold": false, + "FontItalic": false, + "FontUnderline": false, + "ForeColor": "RGB(191,191,191)", + "BackColor": "RGB(255,255,255)", + "Expression1": "[txtWord] Is Null" + }, + { + "Type": "Expression", + "Enabled": true, + "FontBold": true, + "FontItalic": false, + "FontUnderline": false, + "ForeColor": "RGB(186,20,25)", + "BackColor": "RGB(255,255,255)", + "Expression1": "StrComp([txtWord],[txtCurrentValue],0)<>0" + } + ] + }, + "txtSelectedLetterCase": { + "Rules": [ + { + "Type": "Expression", + "Enabled": true, + "FontBold": false, + "FontItalic": false, + "FontUnderline": false, + "ForeColor": "RGB(191,191,191)", + "BackColor": "RGB(255,255,255)", + "Expression1": "[txtWord] Is Null" + } + ] + } + } + } +} diff --git a/source/forms/InfoFormAPI.bas b/source/forms/InfoFormAPI.form similarity index 95% rename from source/forms/InfoFormAPI.bas rename to source/forms/InfoFormAPI.form index 94c7565..2d4e373 100644 --- a/source/forms/InfoFormAPI.bas +++ b/source/forms/InfoFormAPI.form @@ -21,10 +21,10 @@ Begin Form Width =9072 DatasheetFontHeight =11 ItemSuffix =4 - Left =7620 - Top =3045 - Right =20775 - Bottom =14775 + Left =1000 + Top =1000 + Right =50000 + Bottom =50000 RecSrcDt = Begin 0x9487851a5859e640 End @@ -105,8 +105,6 @@ Begin Form HorizontalAnchor =2 VerticalAnchor =2 - LayoutCachedWidth =9072 - LayoutCachedHeight =6804 End End End diff --git a/source/reports/InfoReportAPI.bas b/source/reports/InfoReportAPI.report similarity index 100% rename from source/reports/InfoReportAPI.bas rename to source/reports/InfoReportAPI.report diff --git a/source/tbldefs/USysAPI.xml b/source/tbldefs/USysAPI.xml index ab8918d..7ab7d81 100644 --- a/source/tbldefs/USysAPI.xml +++ b/source/tbldefs/USysAPI.xml @@ -12,24 +12,24 @@ - - + + + + + + + - - - - - - - - + + + - - + + @@ -37,19 +37,19 @@ - - - - + + + + + - - - + - + + @@ -61,20 +61,20 @@ - - - - + + + + + + - - - - - + - + + + @@ -86,16 +86,16 @@ - - + + + + - - - + - + diff --git a/source/vcs-options.json b/source/vcs-options.json index a712fa4..5e5b96c 100644 --- a/source/vcs-options.json +++ b/source/vcs-options.json @@ -7,7 +7,7 @@ "ExportFolder": "\\source", "UseFastSave": true, "SplitLayoutFromVBA": true, - "ExportFormatVersion": "4.1.2", + "ExportFormatVersion": "5.1.0", "RunBeforeExport": "", "RunAfterExport": "", "SanitizeLevel": 2, From 6c6743cf73f1587b8ba597a65f1ac9777835f7ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Josef=20P=C3=B6tzl?= Date: Sat, 21 Nov 2026 13:53:43 +0100 Subject: [PATCH 8/8] Bump version to 0.6.0 --- source/modules/modApiDialogSupport.bas | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/modules/modApiDialogSupport.bas b/source/modules/modApiDialogSupport.bas index a1502d2..72de99e 100644 --- a/source/modules/modApiDialogSupport.bas +++ b/source/modules/modApiDialogSupport.bas @@ -4,7 +4,7 @@ Option Explicit Option Private Module Public Const DeclDictAddInName As String = "ACLib Declaration Dictionary" -Public Const DeclDictVersion As String = "0.5.0" +Public Const DeclDictVersion As String = "0.6.0" Private m_DeclarationDict As DeclarationDict