mirror of
https://github.com/Nikolay-Shirokov/cc-1c-skills.git
synced 2026-09-01 16:00:51 +03:00
refactor(skills): регистрация в ChildObjects — именованная функция под анти-дрейфом
Три навыка делали одну работу тремя инлайновыми копиями в main(), и одна копия молча разъехалась: role-compile.py рапортовал об успехе, не тронув файл. Это ровно тот класс, от которого заведён check-inline-drift.mjs, но в реестр регистрацию было не записать — он работает по именованным функциям. Регистрация вынесена в Register-InChildObjects / register_in_childobjects с контрактом (родительский XML, тег родителя, тег потомка, имя) и исходом added | already | no-childobj | no-config. Печать сообщений осталась на вызывающей стороне: тексты у навыков разные, и сведение их меняло бы вывод. Эталон — meta-compile, форма функции задана на .ps1. role-compile берёт его тело копией, и гард это подтверждает. subsystem-compile идёт отдельным вариантом с обоснованием: родителем бывает вложенный Subsystem.xml произвольной глубины, поэтому отступ он берёт из документа, а запись дописывает в конец блока — фиксированные три табуляции там неверны, и группировать по типу нечего. Вынос поведенчески нейтрален: 837 кейсов зелёные на обоих рантаймах, снэпшоты не дрейфовали, матрица «навык × порт × изломанная форма Configuration.xml» даёт те же исходы, а порты — байт-в-байт одинаковый файл. Попутно из subsystem-compile.py убран мёртвый ET.SubElement перед pass: дерево мутировалось и выбрасывалось, правка идёт по сырому тексту. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
2b0ac3ea75
commit
1c63d9ddcc
@@ -1,4 +1,4 @@
|
||||
# meta-compile v1.94 — Compile 1C metadata object from JSON
|
||||
# meta-compile v1.95 — Compile 1C metadata object from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
@@ -5169,91 +5169,85 @@ if ($commands -and $commands.Count -gt 0) {
|
||||
|
||||
# --- 17. Register in Configuration.xml ---
|
||||
|
||||
$configXmlPath = Join-Path $OutputDir "Configuration.xml"
|
||||
$regResult = $null
|
||||
# Регистрация объекта в <ChildObjects> родительского XML. Общая реализация: эталон —
|
||||
# meta-compile, копия — role-compile. Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
# Возвращает исход: added | already | no-childobj | no-config.
|
||||
function Register-InChildObjects([string]$ParentXmlPath, [string]$ParentTag, [string]$ChildTag, [string]$ChildName) {
|
||||
if (-not (Test-Path $ParentXmlPath)) { return "no-config" }
|
||||
|
||||
$doc = New-Object System.Xml.XmlDocument
|
||||
$doc.PreserveWhitespace = $true
|
||||
$doc.Load($ParentXmlPath)
|
||||
|
||||
$nsMgr = New-Object System.Xml.XmlNamespaceManager($doc.NameTable)
|
||||
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||
|
||||
$childObjects = $doc.SelectSingleNode("//md:$ParentTag/md:ChildObjects", $nsMgr)
|
||||
if (-not $childObjects) { return "no-childobj" }
|
||||
|
||||
$existing = $childObjects.SelectNodes("md:$ChildTag", $nsMgr)
|
||||
foreach ($e in $existing) {
|
||||
if ($e.InnerText -eq $ChildName) { return "already" }
|
||||
}
|
||||
|
||||
$newElem = $doc.CreateElement($ChildTag, "http://v8.1c.ru/8.3/MDClasses")
|
||||
$newElem.InnerText = $ChildName
|
||||
|
||||
if ($existing.Count -gt 0) {
|
||||
# Insert after last existing element of same type
|
||||
$lastElem = $existing[$existing.Count - 1]
|
||||
$newWs = $doc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertAfter($newWs, $lastElem) | Out-Null
|
||||
$childObjects.InsertAfter($newElem, $newWs) | Out-Null
|
||||
} else {
|
||||
# No existing elements of this type — insert before closing whitespace.
|
||||
# Самозакрытый <ChildObjects/> попадает сюда же: LastChild пуст, идёт ветка AppendChild.
|
||||
$lastChild = $childObjects.LastChild
|
||||
if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
|
||||
$newWs = $doc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertBefore($newWs, $lastChild) | Out-Null
|
||||
$childObjects.InsertBefore($newElem, $lastChild) | Out-Null
|
||||
} else {
|
||||
$childObjects.AppendChild($doc.CreateWhitespace("`n`t`t`t")) | Out-Null
|
||||
$childObjects.AppendChild($newElem) | Out-Null
|
||||
$childObjects.AppendChild($doc.CreateWhitespace("`n`t`t")) | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
# Save. Пишем через MemoryStream, а не прямо в файл: нужен шаг пост-обработки
|
||||
# строки — XmlWriter отдаёт `encoding="utf-8"` и `<a />`, Конфигуратор пишет
|
||||
# `encoding="UTF-8"` и `<a/>`.
|
||||
$cfgSettings = New-Object System.Xml.XmlWriterSettings
|
||||
$cfgSettings.Encoding = New-Object System.Text.UTF8Encoding($true)
|
||||
$cfgSettings.Indent = $false
|
||||
$cfgSettings.NewLineHandling = [System.Xml.NewLineHandling]::None
|
||||
$memStream = New-Object System.IO.MemoryStream
|
||||
$writer = [System.Xml.XmlWriter]::Create($memStream, $cfgSettings)
|
||||
$doc.Save($writer)
|
||||
$writer.Flush(); $writer.Close()
|
||||
|
||||
$cfgText = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
|
||||
$memStream.Close()
|
||||
if ($cfgText.Length -gt 0 -and $cfgText[0] -eq [char]0xFEFF) { $cfgText = $cfgText.Substring(1) }
|
||||
$cfgText = $cfgText.Replace('encoding="utf-8"', 'encoding="UTF-8"')
|
||||
# Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
|
||||
# CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
|
||||
# поэтому они идут первыми ветками альтернации и возвращаются как есть.
|
||||
$cfgText = [regex]::Replace($cfgText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
|
||||
# Целевой перевод строки: стиль файла-назначения — правка наследует его (#44/#46/#47),
|
||||
# новый файл получает канон выгрузки CRLF. Зеркало _detect_xml_style в py-порту.
|
||||
$targetEol = if ([System.IO.File]::ReadAllText($ParentXmlPath) -notmatch "`r`n") { "`n" } else { "`r`n" }
|
||||
$cfgText = ($cfgText -replace "`r`n", "`n") -replace "`n", $targetEol
|
||||
[System.IO.File]::WriteAllText($ParentXmlPath, $cfgText, (New-Object System.Text.UTF8Encoding($true)))
|
||||
|
||||
return "added"
|
||||
}
|
||||
|
||||
# XML tag name for Configuration.xml ChildObjects
|
||||
$childTag = $objType
|
||||
|
||||
if (Test-Path $configXmlPath) {
|
||||
$configDoc = New-Object System.Xml.XmlDocument
|
||||
$configDoc.PreserveWhitespace = $true
|
||||
$configDoc.Load($configXmlPath)
|
||||
|
||||
$nsMgr = New-Object System.Xml.XmlNamespaceManager($configDoc.NameTable)
|
||||
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||
|
||||
$childObjects = $configDoc.SelectSingleNode("//md:Configuration/md:ChildObjects", $nsMgr)
|
||||
if ($childObjects) {
|
||||
$existing = $childObjects.SelectNodes("md:$childTag", $nsMgr)
|
||||
$alreadyExists = $false
|
||||
foreach ($e in $existing) {
|
||||
if ($e.InnerText -eq $objName) {
|
||||
$alreadyExists = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($alreadyExists) {
|
||||
$regResult = "already"
|
||||
} else {
|
||||
$newElem = $configDoc.CreateElement($childTag, "http://v8.1c.ru/8.3/MDClasses")
|
||||
$newElem.InnerText = $objName
|
||||
|
||||
if ($existing.Count -gt 0) {
|
||||
# Insert after last existing element of same type
|
||||
$lastElem = $existing[$existing.Count - 1]
|
||||
$newWs = $configDoc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertAfter($newWs, $lastElem) | Out-Null
|
||||
$childObjects.InsertAfter($newElem, $newWs) | Out-Null
|
||||
} else {
|
||||
# No existing elements of this type — insert before closing whitespace
|
||||
$lastChild = $childObjects.LastChild
|
||||
if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
|
||||
$newWs = $configDoc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertBefore($newWs, $lastChild) | Out-Null
|
||||
$childObjects.InsertBefore($newElem, $lastChild) | Out-Null
|
||||
} else {
|
||||
$childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
|
||||
$childObjects.AppendChild($newElem) | Out-Null
|
||||
$childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t")) | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
# Save. Пишем через MemoryStream, а не прямо в файл: нужен шаг пост-обработки
|
||||
# строки — XmlWriter отдаёт `encoding="utf-8"` и `<a />`, Конфигуратор пишет
|
||||
# `encoding="UTF-8"` и `<a/>`.
|
||||
$cfgSettings = New-Object System.Xml.XmlWriterSettings
|
||||
$cfgSettings.Encoding = New-Object System.Text.UTF8Encoding($true)
|
||||
$cfgSettings.Indent = $false
|
||||
$cfgSettings.NewLineHandling = [System.Xml.NewLineHandling]::None
|
||||
$memStream = New-Object System.IO.MemoryStream
|
||||
$writer = [System.Xml.XmlWriter]::Create($memStream, $cfgSettings)
|
||||
$configDoc.Save($writer)
|
||||
$writer.Flush(); $writer.Close()
|
||||
|
||||
$cfgText = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
|
||||
$memStream.Close()
|
||||
if ($cfgText.Length -gt 0 -and $cfgText[0] -eq [char]0xFEFF) { $cfgText = $cfgText.Substring(1) }
|
||||
$cfgText = $cfgText.Replace('encoding="utf-8"', 'encoding="UTF-8"')
|
||||
# Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
|
||||
# CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
|
||||
# поэтому они идут первыми ветками альтернации и возвращаются как есть.
|
||||
$cfgText = [regex]::Replace($cfgText, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
|
||||
# Целевой перевод строки: стиль файла-назначения — правка наследует его (#44/#46/#47),
|
||||
# новый файл получает канон выгрузки CRLF. Зеркало _detect_xml_style в py-порту.
|
||||
$targetEol = if ((Test-Path -LiteralPath $configXmlPath) -and ([System.IO.File]::ReadAllText($configXmlPath) -notmatch "`r`n")) { "`n" } else { "`r`n" }
|
||||
$cfgText = ($cfgText -replace "`r`n", "`n") -replace "`n", $targetEol
|
||||
[System.IO.File]::WriteAllText($configXmlPath, $cfgText, (New-Object System.Text.UTF8Encoding($true)))
|
||||
|
||||
$regResult = "added"
|
||||
}
|
||||
} else {
|
||||
$regResult = "no-childobj"
|
||||
}
|
||||
} else {
|
||||
$regResult = "no-config"
|
||||
}
|
||||
$configXmlPath = Join-Path $OutputDir "Configuration.xml"
|
||||
$regResult = Register-InChildObjects $configXmlPath "Configuration" $childTag $objName
|
||||
|
||||
# --- 18. Summary ---
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# meta-compile v1.94 — Compile 1C metadata object from JSON
|
||||
# meta-compile v1.95 — Compile 1C metadata object from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -5148,78 +5148,82 @@ if commands:
|
||||
# 17. Register in Configuration.xml
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
config_xml_path = os.path.join(output_dir, 'Configuration.xml')
|
||||
reg_result = None
|
||||
def register_in_childobjects(parent_xml_path, parent_tag, child_tag, child_name):
|
||||
"""Регистрация объекта в <ChildObjects> родительского XML.
|
||||
|
||||
child_tag = obj_type
|
||||
Общая реализация: эталон — meta-compile, копия — role-compile.
|
||||
Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
Возвращает исход: added | already | no-childobj | no-config.
|
||||
"""
|
||||
if not os.path.isfile(parent_xml_path):
|
||||
return 'no-config'
|
||||
|
||||
if os.path.isfile(config_xml_path):
|
||||
# Read raw content, preserving BOM/EOL byte-for-byte (newline='' => no translation).
|
||||
with open(config_xml_path, 'r', encoding='utf-8-sig', newline='') as f:
|
||||
# Read raw content, preserving BOM/EOL byte-for-byte (newline='' => no translation)
|
||||
with open(parent_xml_path, 'r', encoding='utf-8-sig', newline='') as f:
|
||||
config_content = f.read()
|
||||
|
||||
ns = 'http://v8.1c.ru/8.3/MDClasses'
|
||||
# ET is used ONLY read-only here: to locate ChildObjects and detect a duplicate.
|
||||
# We deliberately do NOT re-serialize Configuration.xml with ElementTree.write():
|
||||
# it drops every xmlns declaration used only inside attribute VALUES (e.g.
|
||||
# xsi:type="app:ApplicationUsePurpose" in UsePurposes) because ET never sees those
|
||||
# xsi:type="app:ApplicationUsePurpose" in UsePurposes) because ET never sees such
|
||||
# prefixes in element/attribute names. The dropped declaration makes XDTO read the
|
||||
# value as anyType and Designer refuses to load the file (issue #38). Registration is
|
||||
# therefore done by raw-text insertion, preserving BOM, EOL and all namespaces
|
||||
# byte-for-byte (same approach as subsystem-compile).
|
||||
tree = ET.parse(config_xml_path)
|
||||
tree = ET.parse(parent_xml_path)
|
||||
root = tree.getroot()
|
||||
|
||||
child_objects = root.find(f'{{{ns}}}Configuration/{{{ns}}}ChildObjects')
|
||||
child_objects = root.find(f'{{{ns}}}{parent_tag}/{{{ns}}}ChildObjects')
|
||||
if child_objects is None:
|
||||
# Try direct path
|
||||
config_elem = root.find(f'{{{ns}}}Configuration')
|
||||
if config_elem is not None:
|
||||
child_objects = config_elem.find(f'{{{ns}}}ChildObjects')
|
||||
parent_elem = root.find(f'{{{ns}}}{parent_tag}')
|
||||
if parent_elem is not None:
|
||||
child_objects = parent_elem.find(f'{{{ns}}}ChildObjects')
|
||||
|
||||
if child_objects is None:
|
||||
reg_result = 'no-childobj'
|
||||
return 'no-childobj'
|
||||
|
||||
existing = child_objects.findall(f'{{{ns}}}{child_tag}')
|
||||
if any((e.text or '').strip() == child_name for e in existing):
|
||||
return 'already'
|
||||
|
||||
eol = '\r\n' if '\r\n' in config_content else '\n'
|
||||
entry = f'<{child_tag}>{esc_xml_text(child_name)}</{child_tag}>'
|
||||
|
||||
block = re.search(r'<ChildObjects\s*>.*?</ChildObjects>', config_content, re.S)
|
||||
if block is None:
|
||||
# Empty self-closing <ChildObjects/> => open it with the first entry.
|
||||
empty = re.search(r'<ChildObjects\s*/>', config_content)
|
||||
if empty is None:
|
||||
return 'no-childobj'
|
||||
replacement = f'<ChildObjects>{eol}\t\t\t{entry}{eol}\t\t</ChildObjects>'
|
||||
new_content = config_content[:empty.start()] + replacement + config_content[empty.end():]
|
||||
write_utf8_bom(parent_xml_path, new_content)
|
||||
return 'added'
|
||||
|
||||
close_same = f'</{child_tag}>'
|
||||
last_same = config_content.rfind(close_same, block.start(), block.end())
|
||||
if last_same != -1:
|
||||
# After the last element of the same type (keeps them grouped).
|
||||
insert_at = last_same + len(close_same)
|
||||
new_content = (config_content[:insert_at]
|
||||
+ f'{eol}\t\t\t{entry}'
|
||||
+ config_content[insert_at:])
|
||||
else:
|
||||
existing = child_objects.findall(f'{{{ns}}}{child_tag}')
|
||||
already_exists = any((e.text or '').strip() == obj_name for e in existing)
|
||||
# No element of this type yet: new line before </ChildObjects>,
|
||||
# reusing the block's existing closing indent for </ChildObjects>.
|
||||
close_at = config_content.rfind('</ChildObjects>', block.start(), block.end())
|
||||
new_content = (config_content[:close_at]
|
||||
+ f'\t{entry}{eol}\t\t'
|
||||
+ config_content[close_at:])
|
||||
write_utf8_bom(parent_xml_path, new_content)
|
||||
return 'added'
|
||||
|
||||
if already_exists:
|
||||
reg_result = 'already'
|
||||
else:
|
||||
eol = '\r\n' if '\r\n' in config_content else '\n'
|
||||
entry = f'<{child_tag}>{esc_xml_text(obj_name)}</{child_tag}>'
|
||||
|
||||
block = re.search(r'<ChildObjects\s*>.*?</ChildObjects>', config_content, re.S)
|
||||
if block is None:
|
||||
# Empty self-closing <ChildObjects/> => open it with the first entry.
|
||||
empty = re.search(r'<ChildObjects\s*/>', config_content)
|
||||
if empty is None:
|
||||
reg_result = 'no-childobj'
|
||||
else:
|
||||
replacement = f'<ChildObjects>{eol}\t\t\t{entry}{eol}\t\t</ChildObjects>'
|
||||
new_content = config_content[:empty.start()] + replacement + config_content[empty.end():]
|
||||
write_utf8_bom(config_xml_path, new_content)
|
||||
reg_result = 'added'
|
||||
else:
|
||||
close_same = f'</{child_tag}>'
|
||||
last_same = config_content.rfind(close_same, block.start(), block.end())
|
||||
if last_same != -1:
|
||||
# After the last element of the same type (keeps them grouped).
|
||||
insert_at = last_same + len(close_same)
|
||||
new_content = (config_content[:insert_at]
|
||||
+ f'{eol}\t\t\t{entry}'
|
||||
+ config_content[insert_at:])
|
||||
else:
|
||||
# No element of this type yet: new line before </ChildObjects>,
|
||||
# reusing the block's existing closing indent for </ChildObjects>.
|
||||
close_at = config_content.rfind('</ChildObjects>', block.start(), block.end())
|
||||
new_content = (config_content[:close_at]
|
||||
+ f'\t{entry}{eol}\t\t'
|
||||
+ config_content[close_at:])
|
||||
write_utf8_bom(config_xml_path, new_content)
|
||||
reg_result = 'added'
|
||||
else:
|
||||
reg_result = 'no-config'
|
||||
child_tag = obj_type
|
||||
config_xml_path = os.path.join(output_dir, 'Configuration.xml')
|
||||
reg_result = register_in_childobjects(config_xml_path, 'Configuration', child_tag, obj_name)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 18. Summary
|
||||
|
||||
Reference in New Issue
Block a user