mirror of
https://github.com/Nikolay-Shirokov/cc-1c-skills.git
synced 2026-09-22 10:15:52 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4fa4ef6b1 |
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"name": "cc-1c-skills",
|
||||
"interface": {
|
||||
"displayName": "1C Skills"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "1c-skills",
|
||||
"source": {
|
||||
"source": "url",
|
||||
"url": "https://github.com/Nikolay-Shirokov/cc-1c-skills.git",
|
||||
"ref": "port-codex"
|
||||
},
|
||||
"policy": {
|
||||
"installation": "AVAILABLE"
|
||||
},
|
||||
"category": "Development"
|
||||
},
|
||||
{
|
||||
"name": "1c-skills-py",
|
||||
"source": {
|
||||
"source": "url",
|
||||
"url": "https://github.com/Nikolay-Shirokov/cc-1c-skills.git",
|
||||
"ref": "port-codex-py"
|
||||
},
|
||||
"policy": {
|
||||
"installation": "AVAILABLE"
|
||||
},
|
||||
"category": "Development"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-marketplace-manifest.json",
|
||||
"name": "cc-1c-skills",
|
||||
"description": "Маркетплейс навыков для разработки на платформе 1С:Предприятие",
|
||||
"owner": {
|
||||
"name": "Nikolay Shirokov"
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
"name": "1c-skills",
|
||||
"source": "./",
|
||||
"description": "[PowerShell] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент."
|
||||
},
|
||||
{
|
||||
"name": "1c-skills-py",
|
||||
"source": {
|
||||
"source": "github",
|
||||
"repo": "Nikolay-Shirokov/cc-1c-skills",
|
||||
"ref": "port-claude-code-py"
|
||||
},
|
||||
"description": "[Python] То же — для Linux/Mac или когда PowerShell недоступен."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
|
||||
"name": "1c-skills",
|
||||
"description": "[PowerShell] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент.",
|
||||
"author": {
|
||||
"name": "Nikolay Shirokov"
|
||||
},
|
||||
"homepage": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"repository": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"1c",
|
||||
"1c-dev",
|
||||
"cf",
|
||||
"cfe",
|
||||
"epf",
|
||||
"erf",
|
||||
"metadata",
|
||||
"configuration",
|
||||
"extension",
|
||||
"form",
|
||||
"report",
|
||||
"skd",
|
||||
"data-processor",
|
||||
"mxl",
|
||||
"web-client",
|
||||
"testing",
|
||||
"test-automation"
|
||||
],
|
||||
"skills": "./.claude/skills/"
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
---
|
||||
name: cf-init
|
||||
description: Создать пустую конфигурацию 1С (scaffold XML-исходников). Используй когда нужно начать новую конфигурацию с нуля
|
||||
argument-hint: <Name> [-Synonym <name>] [-OutputDir src]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /cf-init — Создание пустой конфигурации 1С
|
||||
|
||||
Создаёт scaffold исходников пустой конфигурации 1С: `Configuration.xml`, `Languages/Русский.xml`.
|
||||
|
||||
## Параметры и команда
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `Name` | Имя конфигурации (обязат.) |
|
||||
| `Synonym` | Синоним (= Name если не указан) |
|
||||
| `OutputDir` | Каталог для создания (default: `src`) |
|
||||
| `Version` | Версия конфигурации |
|
||||
| `Vendor` | Поставщик |
|
||||
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-init.ps1" -Name "МояКонфигурация"
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Базовая конфигурация
|
||||
... -Name МояКонфигурация -Synonym "Моя конфигурация" -OutputDir test-tmp/cf
|
||||
|
||||
# С версией и поставщиком
|
||||
... -Name TestCfg -Synonym "Тестовая" -Version "1.0.0.1" -Vendor "Фирма 1С" -OutputDir test-tmp/cf2
|
||||
|
||||
# Другой режим совместимости
|
||||
... -Name TestCfg -CompatibilityMode Version8_3_27 -OutputDir test-tmp/cf3
|
||||
```
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/cf-init TestConfig -OutputDir test-tmp/cf
|
||||
/cf-info test-tmp/cf — проверить созданное
|
||||
/cf-validate test-tmp/cf — валидировать
|
||||
```
|
||||
@@ -1,238 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# cf-init v1.4 — Create empty 1C configuration scaffold
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Generates minimal XML source files for a 1C configuration."""
|
||||
import sys, os, argparse, uuid
|
||||
|
||||
def esc_xml(s):
|
||||
return s.replace('&','&').replace('<','<').replace('>','>').replace('"','"')
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Create empty 1C configuration scaffold', allow_abbrev=False)
|
||||
parser.add_argument('-Name', dest='Name', required=True)
|
||||
parser.add_argument('-Synonym', dest='Synonym', default=None)
|
||||
parser.add_argument('-OutputDir', dest='OutputDir', default='src')
|
||||
parser.add_argument('-Version', dest='Version', default='')
|
||||
parser.add_argument('-Vendor', dest='Vendor', default='')
|
||||
parser.add_argument('-CompatibilityMode', dest='CompatibilityMode', default='Version8_3_24')
|
||||
# Версия формата выгрузки (MDClasses) — её задаёт ПЛАТФОРМА, а не режим совместимости:
|
||||
# 8.3.20-8.3.24 пишут 2.17, 8.3.25 — 2.18, 8.3.26 — 2.19, 8.3.27 — 2.20.
|
||||
# Дефолт консервативный: 2.17 читается всеми платформами.
|
||||
parser.add_argument('-FormatVersion', dest='FormatVersion', default='2.17',
|
||||
choices=['2.17', '2.18', '2.19', '2.20', '2.21'])
|
||||
args = parser.parse_args()
|
||||
|
||||
name = args.Name
|
||||
synonym = args.Synonym if args.Synonym else name
|
||||
output_dir = args.OutputDir
|
||||
version = args.Version
|
||||
vendor = args.Vendor
|
||||
compat = args.CompatibilityMode
|
||||
|
||||
# --- Resolve output dir ---
|
||||
if not os.path.isabs(output_dir):
|
||||
output_dir = os.path.join(os.getcwd(), output_dir)
|
||||
|
||||
# --- Check existing ---
|
||||
cfg_file = os.path.join(output_dir, "Configuration.xml")
|
||||
if os.path.exists(cfg_file):
|
||||
print(f"Configuration.xml already exists: {cfg_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# --- Generate UUIDs ---
|
||||
uuid_cfg = new_uuid()
|
||||
uuid_lang = new_uuid()
|
||||
co = [new_uuid() for _ in range(7)]
|
||||
|
||||
# --- Mobile functionalities ---
|
||||
mobile_funcs = [
|
||||
("Biometrics","true"), ("Location","false"), ("BackgroundLocation","false"),
|
||||
("BluetoothPrinters","false"), ("WiFiPrinters","false"), ("Contacts","false"),
|
||||
("Calendars","false"), ("PushNotifications","false"), ("LocalNotifications","false"),
|
||||
("InAppPurchases","false"), ("PersonalComputerFileExchange","false"), ("Ads","false"),
|
||||
("NumberDialing","false"), ("CallProcessing","false"), ("CallLog","false"),
|
||||
("AutoSendSMS","false"), ("ReceiveSMS","false"), ("SMSLog","false"),
|
||||
("Camera","false"), ("Microphone","false"), ("MusicLibrary","false"),
|
||||
("PictureAndVideoLibraries","false"), ("AudioPlaybackAndVibration","false"),
|
||||
("BackgroundAudioPlaybackAndVibration","false"), ("InstallPackages","false"),
|
||||
("OSBackup","true"), ("ApplicationUsageStatistics","false"),
|
||||
("BarcodeScanning","false"), ("BackgroundAudioRecording","false"),
|
||||
("AllFilesAccess","false"), ("Videoconferences","false"), ("NFC","false"),
|
||||
("DocumentScanning","false"), ("SpeechToText","false"), ("Geofences","false"),
|
||||
("IncomingShareRequests","false"), ("AllIncomingShareRequestsTypesProcessing","false"),
|
||||
]
|
||||
|
||||
mobile_xml = ""
|
||||
for func_name, func_use in mobile_funcs:
|
||||
mobile_xml += f"\r\n\t\t\t\t<app:functionality>\r\n\t\t\t\t\t<app:functionality>{func_name}</app:functionality>\r\n\t\t\t\t\t<app:use>{func_use}</app:use>\r\n\t\t\t\t</app:functionality>"
|
||||
|
||||
# --- Synonym XML ---
|
||||
synonym_xml = ""
|
||||
if synonym:
|
||||
synonym_xml = f"\r\n\t\t\t\t<v8:item>\r\n\t\t\t\t\t<v8:lang>ru</v8:lang>\r\n\t\t\t\t\t<v8:content>{esc_xml(synonym)}</v8:content>\r\n\t\t\t\t</v8:item>\r\n\t\t\t"
|
||||
|
||||
vendor_xml = esc_xml(vendor) if vendor else ""
|
||||
version_xml = esc_xml(version) if version else ""
|
||||
|
||||
class_ids = [
|
||||
"9cd510cd-abfc-11d4-9434-004095e12fc7",
|
||||
"9fcd25a0-4822-11d4-9414-008048da11f9",
|
||||
"e3687481-0a87-462c-a166-9f34594f9bba",
|
||||
"9de14907-ec23-4a07-96f0-85521cb6b53b",
|
||||
"51f2d5d8-ea4d-4064-8892-82951750031e",
|
||||
"e68182ea-4237-4383-967f-90c1e3370bc7",
|
||||
"fb282519-d103-4dd3-bc12-cb271d631dfc",
|
||||
]
|
||||
|
||||
contained_objects = ""
|
||||
for i in range(7):
|
||||
contained_objects += f"""\t\t\t<xr:ContainedObject>
|
||||
\t\t\t\t<xr:ClassId>{class_ids[i]}</xr:ClassId>
|
||||
\t\t\t\t<xr:ObjectId>{co[i]}</xr:ObjectId>
|
||||
\t\t\t</xr:ContainedObject>\n"""
|
||||
|
||||
cfg_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{args.FormatVersion}">
|
||||
\t<Configuration uuid="{uuid_cfg}">
|
||||
\t\t<InternalInfo>
|
||||
{contained_objects}\t\t</InternalInfo>
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{esc_xml(name)}</Name>
|
||||
\t\t\t<Synonym>{synonym_xml}</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<NamePrefix/>
|
||||
\t\t\t<ConfigurationExtensionCompatibilityMode>{compat}</ConfigurationExtensionCompatibilityMode>
|
||||
\t\t\t<DefaultRunMode>ManagedApplication</DefaultRunMode>
|
||||
\t\t\t<UsePurposes>
|
||||
\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||
\t\t\t</UsePurposes>
|
||||
\t\t\t<ScriptVariant>Russian</ScriptVariant>
|
||||
\t\t\t<DefaultRoles/>
|
||||
\t\t\t<Vendor>{vendor_xml}</Vendor>
|
||||
\t\t\t<Version>{version_xml}</Version>
|
||||
\t\t\t<UpdateCatalogAddress/>
|
||||
\t\t\t<IncludeHelpInContents>false</IncludeHelpInContents>
|
||||
\t\t\t<UseManagedFormInOrdinaryApplication>false</UseManagedFormInOrdinaryApplication>
|
||||
\t\t\t<UseOrdinaryFormInManagedApplication>false</UseOrdinaryFormInManagedApplication>
|
||||
\t\t\t<AdditionalFullTextSearchDictionaries/>
|
||||
\t\t\t<CommonSettingsStorage/>
|
||||
\t\t\t<ReportsUserSettingsStorage/>
|
||||
\t\t\t<ReportsVariantsStorage/>
|
||||
\t\t\t<FormDataSettingsStorage/>
|
||||
\t\t\t<DynamicListsUserSettingsStorage/>
|
||||
\t\t\t<URLExternalDataStorage/>
|
||||
\t\t\t<Content/>
|
||||
\t\t\t<DefaultReportForm/>
|
||||
\t\t\t<DefaultReportVariantForm/>
|
||||
\t\t\t<DefaultReportSettingsForm/>
|
||||
\t\t\t<DefaultReportAppearanceTemplate/>
|
||||
\t\t\t<DefaultDynamicListSettingsForm/>
|
||||
\t\t\t<DefaultSearchForm/>
|
||||
\t\t\t<DefaultDataHistoryChangeHistoryForm/>
|
||||
\t\t\t<DefaultDataHistoryVersionDataForm/>
|
||||
\t\t\t<DefaultDataHistoryVersionDifferencesForm/>
|
||||
\t\t\t<DefaultCollaborationSystemUsersChoiceForm/>
|
||||
\t\t\t<RequiredMobileApplicationPermissions/>
|
||||
\t\t\t<UsedMobileApplicationFunctionalities>{mobile_xml}
|
||||
\t\t\t</UsedMobileApplicationFunctionalities>
|
||||
\t\t\t<StandaloneConfigurationRestrictionRoles/>
|
||||
\t\t\t<MobileApplicationURLs/>
|
||||
\t\t\t<AllowedIncomingShareRequestTypes/>
|
||||
\t\t\t<MainClientApplicationWindowMode>Normal</MainClientApplicationWindowMode>
|
||||
\t\t\t<DefaultInterface/>
|
||||
\t\t\t<DefaultStyle/>
|
||||
\t\t\t<DefaultLanguage>Language.Русский</DefaultLanguage>
|
||||
\t\t\t<BriefInformation/>
|
||||
\t\t\t<DetailedInformation/>
|
||||
\t\t\t<Copyright/>
|
||||
\t\t\t<VendorInformationAddress/>
|
||||
\t\t\t<ConfigurationInformationAddress/>
|
||||
\t\t\t<DataLockControlMode>Managed</DataLockControlMode>
|
||||
\t\t\t<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
||||
\t\t\t<ModalityUseMode>DontUse</ModalityUseMode>
|
||||
\t\t\t<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
||||
\t\t\t<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
||||
\t\t\t<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
||||
\t\t\t<CompatibilityMode>{compat}</CompatibilityMode>
|
||||
\t\t\t<DefaultConstantsForm/>
|
||||
\t\t</Properties>
|
||||
\t\t<ChildObjects>
|
||||
\t\t\t<Language>Русский</Language>
|
||||
\t\t</ChildObjects>
|
||||
\t</Configuration>
|
||||
</MetaDataObject>'''
|
||||
|
||||
# --- Languages/Русский.xml ---
|
||||
lang_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{args.FormatVersion}">
|
||||
\t<Language uuid="{uuid_lang}">
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>Русский</Name>
|
||||
\t\t\t<Synonym>
|
||||
\t\t\t\t<v8:item>
|
||||
\t\t\t\t\t<v8:lang>ru</v8:lang>
|
||||
\t\t\t\t\t<v8:content>Русский</v8:content>
|
||||
\t\t\t\t</v8:item>
|
||||
\t\t\t</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<LanguageCode>ru</LanguageCode>
|
||||
\t\t</Properties>
|
||||
\t</Language>
|
||||
</MetaDataObject>'''
|
||||
|
||||
# --- Ext/ClientApplicationInterface.xml (default ERP-style panel layout) ---
|
||||
# Open panel on top, Sections panel on left; Functions/Favorites/History declared
|
||||
# via panelDef but not placed by default. Without this file the web client renders
|
||||
# section icons without labels (icon-only mode).
|
||||
open_panel_inst = new_uuid()
|
||||
sections_panel_inst = new_uuid()
|
||||
cai_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ClientApplicationInterface xmlns="http://v8.1c.ru/8.2/managed-application/core" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="InterfaceLayouter">
|
||||
\t<top>
|
||||
\t\t<panel id="{open_panel_inst}">
|
||||
\t\t\t<uuid>cbab57f2-a0f3-4f0a-89ea-4cb19570ab75</uuid>
|
||||
\t\t</panel>
|
||||
\t</top>
|
||||
\t<left>
|
||||
\t\t<panel id="{sections_panel_inst}">
|
||||
\t\t\t<uuid>b553047f-c9aa-4157-978d-448ecad24248</uuid>
|
||||
\t\t</panel>
|
||||
\t</left>
|
||||
\t<panelDef id="b553047f-c9aa-4157-978d-448ecad24248"/>
|
||||
\t<panelDef id="13322b22-3960-4d68-93a6-fe2dd7f28ca3"/>
|
||||
\t<panelDef id="c933ac92-92cd-459d-81cc-e0c8a83ced99"/>
|
||||
\t<panelDef id="cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"/>
|
||||
\t<panelDef id="b2735bd3-d822-4430-ba59-c9e869693b24"/>
|
||||
</ClientApplicationInterface>'''
|
||||
|
||||
# --- Create directories ---
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
lang_dir = os.path.join(output_dir, "Languages")
|
||||
os.makedirs(lang_dir, exist_ok=True)
|
||||
ext_dir = os.path.join(output_dir, "Ext")
|
||||
os.makedirs(ext_dir, exist_ok=True)
|
||||
|
||||
# --- Write files ---
|
||||
write_utf8_bom(cfg_file, cfg_xml)
|
||||
lang_file = os.path.join(lang_dir, "Русский.xml")
|
||||
write_utf8_bom(lang_file, lang_xml)
|
||||
cai_file = os.path.join(ext_dir, "ClientApplicationInterface.xml")
|
||||
write_utf8_bom(cai_file, cai_xml)
|
||||
|
||||
print(f"[OK] Создана конфигурация: {name}")
|
||||
print(f" Каталог: {output_dir}")
|
||||
print(f" Configuration.xml: {cfg_file}")
|
||||
print(f" Languages: {lang_file}")
|
||||
print(f" Ext/CAI: {cai_file}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,29 +0,0 @@
|
||||
---
|
||||
name: cfe-validate
|
||||
description: Валидация расширения конфигурации 1С (CFE). Используй после создания или модификации расширения для проверки корректности
|
||||
argument-hint: <ExtensionPath> [-Detailed] [-MaxErrors 30]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /cfe-validate — валидация расширения конфигурации (CFE)
|
||||
|
||||
Проверяет структурную корректность расширения: XML-формат, свойства, состав, заимствованные объекты. Аналог `/cf-validate`, но для расширений.
|
||||
|
||||
## Параметры
|
||||
|
||||
| Параметр | Обяз. | Умолч. | Описание |
|
||||
|---------------|:-----:|---------|-------------------------------------------------|
|
||||
| ExtensionPath | да | — | Путь к каталогу или Configuration.xml расширения |
|
||||
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
|
||||
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||
| OutFile | нет | — | Записать результат в файл |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-validate.ps1" -ExtensionPath "src"
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-validate.ps1" -ExtensionPath "src/Configuration.xml"
|
||||
```
|
||||
@@ -1,41 +0,0 @@
|
||||
---
|
||||
name: epf-init
|
||||
description: Создать пустую внешнюю обработку 1С (scaffold XML-исходников). Используй когда нужно создать новую внешнюю обработку с нуля
|
||||
argument-hint: <Name> [Synonym]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Glob
|
||||
- Grep
|
||||
---
|
||||
|
||||
# /epf-init — Создание новой обработки
|
||||
|
||||
Генерирует минимальный набор XML-исходников для внешней обработки 1С: корневой файл метаданных и каталог обработки.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/epf-init <Name> [Synonym] [SrcDir]
|
||||
```
|
||||
|
||||
| Параметр | Обязательный | По умолчанию | Описание |
|
||||
|-----------|:------------:|--------------|-------------------------------------|
|
||||
| Name | да | — | Имя обработки (латиница/кириллица) |
|
||||
| Synonym | нет | = Name | Синоним (отображаемое имя) |
|
||||
| SrcDir | нет | `src` | Каталог исходников относительно CWD |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/init.ps1" -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"]
|
||||
```
|
||||
|
||||
## Дальнейшие шаги
|
||||
|
||||
- Добавить форму: `/form-add`
|
||||
- Добавить макет: `/template-add`
|
||||
- Добавить справку: `/help-add`
|
||||
- Собрать EPF: `/epf-build`
|
||||
@@ -1,90 +0,0 @@
|
||||
# epf-init v1.1 — Init 1C external data processor scaffold
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
|
||||
[string]$Synonym = $Name,
|
||||
|
||||
[string]$SrcDir = "src"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
$uuid1 = [guid]::NewGuid().ToString()
|
||||
$uuid2 = [guid]::NewGuid().ToString()
|
||||
$uuid3 = [guid]::NewGuid().ToString()
|
||||
$uuid4 = [guid]::NewGuid().ToString()
|
||||
|
||||
$xml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
<ExternalDataProcessor uuid="$uuid1">
|
||||
<InternalInfo>
|
||||
<xr:ContainedObject>
|
||||
<xr:ClassId>c3831ec8-d8d5-4f93-8a22-f9bfae07327f</xr:ClassId>
|
||||
<xr:ObjectId>$uuid2</xr:ObjectId>
|
||||
</xr:ContainedObject>
|
||||
<xr:GeneratedType name="ExternalDataProcessorObject.$Name" category="Object">
|
||||
<xr:TypeId>$uuid3</xr:TypeId>
|
||||
<xr:ValueId>$uuid4</xr:ValueId>
|
||||
</xr:GeneratedType>
|
||||
</InternalInfo>
|
||||
<Properties>
|
||||
<Name>$Name</Name>
|
||||
<Synonym>
|
||||
<v8:item>
|
||||
<v8:lang>ru</v8:lang>
|
||||
<v8:content>$Synonym</v8:content>
|
||||
</v8:item>
|
||||
</Synonym>
|
||||
<Comment/>
|
||||
<DefaultForm/>
|
||||
<AuxiliaryForm/>
|
||||
</Properties>
|
||||
<ChildObjects/>
|
||||
</ExternalDataProcessor>
|
||||
</MetaDataObject>
|
||||
"@
|
||||
|
||||
$rootFile = Join-Path $SrcDir "$Name.xml"
|
||||
$processorDir = Join-Path $SrcDir $Name
|
||||
|
||||
if (Test-Path $rootFile) {
|
||||
Write-Error "Файл уже существует: $rootFile"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path $SrcDir)) {
|
||||
New-Item -ItemType Directory -Path $SrcDir -Force | Out-Null
|
||||
}
|
||||
$extDir = Join-Path $processorDir "Ext"
|
||||
New-Item -ItemType Directory -Path $extDir -Force | Out-Null
|
||||
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText((Resolve-Path $SrcDir | Join-Path -ChildPath "$Name.xml"), $xml, $enc)
|
||||
|
||||
# --- Модуль объекта ---
|
||||
|
||||
$moduleBsl = @"
|
||||
#Область ОписаниеПеременных
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ПрограммныйИнтерфейс
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область СлужебныеПроцедурыИФункции
|
||||
|
||||
#КонецОбласти
|
||||
"@
|
||||
|
||||
$modulePath = Join-Path $extDir "ObjectModule.bsl"
|
||||
[System.IO.File]::WriteAllText($modulePath, $moduleBsl, $enc)
|
||||
|
||||
Write-Host "[OK] Создана обработка: $rootFile"
|
||||
Write-Host " Каталог: $processorDir"
|
||||
Write-Host " Модуль: $modulePath"
|
||||
@@ -1,99 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# epf-init v1.1 — Init 1C external data processor scaffold
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Generates minimal XML source files for a 1C external data processor."""
|
||||
import sys, os, argparse, uuid
|
||||
|
||||
def esc_xml(s):
|
||||
return s.replace('&','&').replace('<','<').replace('>','>').replace('"','"')
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Init 1C external data processor scaffold', allow_abbrev=False)
|
||||
parser.add_argument('-Name', dest='Name', required=True)
|
||||
parser.add_argument('-Synonym', dest='Synonym', default=None)
|
||||
parser.add_argument('-SrcDir', dest='SrcDir', default='src')
|
||||
args = parser.parse_args()
|
||||
|
||||
name = args.Name
|
||||
synonym = args.Synonym if args.Synonym else name
|
||||
src_dir = args.SrcDir
|
||||
|
||||
uuid1 = new_uuid()
|
||||
uuid2 = new_uuid()
|
||||
uuid3 = new_uuid()
|
||||
uuid4 = new_uuid()
|
||||
|
||||
xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
\t<ExternalDataProcessor uuid="{uuid1}">
|
||||
\t\t<InternalInfo>
|
||||
\t\t\t<xr:ContainedObject>
|
||||
\t\t\t\t<xr:ClassId>c3831ec8-d8d5-4f93-8a22-f9bfae07327f</xr:ClassId>
|
||||
\t\t\t\t<xr:ObjectId>{uuid2}</xr:ObjectId>
|
||||
\t\t\t</xr:ContainedObject>
|
||||
\t\t\t<xr:GeneratedType name="ExternalDataProcessorObject.{name}" category="Object">
|
||||
\t\t\t\t<xr:TypeId>{uuid3}</xr:TypeId>
|
||||
\t\t\t\t<xr:ValueId>{uuid4}</xr:ValueId>
|
||||
\t\t\t</xr:GeneratedType>
|
||||
\t\t</InternalInfo>
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{esc_xml(name)}</Name>
|
||||
\t\t\t<Synonym>
|
||||
\t\t\t\t<v8:item>
|
||||
\t\t\t\t\t<v8:lang>ru</v8:lang>
|
||||
\t\t\t\t\t<v8:content>{esc_xml(synonym)}</v8:content>
|
||||
\t\t\t\t</v8:item>
|
||||
\t\t\t</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<DefaultForm/>
|
||||
\t\t\t<AuxiliaryForm/>
|
||||
\t\t</Properties>
|
||||
\t\t<ChildObjects/>
|
||||
\t</ExternalDataProcessor>
|
||||
</MetaDataObject>'''
|
||||
|
||||
root_file = os.path.join(src_dir, f"{name}.xml")
|
||||
processor_dir = os.path.join(src_dir, name)
|
||||
|
||||
if os.path.exists(root_file):
|
||||
print(f"Файл уже существует: {root_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
os.makedirs(src_dir, exist_ok=True)
|
||||
ext_dir = os.path.join(processor_dir, "Ext")
|
||||
os.makedirs(ext_dir, exist_ok=True)
|
||||
|
||||
write_utf8_bom(os.path.join(os.path.abspath(src_dir), f"{name}.xml"), xml)
|
||||
|
||||
# --- Модуль объекта ---
|
||||
module_bsl = """\
|
||||
#Область ОписаниеПеременных
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ПрограммныйИнтерфейс
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область СлужебныеПроцедурыИФункции
|
||||
|
||||
#КонецОбласти"""
|
||||
|
||||
module_path = os.path.join(ext_dir, "ObjectModule.bsl")
|
||||
write_utf8_bom(module_path, module_bsl)
|
||||
|
||||
print(f"[OK] Создана обработка: {root_file}")
|
||||
print(f" Каталог: {processor_dir}")
|
||||
print(f" Модуль: {module_path}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
name: erf-init
|
||||
description: Создать пустой внешний отчёт 1С (scaffold XML-исходников). Используй когда нужно создать новый внешний отчёт с нуля
|
||||
argument-hint: <Name> [Synonym] [--with-skd]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Glob
|
||||
- Grep
|
||||
---
|
||||
|
||||
# /erf-init — Создание нового отчёта
|
||||
|
||||
Генерирует минимальный набор XML-исходников для внешнего отчёта 1С: корневой файл метаданных и каталог отчёта.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/erf-init <Name> [Synonym] [SrcDir] [--with-skd]
|
||||
```
|
||||
|
||||
| Параметр | Обязательный | По умолчанию | Описание |
|
||||
|-----------|:------------:|--------------|---------------------------------------|
|
||||
| Name | да | — | Имя отчёта (латиница/кириллица) |
|
||||
| Synonym | нет | = Name | Синоним (отображаемое имя) |
|
||||
| SrcDir | нет | `src` | Каталог исходников относительно CWD |
|
||||
| --WithSKD | нет | — | Создать пустую СКД и привязать к MainDataCompositionSchema |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/init.ps1" -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"] [-WithSKD]
|
||||
```
|
||||
|
||||
## Дальнейшие шаги
|
||||
|
||||
- Добавить форму: `/form-add`
|
||||
- Добавить макет: `/template-add`
|
||||
- Добавить справку: `/help-add`
|
||||
- Собрать ERF: `/erf-build`
|
||||
@@ -1,180 +0,0 @@
|
||||
# erf-init v1.1 — Init 1C external report scaffold
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
|
||||
[string]$Synonym = $Name,
|
||||
|
||||
[string]$SrcDir = "src",
|
||||
|
||||
[switch]$WithSKD
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
$uuid1 = [guid]::NewGuid().ToString()
|
||||
$uuid2 = [guid]::NewGuid().ToString()
|
||||
$uuid3 = [guid]::NewGuid().ToString()
|
||||
$uuid4 = [guid]::NewGuid().ToString()
|
||||
|
||||
# --- Формируем Properties ---
|
||||
|
||||
$mainDCSValue = ""
|
||||
$childObjectsContent = ""
|
||||
|
||||
if ($WithSKD) {
|
||||
$mainDCSValue = "ExternalReport.$Name.Template.ОсновнаяСхемаКомпоновкиДанных"
|
||||
$childObjectsContent = @"
|
||||
|
||||
<Template>ОсновнаяСхемаКомпоновкиДанных</Template>
|
||||
|
||||
"@
|
||||
}
|
||||
|
||||
$mainDCSElement = if ($mainDCSValue) {
|
||||
"<MainDataCompositionSchema>$mainDCSValue</MainDataCompositionSchema>"
|
||||
} else {
|
||||
"<MainDataCompositionSchema/>"
|
||||
}
|
||||
|
||||
$childObjectsXml = if ($childObjectsContent) {
|
||||
"<ChildObjects>$childObjectsContent</ChildObjects>"
|
||||
} else {
|
||||
"<ChildObjects/>"
|
||||
}
|
||||
|
||||
$xml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
<ExternalReport uuid="$uuid1">
|
||||
<InternalInfo>
|
||||
<xr:ContainedObject>
|
||||
<xr:ClassId>e41aff26-25cf-4bb6-b6c1-3f478a75f374</xr:ClassId>
|
||||
<xr:ObjectId>$uuid2</xr:ObjectId>
|
||||
</xr:ContainedObject>
|
||||
<xr:GeneratedType name="ExternalReportObject.$Name" category="Object">
|
||||
<xr:TypeId>$uuid3</xr:TypeId>
|
||||
<xr:ValueId>$uuid4</xr:ValueId>
|
||||
</xr:GeneratedType>
|
||||
</InternalInfo>
|
||||
<Properties>
|
||||
<Name>$Name</Name>
|
||||
<Synonym>
|
||||
<v8:item>
|
||||
<v8:lang>ru</v8:lang>
|
||||
<v8:content>$Synonym</v8:content>
|
||||
</v8:item>
|
||||
</Synonym>
|
||||
<Comment/>
|
||||
<DefaultForm/>
|
||||
<AuxiliaryForm/>
|
||||
$mainDCSElement
|
||||
<DefaultSettingsForm/>
|
||||
<AuxiliarySettingsForm/>
|
||||
<DefaultVariantForm/>
|
||||
<VariantsStorage/>
|
||||
<SettingsStorage/>
|
||||
</Properties>
|
||||
$childObjectsXml
|
||||
</ExternalReport>
|
||||
</MetaDataObject>
|
||||
"@
|
||||
|
||||
$rootFile = Join-Path $SrcDir "$Name.xml"
|
||||
$reportDir = Join-Path $SrcDir $Name
|
||||
|
||||
if (Test-Path $rootFile) {
|
||||
Write-Error "Файл уже существует: $rootFile"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not (Test-Path $SrcDir)) {
|
||||
New-Item -ItemType Directory -Path $SrcDir -Force | Out-Null
|
||||
}
|
||||
$extDir = Join-Path $reportDir "Ext"
|
||||
New-Item -ItemType Directory -Path $extDir -Force | Out-Null
|
||||
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText((Resolve-Path $SrcDir | Join-Path -ChildPath "$Name.xml"), $xml, $enc)
|
||||
|
||||
# --- Модуль объекта ---
|
||||
|
||||
$moduleBsl = @"
|
||||
#Область ОписаниеПеременных
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ПрограммныйИнтерфейс
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область СлужебныеПроцедурыИФункции
|
||||
|
||||
#КонецОбласти
|
||||
"@
|
||||
|
||||
$modulePath = Join-Path $extDir "ObjectModule.bsl"
|
||||
[System.IO.File]::WriteAllText($modulePath, $moduleBsl, $enc)
|
||||
|
||||
Write-Host "[OK] Создан отчёт: $rootFile"
|
||||
Write-Host " Каталог: $reportDir"
|
||||
Write-Host " Модуль: $modulePath"
|
||||
|
||||
# --- СКД-макет (если --WithSKD) ---
|
||||
|
||||
if ($WithSKD) {
|
||||
$templatesDir = Join-Path $reportDir "Templates"
|
||||
$skdName = "ОсновнаяСхемаКомпоновкиДанных"
|
||||
$skdMetaPath = Join-Path $templatesDir "$skdName.xml"
|
||||
$skdExtDir = Join-Path (Join-Path $templatesDir $skdName) "Ext"
|
||||
New-Item -ItemType Directory -Path $skdExtDir -Force | Out-Null
|
||||
|
||||
$skdUuid = [guid]::NewGuid().ToString()
|
||||
|
||||
$skdMetaXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
<Template uuid="$skdUuid">
|
||||
<Properties>
|
||||
<Name>$skdName</Name>
|
||||
<Synonym>
|
||||
<v8:item>
|
||||
<v8:lang>ru</v8:lang>
|
||||
<v8:content>Основная схема компоновки данных</v8:content>
|
||||
</v8:item>
|
||||
</Synonym>
|
||||
<Comment/>
|
||||
<TemplateType>DataCompositionSchema</TemplateType>
|
||||
</Properties>
|
||||
</Template>
|
||||
</MetaDataObject>
|
||||
"@
|
||||
|
||||
[System.IO.File]::WriteAllText($skdMetaPath, $skdMetaXml, $enc)
|
||||
|
||||
$skdContent = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<DataCompositionSchema xmlns="http://v8.1c.ru/8.1/data-composition-system/schema"
|
||||
xmlns:dcscom="http://v8.1c.ru/8.1/data-composition-system/common"
|
||||
xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"
|
||||
xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"
|
||||
xmlns:v8="http://v8.1c.ru/8.1/data/core"
|
||||
xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"
|
||||
xmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<dataSource>
|
||||
<name>ИсточникДанных1</name>
|
||||
<dataSourceType>Local</dataSourceType>
|
||||
</dataSource>
|
||||
</DataCompositionSchema>
|
||||
"@
|
||||
|
||||
$skdFilePath = Join-Path $skdExtDir "Template.xml"
|
||||
[System.IO.File]::WriteAllText($skdFilePath, $skdContent, $enc)
|
||||
|
||||
Write-Host " СКД: $skdMetaPath"
|
||||
Write-Host " Тело: $skdFilePath"
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# erf-init v1.1 — Init 1C external report scaffold
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Generates minimal XML source files for a 1C external report."""
|
||||
import sys, os, argparse, uuid
|
||||
|
||||
def esc_xml(s):
|
||||
return s.replace('&','&').replace('<','<').replace('>','>').replace('"','"')
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Init 1C external report scaffold', allow_abbrev=False)
|
||||
parser.add_argument('-Name', dest='Name', required=True)
|
||||
parser.add_argument('-Synonym', dest='Synonym', default=None)
|
||||
parser.add_argument('-SrcDir', dest='SrcDir', default='src')
|
||||
parser.add_argument('-WithSKD', dest='WithSKD', action='store_true')
|
||||
args = parser.parse_args()
|
||||
|
||||
name = args.Name
|
||||
synonym = args.Synonym if args.Synonym else name
|
||||
src_dir = args.SrcDir
|
||||
|
||||
uuid1 = new_uuid()
|
||||
uuid2 = new_uuid()
|
||||
uuid3 = new_uuid()
|
||||
uuid4 = new_uuid()
|
||||
|
||||
# --- Properties ---
|
||||
main_dcs_value = ""
|
||||
child_objects_content = ""
|
||||
|
||||
if args.WithSKD:
|
||||
main_dcs_value = f"ExternalReport.{name}.Template.ОсновнаяСхемаКомпоновкиДанных"
|
||||
child_objects_content = f"\n\t\t\t<Template>ОсновнаяСхемаКомпоновкиДанных</Template>\n"
|
||||
|
||||
main_dcs_element = f"<MainDataCompositionSchema>{main_dcs_value}</MainDataCompositionSchema>" if main_dcs_value else "<MainDataCompositionSchema/>"
|
||||
child_objects_xml = f"<ChildObjects>{child_objects_content}\t\t</ChildObjects>" if child_objects_content else "<ChildObjects/>"
|
||||
|
||||
xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
\t<ExternalReport uuid="{uuid1}">
|
||||
\t\t<InternalInfo>
|
||||
\t\t\t<xr:ContainedObject>
|
||||
\t\t\t\t<xr:ClassId>e41aff26-25cf-4bb6-b6c1-3f478a75f374</xr:ClassId>
|
||||
\t\t\t\t<xr:ObjectId>{uuid2}</xr:ObjectId>
|
||||
\t\t\t</xr:ContainedObject>
|
||||
\t\t\t<xr:GeneratedType name="ExternalReportObject.{name}" category="Object">
|
||||
\t\t\t\t<xr:TypeId>{uuid3}</xr:TypeId>
|
||||
\t\t\t\t<xr:ValueId>{uuid4}</xr:ValueId>
|
||||
\t\t\t</xr:GeneratedType>
|
||||
\t\t</InternalInfo>
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{esc_xml(name)}</Name>
|
||||
\t\t\t<Synonym>
|
||||
\t\t\t\t<v8:item>
|
||||
\t\t\t\t\t<v8:lang>ru</v8:lang>
|
||||
\t\t\t\t\t<v8:content>{esc_xml(synonym)}</v8:content>
|
||||
\t\t\t\t</v8:item>
|
||||
\t\t\t</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<DefaultForm/>
|
||||
\t\t\t<AuxiliaryForm/>
|
||||
\t\t\t{main_dcs_element}
|
||||
\t\t\t<DefaultSettingsForm/>
|
||||
\t\t\t<AuxiliarySettingsForm/>
|
||||
\t\t\t<DefaultVariantForm/>
|
||||
\t\t\t<VariantsStorage/>
|
||||
\t\t\t<SettingsStorage/>
|
||||
\t\t</Properties>
|
||||
\t\t{child_objects_xml}
|
||||
\t</ExternalReport>
|
||||
</MetaDataObject>'''
|
||||
|
||||
root_file = os.path.join(src_dir, f"{name}.xml")
|
||||
report_dir = os.path.join(src_dir, name)
|
||||
|
||||
if os.path.exists(root_file):
|
||||
print(f"Файл уже существует: {root_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
os.makedirs(src_dir, exist_ok=True)
|
||||
ext_dir = os.path.join(report_dir, "Ext")
|
||||
os.makedirs(ext_dir, exist_ok=True)
|
||||
|
||||
write_utf8_bom(os.path.join(os.path.abspath(src_dir), f"{name}.xml"), xml)
|
||||
|
||||
# --- Модуль объекта ---
|
||||
module_bsl = """\
|
||||
#Область ОписаниеПеременных
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ПрограммныйИнтерфейс
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область СлужебныеПроцедурыИФункции
|
||||
|
||||
#КонецОбласти"""
|
||||
|
||||
module_path = os.path.join(ext_dir, "ObjectModule.bsl")
|
||||
write_utf8_bom(module_path, module_bsl)
|
||||
|
||||
print(f"[OK] Создан отчёт: {root_file}")
|
||||
print(f" Каталог: {report_dir}")
|
||||
print(f" Модуль: {module_path}")
|
||||
|
||||
# --- СКД-макет ---
|
||||
if args.WithSKD:
|
||||
templates_dir = os.path.join(report_dir, "Templates")
|
||||
skd_name = "ОсновнаяСхемаКомпоновкиДанных"
|
||||
skd_meta_path = os.path.join(templates_dir, f"{skd_name}.xml")
|
||||
skd_ext_dir = os.path.join(templates_dir, skd_name, "Ext")
|
||||
os.makedirs(skd_ext_dir, exist_ok=True)
|
||||
|
||||
skd_uuid = new_uuid()
|
||||
|
||||
skd_meta_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||
\t<Template uuid="{skd_uuid}">
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{skd_name}</Name>
|
||||
\t\t\t<Synonym>
|
||||
\t\t\t\t<v8:item>
|
||||
\t\t\t\t\t<v8:lang>ru</v8:lang>
|
||||
\t\t\t\t\t<v8:content>Основная схема компоновки данных</v8:content>
|
||||
\t\t\t\t</v8:item>
|
||||
\t\t\t</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<TemplateType>DataCompositionSchema</TemplateType>
|
||||
\t\t</Properties>
|
||||
\t</Template>
|
||||
</MetaDataObject>'''
|
||||
|
||||
write_utf8_bom(skd_meta_path, skd_meta_xml)
|
||||
|
||||
skd_content = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<DataCompositionSchema xmlns="http://v8.1c.ru/8.1/data-composition-system/schema"
|
||||
\t\txmlns:dcscom="http://v8.1c.ru/8.1/data-composition-system/common"
|
||||
\t\txmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"
|
||||
\t\txmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"
|
||||
\t\txmlns:v8="http://v8.1c.ru/8.1/data/core"
|
||||
\t\txmlns:v8ui="http://v8.1c.ru/8.1/data/ui"
|
||||
\t\txmlns:xs="http://www.w3.org/2001/XMLSchema"
|
||||
\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
\t<dataSource>
|
||||
\t\t<name>ИсточникДанных1</name>
|
||||
\t\t<dataSourceType>Local</dataSourceType>
|
||||
\t</dataSource>
|
||||
</DataCompositionSchema>'''
|
||||
|
||||
skd_file_path = os.path.join(skd_ext_dir, "Template.xml")
|
||||
write_utf8_bom(skd_file_path, skd_content)
|
||||
|
||||
print(f" СКД: {skd_meta_path}")
|
||||
print(f" Тело: {skd_file_path}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,71 +0,0 @@
|
||||
---
|
||||
name: form-add
|
||||
description: Добавить пустую управляемую форму к объекту 1С. Используй когда нужно создать у объекта новую форму
|
||||
argument-hint: <ObjectPath> <FormName> [Purpose] [--set-default]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Glob
|
||||
- Grep
|
||||
---
|
||||
|
||||
# /form-add — Добавление формы к объекту конфигурации
|
||||
|
||||
Создаёт управляемую форму (metadata XML + Form.xml + Module.bsl) и регистрирует её в корневом XML объекта конфигурации (Document, Catalog, InformationRegister и др.).
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/form-add <ObjectPath> <FormName> [Purpose] [Synonym] [--set-default]
|
||||
```
|
||||
|
||||
| Параметр | Обязательный | По умолчанию | Описание |
|
||||
|-------------|:------------:|--------------|----------------------------------------------|
|
||||
| ObjectPath | да | — | Путь к XML-файлу объекта (Documents/Док.xml) |
|
||||
| FormName | да | — | Имя формы (ФормаДокумента) |
|
||||
| Purpose | нет | Object | Назначение: Object, List, Choice, Record |
|
||||
| Synonym | нет | = FormName | Синоним формы |
|
||||
| --set-default | нет | авто | Установить как форму по умолчанию |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/form-add.ps1" -ObjectPath "<ObjectPath>" -FormName "<FormName>" [-Purpose "<Purpose>"] [-Synonym "<Synonym>"] [-SetDefault]
|
||||
```
|
||||
|
||||
## Purpose — назначение формы
|
||||
|
||||
| Purpose | Допустимые типы объектов | Основной реквизит | DefaultForm-свойство |
|
||||
|---------|-------------------------|-------------------|---------------------|
|
||||
| Object | Document, Catalog, DataProcessor, Report, ExternalDataProcessor, ExternalReport, ChartOf*, ExchangePlan, BusinessProcess, Task | Объект (тип: *Object.Имя) | DefaultObjectForm (DefaultForm для DataProcessor/Report/ExternalDataProcessor/ExternalReport) |
|
||||
| List | Все кроме DataProcessor | Список (DynamicList) | DefaultListForm |
|
||||
| Choice | Document, Catalog, ChartOf*, ExchangePlan, BusinessProcess, Task | Список (DynamicList) | DefaultChoiceForm |
|
||||
| Record | InformationRegister | Запись (InformationRegisterRecordManager) | DefaultRecordForm |
|
||||
|
||||
## Примеры
|
||||
|
||||
```
|
||||
# Форма документа
|
||||
/form-add Documents/АвансовыйОтчет.xml ФормаДокумента --purpose Object
|
||||
|
||||
# Форма списка каталога
|
||||
/form-add Catalogs/Контрагенты.xml ФормаСписка --purpose List
|
||||
|
||||
# Форма записи регистра сведений
|
||||
/form-add InformationRegisters/КурсыВалют.xml ФормаЗаписи --purpose Record
|
||||
|
||||
# Форма выбора с синонимом
|
||||
/form-add Catalogs/Номенклатура.xml ФормаВыбора --purpose Choice --synonym "Выбор номенклатуры"
|
||||
|
||||
# Установить как форму по умолчанию
|
||||
/form-add Documents/Заказ.xml ФормаДокументаНовая --purpose Object --set-default
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
1. `/form-add` — создать каркас формы
|
||||
2. `/form-compile` или `/form-edit` — наполнить Form.xml элементами
|
||||
3. `/form-validate` — проверить корректность
|
||||
4. `/form-info` — проанализировать результат
|
||||
@@ -1,621 +0,0 @@
|
||||
# form-add v1.12 — Add managed form to 1C config object
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ObjectPath,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FormName,
|
||||
|
||||
[string]$Synonym = $FormName,
|
||||
|
||||
[string]$Purpose = "Object",
|
||||
|
||||
[switch]$SetDefault
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Support guard (Ext/ParentConfigurations.bin) ---
|
||||
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
|
||||
# read-only configs unless allowed. Trigger = bin present; reaction from
|
||||
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
|
||||
# throws — guard errors degrade to allow.
|
||||
function Get-RootUuid([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $null }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
|
||||
} catch {}
|
||||
return $null
|
||||
}
|
||||
function Test-ExternalObjectRoot([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $false }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
||||
} catch {}
|
||||
return $false
|
||||
}
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Get-EditMode([string]$cfgDir) {
|
||||
try {
|
||||
$pj = Find-V8Project (Get-Location).Path
|
||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
||||
if (-not $pj) { return 'deny' }
|
||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
||||
if ($proj.databases) {
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($db.configSrc) {
|
||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
||||
return 'deny'
|
||||
} catch { return 'deny' }
|
||||
}
|
||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
||||
try {
|
||||
$rp = $targetPath
|
||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if (Test-ExternalObjectRoot $rp) { return }
|
||||
$elemUuid = Get-RootUuid $rp
|
||||
$cfgDir = $null; $binPath = $null
|
||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
||||
if (-not $cfgDir) {
|
||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
||||
}
|
||||
if ($elemUuid -and $cfgDir) { break }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
# New object (no element file): fall back to config root uuid.
|
||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
||||
if ($bytes.Length -le 32) { return }
|
||||
$start = 0
|
||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
||||
if (-not $hm.Success) { return }
|
||||
$G = [int]$hm.Groups[1].Value
|
||||
$K = [int]$hm.Groups[2].Value
|
||||
if ($K -eq 0) { return }
|
||||
$best = $null
|
||||
if ($elemUuid) {
|
||||
$u = [regex]::Escape($elemUuid.ToLower())
|
||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
||||
$f1 = [int]$m.Groups[1].Value
|
||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
||||
}
|
||||
}
|
||||
$blocked = $false; $code = ""; $reason = ""
|
||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
||||
elseif ($require -eq 'removed') {
|
||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
||||
}
|
||||
else {
|
||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
||||
}
|
||||
if (-not $blocked) { return }
|
||||
$mode = Get-EditMode $cfgDir
|
||||
if ($mode -eq 'off') { return }
|
||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
||||
# latter throws and would be swallowed by this function's own catch.
|
||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if ($code -eq "capability-off") {
|
||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
} elseif ($code -eq "not-removed") {
|
||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
||||
} else {
|
||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
||||
}
|
||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
||||
exit 1
|
||||
} catch { return }
|
||||
}
|
||||
|
||||
# --- Detect XML format version ---
|
||||
|
||||
function Detect-FormatVersion([string]$dir) {
|
||||
$d = $dir
|
||||
while ($d) {
|
||||
$cfgPath = Join-Path $d "Configuration.xml"
|
||||
if (Test-Path $cfgPath) {
|
||||
$cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
|
||||
# Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
|
||||
# СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
|
||||
$head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
|
||||
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
|
||||
}
|
||||
$parent = Split-Path $d -Parent
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return "2.17"
|
||||
}
|
||||
|
||||
# --- Фаза 1: Определение типа объекта ---
|
||||
|
||||
# Resolve ObjectPath (directory → .xml)
|
||||
if (-not [System.IO.Path]::IsPathRooted($ObjectPath)) {
|
||||
$ObjectPath = Join-Path (Get-Location).Path $ObjectPath
|
||||
}
|
||||
if (Test-Path $ObjectPath -PathType Container) {
|
||||
$dirName = Split-Path $ObjectPath -Leaf
|
||||
$candidate = Join-Path $ObjectPath "$dirName.xml"
|
||||
$sibling = Join-Path (Split-Path $ObjectPath) "$dirName.xml"
|
||||
if (Test-Path $candidate) { $ObjectPath = $candidate }
|
||||
elseif (Test-Path $sibling) { $ObjectPath = $sibling }
|
||||
}
|
||||
|
||||
if (-not (Test-Path $ObjectPath)) {
|
||||
Write-Error "Файл объекта не найден: $ObjectPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$objectXmlFull = Resolve-Path $ObjectPath
|
||||
Assert-EditAllowed $objectXmlFull.Path 'editable'
|
||||
$script:formatVersion = Detect-FormatVersion (Split-Path $objectXmlFull.Path -Parent)
|
||||
|
||||
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||
$xmlDoc.PreserveWhitespace = $true
|
||||
$xmlDoc.Load($objectXmlFull.Path)
|
||||
|
||||
$nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
|
||||
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||
$nsMgr.AddNamespace("v8", "http://v8.1c.ru/8.1/data/core")
|
||||
|
||||
# Определяем тип объекта по корневому тегу внутри MetaDataObject
|
||||
$metaDataObject = $xmlDoc.SelectSingleNode("//md:MetaDataObject", $nsMgr)
|
||||
if (-not $metaDataObject) {
|
||||
# Пробуем без namespace (fallback)
|
||||
$metaDataObject = $xmlDoc.DocumentElement
|
||||
}
|
||||
|
||||
$supportedTypes = @(
|
||||
"Document", "Catalog", "DataProcessor", "Report",
|
||||
"ExternalDataProcessor", "ExternalReport",
|
||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||
"ExchangePlan", "BusinessProcess", "Task", "DocumentJournal"
|
||||
)
|
||||
|
||||
$objectType = $null
|
||||
$objectNode = $null
|
||||
foreach ($t in $supportedTypes) {
|
||||
$node = $xmlDoc.SelectSingleNode("//md:$t", $nsMgr)
|
||||
if ($node) {
|
||||
$objectType = $t
|
||||
$objectNode = $node
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $objectType) {
|
||||
Write-Error "Не удалось определить тип объекта. Поддерживаемые типы: $($supportedTypes -join ', ')"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Имя объекта из Properties/Name
|
||||
$objectName = $xmlDoc.SelectSingleNode("//md:${objectType}/md:Properties/md:Name", $nsMgr).InnerText
|
||||
if (-not $objectName) {
|
||||
Write-Error "Не удалось определить имя объекта из Properties/Name"
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "=== form-add ==="
|
||||
Write-Host ""
|
||||
Write-Host "Object: $objectType.$objectName"
|
||||
|
||||
# --- Фаза 2: Валидация Purpose ---
|
||||
|
||||
$Purpose = $Purpose.Substring(0,1).ToUpper() + $Purpose.Substring(1).ToLower()
|
||||
# Нормализация
|
||||
switch ($Purpose) {
|
||||
"Object" { }
|
||||
"List" { }
|
||||
"Choice" { }
|
||||
"Record" { }
|
||||
default {
|
||||
Write-Error "Недопустимое назначение: $Purpose. Допустимые: Object, List, Choice, Record"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
$objectLikeTypes = @("Document", "Catalog", "ChartOfAccounts", "ChartOfCharacteristicTypes", "ExchangePlan", "BusinessProcess", "Task")
|
||||
$processorLikeTypes = @("DataProcessor", "Report", "ExternalDataProcessor", "ExternalReport")
|
||||
|
||||
switch ($Purpose) {
|
||||
"Object" {
|
||||
# допустимо для всех типов
|
||||
}
|
||||
"List" {
|
||||
if ($objectType -eq "DataProcessor") {
|
||||
Write-Error "Purpose=List недопустим для DataProcessor"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
"Choice" {
|
||||
if ($objectType -in $processorLikeTypes -or $objectType -eq "InformationRegister") {
|
||||
Write-Error "Purpose=Choice недопустим для $objectType"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
"Record" {
|
||||
if ($objectType -ne "InformationRegister") {
|
||||
Write-Error "Purpose=Record допустим только для InformationRegister"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- Фаза 3: Создание файлов ---
|
||||
|
||||
$objectDir = [System.IO.Path]::ChangeExtension($objectXmlFull.Path, $null).TrimEnd('.')
|
||||
$formsDir = Join-Path $objectDir "Forms"
|
||||
$formMetaPath = Join-Path $formsDir "$FormName.xml"
|
||||
|
||||
if (Test-Path $formMetaPath) {
|
||||
Write-Error "Форма уже существует: $formMetaPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$formDir = Join-Path $formsDir $FormName
|
||||
$formExtDir = Join-Path $formDir "Ext"
|
||||
$formModuleDir = Join-Path $formExtDir "Form"
|
||||
|
||||
New-Item -ItemType Directory -Path $formModuleDir -Force | Out-Null
|
||||
|
||||
$encBom = New-Object System.Text.UTF8Encoding($true)
|
||||
|
||||
# --- 3a. Метаданные формы ---
|
||||
|
||||
$formUuid = [guid]::NewGuid().ToString()
|
||||
|
||||
# ExtendedPresentation — only for DataProcessor, Report, ExternalDataProcessor, ExternalReport forms
|
||||
$extPresentationLine = ""
|
||||
if ($objectType -in $processorLikeTypes) {
|
||||
$extPresentationLine = "`n`t`t`t<ExtendedPresentation/>"
|
||||
}
|
||||
|
||||
$formMetaXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$($script:formatVersion)">
|
||||
<Form uuid="$formUuid">
|
||||
<Properties>
|
||||
<Name>$FormName</Name>
|
||||
<Synonym>
|
||||
<v8:item>
|
||||
<v8:lang>ru</v8:lang>
|
||||
<v8:content>$Synonym</v8:content>
|
||||
</v8:item>
|
||||
</Synonym>
|
||||
<Comment/>
|
||||
<FormType>Managed</FormType>
|
||||
<IncludeHelpInContents>false</IncludeHelpInContents>
|
||||
<UsePurposes>
|
||||
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||
<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>
|
||||
</UsePurposes>$extPresentationLine
|
||||
</Properties>
|
||||
</Form>
|
||||
</MetaDataObject>
|
||||
"@
|
||||
|
||||
[System.IO.File]::WriteAllText($formMetaPath, $formMetaXml, $encBom)
|
||||
|
||||
# --- 3b. Form.xml ---
|
||||
|
||||
$formXmlPath = Join-Path $formExtDir "Form.xml"
|
||||
|
||||
$formNsDecl = 'xmlns="http://v8.1c.ru/8.3/xcf/logform" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core" xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
|
||||
if ($Purpose -eq "List" -or $Purpose -eq "Choice") {
|
||||
# Динамический список
|
||||
# MainTable: тип.имя
|
||||
$mainTable = "$objectType.$objectName"
|
||||
|
||||
$formXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Form $formNsDecl version="$($script:formatVersion)">
|
||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||
<Autofill>true</Autofill>
|
||||
</AutoCommandBar>
|
||||
<ChildItems/>
|
||||
<Attributes>
|
||||
<Attribute name="Список" id="1">
|
||||
<Type>
|
||||
<v8:Type>cfg:DynamicList</v8:Type>
|
||||
</Type>
|
||||
<MainAttribute>true</MainAttribute>
|
||||
<Settings xsi:type="DynamicList">
|
||||
<MainTable>$mainTable</MainTable>
|
||||
</Settings>
|
||||
</Attribute>
|
||||
</Attributes>
|
||||
</Form>
|
||||
"@
|
||||
} elseif ($Purpose -eq "Record") {
|
||||
# Запись регистра сведений
|
||||
$mainAttrName = "Запись"
|
||||
$mainAttrType = "InformationRegisterRecordManager.$objectName"
|
||||
|
||||
$formXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Form $formNsDecl version="$($script:formatVersion)">
|
||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||
<Autofill>true</Autofill>
|
||||
</AutoCommandBar>
|
||||
<ChildItems/>
|
||||
<Attributes>
|
||||
<Attribute name="$mainAttrName" id="1">
|
||||
<Type>
|
||||
<v8:Type>cfg:$mainAttrType</v8:Type>
|
||||
</Type>
|
||||
<MainAttribute>true</MainAttribute>
|
||||
<SavedData>true</SavedData>
|
||||
</Attribute>
|
||||
</Attributes>
|
||||
</Form>
|
||||
"@
|
||||
} else {
|
||||
# Object — форма объекта
|
||||
$mainAttrName = "Объект"
|
||||
|
||||
# Маппинг типа объекта на тип реквизита
|
||||
$attrTypeMap = @{
|
||||
"Document" = "DocumentObject"
|
||||
"Catalog" = "CatalogObject"
|
||||
"DataProcessor" = "DataProcessorObject"
|
||||
"Report" = "ReportObject"
|
||||
"ExternalDataProcessor" = "ExternalDataProcessorObject"
|
||||
"ExternalReport" = "ExternalReportObject"
|
||||
"ChartOfAccounts" = "ChartOfAccountsObject"
|
||||
"ChartOfCharacteristicTypes" = "ChartOfCharacteristicTypesObject"
|
||||
"ExchangePlan" = "ExchangePlanObject"
|
||||
"BusinessProcess" = "BusinessProcessObject"
|
||||
"Task" = "TaskObject"
|
||||
"InformationRegister" = "InformationRegisterRecordManager"
|
||||
"AccumulationRegister" = "AccumulationRegisterRecordSet"
|
||||
}
|
||||
|
||||
$mainAttrType = "$($attrTypeMap[$objectType]).$objectName"
|
||||
|
||||
# SavedData: standard for Catalog/Document/etc, but not for processor-like (DataProcessor/Report/External*)
|
||||
$savedDataLine = ""
|
||||
if ($objectType -notin $processorLikeTypes) {
|
||||
$savedDataLine = "`n`t`t`t<SavedData>true</SavedData>"
|
||||
}
|
||||
|
||||
$formXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Form $formNsDecl version="$($script:formatVersion)">
|
||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||
<Autofill>true</Autofill>
|
||||
</AutoCommandBar>
|
||||
<ChildItems/>
|
||||
<Attributes>
|
||||
<Attribute name="$mainAttrName" id="1">
|
||||
<Type>
|
||||
<v8:Type>cfg:$mainAttrType</v8:Type>
|
||||
</Type>
|
||||
<MainAttribute>true</MainAttribute>$savedDataLine
|
||||
</Attribute>
|
||||
</Attributes>
|
||||
</Form>
|
||||
"@
|
||||
}
|
||||
|
||||
if (Test-Path $formXmlPath) {
|
||||
Write-Host "[SKIP] Form.xml already exists: $formXmlPath — not overwriting"
|
||||
} else {
|
||||
[System.IO.File]::WriteAllText($formXmlPath, $formXml, $encBom)
|
||||
}
|
||||
|
||||
# --- 3c. Module.bsl ---
|
||||
|
||||
$modulePath = Join-Path $formModuleDir "Module.bsl"
|
||||
|
||||
$moduleBsl = @"
|
||||
#Область ОбработчикиСобытийФормы
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ОбработчикиСобытийЭлементовФормы
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ОбработчикиКомандФормы
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область ОбработчикиОповещений
|
||||
|
||||
#КонецОбласти
|
||||
|
||||
#Область СлужебныеПроцедурыИФункции
|
||||
|
||||
#КонецОбласти
|
||||
"@
|
||||
|
||||
if (Test-Path $modulePath) {
|
||||
Write-Host "[SKIP] Module.bsl already exists: $modulePath — not overwriting"
|
||||
} else {
|
||||
[System.IO.File]::WriteAllText($modulePath, $moduleBsl, $encBom)
|
||||
}
|
||||
|
||||
# --- Фаза 4: Регистрация в родительском объекте ---
|
||||
|
||||
$childObjects = $xmlDoc.SelectSingleNode("//md:${objectType}/md:ChildObjects", $nsMgr)
|
||||
if (-not $childObjects) {
|
||||
Write-Error "Не найден элемент ChildObjects в $ObjectPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Добавить <Form>$FormName</Form> — идемпотентно (не дублировать уже зарегистрированную)
|
||||
$alreadyRegistered = [bool]$childObjects.SelectSingleNode("md:Form[text()='$FormName']", $nsMgr)
|
||||
|
||||
if (-not $alreadyRegistered) {
|
||||
$formElem = $xmlDoc.CreateElement("Form", "http://v8.1c.ru/8.3/MDClasses")
|
||||
$formElem.InnerText = $FormName
|
||||
|
||||
# Ищем первый <Template> для вставки перед ним
|
||||
$firstTemplate = $childObjects.SelectSingleNode("md:Template", $nsMgr)
|
||||
# Ищем первую <TabularSection> для вставки перед ней (если нет Template)
|
||||
$firstTabular = $childObjects.SelectSingleNode("md:TabularSection", $nsMgr)
|
||||
|
||||
# Определяем точку вставки: перед Template, перед TabularSection, или в конец
|
||||
$insertBefore = $null
|
||||
if ($firstTemplate) {
|
||||
$insertBefore = $firstTemplate
|
||||
} elseif ($firstTabular) {
|
||||
$insertBefore = $firstTabular
|
||||
}
|
||||
|
||||
if ($insertBefore) {
|
||||
# Вставить перед найденным элементом, с переносом строки
|
||||
$whitespace = $xmlDoc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertBefore($formElem, $insertBefore) | Out-Null
|
||||
$childObjects.InsertBefore($whitespace, $formElem) | Out-Null
|
||||
# Переставляем: whitespace перед formElem — неправильный порядок
|
||||
# Правильно: formElem, затем whitespace перед insertBefore
|
||||
# InsertBefore возвращает вставленный узел, порядок: ... formElem whitespace insertBefore ...
|
||||
# На самом деле нам нужно: ... \n\t\t\tformElem \n\t\t\tinsertBefore
|
||||
# Удалим и вставим правильно
|
||||
$childObjects.RemoveChild($whitespace) | Out-Null
|
||||
$childObjects.RemoveChild($formElem) | Out-Null
|
||||
|
||||
$childObjects.InsertBefore($formElem, $insertBefore) | Out-Null
|
||||
# Whitespace нужен ДО formElem (перенос строки + отступ)
|
||||
# Но перед insertBefore уже должен быть whitespace от предыдущего элемента
|
||||
# Нам нужно добавить whitespace ПОСЛЕ formElem (перед insertBefore)
|
||||
$ws = $xmlDoc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertBefore($ws, $insertBefore) | Out-Null
|
||||
} else {
|
||||
# Добавить в конец ChildObjects
|
||||
if ($childObjects.ChildNodes.Count -eq 0) {
|
||||
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
|
||||
$childObjects.AppendChild($formElem) | Out-Null
|
||||
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t")) | Out-Null
|
||||
} else {
|
||||
$lastChild = $childObjects.LastChild
|
||||
if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
|
||||
$childObjects.InsertBefore($xmlDoc.CreateWhitespace("`n`t`t`t"), $lastChild) | Out-Null
|
||||
$childObjects.InsertBefore($formElem, $lastChild) | Out-Null
|
||||
} else {
|
||||
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
|
||||
$childObjects.AppendChild($formElem) | Out-Null
|
||||
$childObjects.AppendChild($xmlDoc.CreateWhitespace("`n`t`t")) | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- SetDefault ---
|
||||
|
||||
$existingForms = $childObjects.SelectNodes("md:Form", $nsMgr)
|
||||
$isFirstFormForPurpose = $false
|
||||
$defaultPropName = $null
|
||||
$defaultValue = "$objectType.$objectName.Form.$FormName"
|
||||
|
||||
# Определяем имя свойства для DefaultForm
|
||||
switch ($Purpose) {
|
||||
"Object" {
|
||||
if ($objectType -in $processorLikeTypes) {
|
||||
$defaultPropName = "DefaultForm"
|
||||
} else {
|
||||
$defaultPropName = "DefaultObjectForm"
|
||||
}
|
||||
}
|
||||
"List" { $defaultPropName = "DefaultListForm" }
|
||||
"Choice" { $defaultPropName = "DefaultChoiceForm" }
|
||||
"Record" { $defaultPropName = "DefaultRecordForm" }
|
||||
}
|
||||
|
||||
# Проверяем, установлено ли уже значение
|
||||
$defaultNode = $xmlDoc.SelectSingleNode("//md:${objectType}/md:Properties/md:$defaultPropName", $nsMgr)
|
||||
if ($defaultNode) {
|
||||
$isFirstFormForPurpose = [string]::IsNullOrWhiteSpace($defaultNode.InnerText)
|
||||
}
|
||||
|
||||
$defaultUpdated = $false
|
||||
if ($SetDefault -or $isFirstFormForPurpose) {
|
||||
if ($defaultNode) {
|
||||
$defaultNode.InnerText = $defaultValue
|
||||
$defaultUpdated = $true
|
||||
}
|
||||
}
|
||||
|
||||
# Сохранить с BOM
|
||||
$settings = New-Object System.Xml.XmlWriterSettings
|
||||
$settings.Encoding = $encBom
|
||||
$settings.Indent = $false
|
||||
|
||||
$stream = New-Object System.IO.FileStream($objectXmlFull.Path, [System.IO.FileMode]::Create)
|
||||
$writer = [System.Xml.XmlWriter]::Create($stream, $settings)
|
||||
$xmlDoc.Save($writer)
|
||||
$writer.Close()
|
||||
$stream.Close()
|
||||
|
||||
# --- Фаза 5: Вывод ---
|
||||
|
||||
# Относительные пути для вывода
|
||||
$basePath = Split-Path $objectXmlFull.Path -Parent
|
||||
# Определяем корень (ищем родительский каталог типа Documents, Catalogs и т.д.)
|
||||
$relFormMeta = $formMetaPath.Replace($basePath, "").TrimStart("\", "/")
|
||||
$relFormXml = $formXmlPath.Replace($basePath, "").TrimStart("\", "/")
|
||||
$relModule = $modulePath.Replace($basePath, "").TrimStart("\", "/")
|
||||
|
||||
$objFileName = [System.IO.Path]::GetFileName($ObjectPath)
|
||||
$objDirName = Split-Path $ObjectPath -Parent
|
||||
$objBaseName = [System.IO.Path]::GetFileNameWithoutExtension($ObjectPath)
|
||||
|
||||
Write-Host "Created:"
|
||||
Write-Host " Metadata: $objDirName\$objBaseName\Forms\$FormName.xml"
|
||||
Write-Host " Form: $objDirName\$objBaseName\Forms\$FormName\Ext\Form.xml"
|
||||
Write-Host " Module: $objDirName\$objBaseName\Forms\$FormName\Ext\Form\Module.bsl"
|
||||
Write-Host ""
|
||||
if ($alreadyRegistered) {
|
||||
Write-Host "Already registered: <Form>$FormName</Form> in ChildObjects (skipped duplicate)"
|
||||
} else {
|
||||
Write-Host "Registered: <Form>$FormName</Form> in ChildObjects"
|
||||
}
|
||||
if ($defaultUpdated) {
|
||||
Write-Host "${defaultPropName}: $defaultValue"
|
||||
}
|
||||
Write-Host ""
|
||||
@@ -1,693 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# form-add v1.12 — Add managed form to 1C config object
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from lxml import etree
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
|
||||
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
|
||||
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
|
||||
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
|
||||
# ============================================================
|
||||
|
||||
def _sg_root_uuid(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return None
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str) and child.get("uuid"):
|
||||
return child.get("uuid")
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _sg_is_external_root(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return False
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str):
|
||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
|
||||
def _sg_get_edit_mode(cfg_dir):
|
||||
try:
|
||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
||||
if not pj:
|
||||
return "deny"
|
||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
||||
for db in proj.get("databases", []):
|
||||
src = db.get("configSrc")
|
||||
if src:
|
||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
||||
if db.get("editingAllowedCheck"):
|
||||
return db["editingAllowedCheck"]
|
||||
if proj.get("editingAllowedCheck"):
|
||||
return proj["editingAllowedCheck"]
|
||||
return "deny"
|
||||
except Exception:
|
||||
return "deny"
|
||||
|
||||
|
||||
def assert_edit_allowed(target_path, require):
|
||||
try:
|
||||
rp = os.path.abspath(target_path)
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if _sg_is_external_root(rp):
|
||||
return
|
||||
elem_uuid = _sg_root_uuid(rp)
|
||||
cfg_dir = None
|
||||
bin_path = None
|
||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
||||
for _ in range(12):
|
||||
if not d:
|
||||
break
|
||||
if _sg_is_external_root(d + ".xml"):
|
||||
return
|
||||
if not elem_uuid:
|
||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
||||
if not cfg_dir:
|
||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
||||
cfg_dir = d
|
||||
bin_path = cand
|
||||
if elem_uuid and cfg_dir:
|
||||
break
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
if not elem_uuid and cfg_dir:
|
||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
||||
if not bin_path or not os.path.exists(bin_path):
|
||||
return
|
||||
data = open(bin_path, "rb").read()
|
||||
if len(data) <= 32:
|
||||
return
|
||||
if data[:3] == b"\xef\xbb\xbf":
|
||||
data = data[3:]
|
||||
text = data.decode("utf-8", "replace")
|
||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
||||
if not h:
|
||||
return
|
||||
g = int(h.group(1))
|
||||
k = int(h.group(2))
|
||||
if k == 0:
|
||||
return
|
||||
best = None
|
||||
if elem_uuid:
|
||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
||||
f1 = int(m.group(1))
|
||||
if best is None or f1 < best:
|
||||
best = f1
|
||||
blocked = False
|
||||
code = ""
|
||||
reason = ""
|
||||
if g == 1:
|
||||
blocked = True
|
||||
code = "capability-off"
|
||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
||||
elif require == "removed":
|
||||
if best is not None and best != 2:
|
||||
blocked = True
|
||||
code = "not-removed"
|
||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
||||
else:
|
||||
if best is not None and best == 0:
|
||||
blocked = True
|
||||
code = "locked"
|
||||
reason = "объект на замке — редактирование сломает обновления"
|
||||
if not blocked:
|
||||
return
|
||||
mode = _sg_get_edit_mode(cfg_dir)
|
||||
if mode == "off":
|
||||
return
|
||||
if mode == "warn":
|
||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
||||
return
|
||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if code == "capability-off":
|
||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
||||
fix = (
|
||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
)
|
||||
elif code == "not-removed":
|
||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
fix = (
|
||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
||||
)
|
||||
else:
|
||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
fix = (
|
||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
||||
)
|
||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
||||
sys.exit(1)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
NSMAP = {
|
||||
"md": "http://v8.1c.ru/8.3/MDClasses",
|
||||
"v8": "http://v8.1c.ru/8.1/data/core",
|
||||
}
|
||||
|
||||
|
||||
def detect_format_version(d):
|
||||
while d:
|
||||
cfg_path = os.path.join(d, "Configuration.xml")
|
||||
if os.path.isfile(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8-sig") as f:
|
||||
head = f.read(2000)
|
||||
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
|
||||
if m:
|
||||
return m.group(1)
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return "2.17"
|
||||
|
||||
|
||||
def _detect_xml_style(path):
|
||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
||||
try:
|
||||
raw = open(path, "rb").read()
|
||||
except OSError:
|
||||
return None
|
||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||
body = raw[3:] if bom else raw
|
||||
crlf = b"\r\n" in body
|
||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
final_nl = body.endswith(b"\n")
|
||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
||||
|
||||
|
||||
def _finalize_xml_bytes(xml_bytes, style):
|
||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
||||
enc_decl = style["enc"] if style else "utf-8"
|
||||
xml_bytes = xml_bytes.replace(
|
||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
||||
want_final_nl = style["final_nl"] if style else True
|
||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
||||
if want_final_nl:
|
||||
xml_bytes += b"\n"
|
||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
||||
if style and style["crlf"]:
|
||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
||||
return xml_bytes
|
||||
|
||||
|
||||
def save_xml_with_bom(tree, path):
|
||||
"""Save XML tree preserving the existing file's BOM/EOL/encoding-case/final-newline."""
|
||||
style = _detect_xml_style(path)
|
||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||
xml_bytes = _finalize_xml_bytes(xml_bytes, style)
|
||||
with open(path, "wb") as f:
|
||||
if style is None or style["bom"]:
|
||||
f.write(b"\xef\xbb\xbf")
|
||||
f.write(xml_bytes)
|
||||
|
||||
|
||||
def write_text_with_bom(path, text):
|
||||
"""Write text to file with UTF-8 BOM."""
|
||||
with open(path, "w", encoding="utf-8-sig") as f:
|
||||
f.write(text)
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description="Add managed form to 1C config object", allow_abbrev=False)
|
||||
parser.add_argument("-ObjectPath", required=True)
|
||||
parser.add_argument("-FormName", required=True)
|
||||
parser.add_argument("-Synonym", default=None)
|
||||
parser.add_argument("-Purpose", default="Object")
|
||||
parser.add_argument("-SetDefault", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
object_path = args.ObjectPath
|
||||
form_name = args.FormName
|
||||
synonym = args.Synonym if args.Synonym is not None else form_name
|
||||
purpose = args.Purpose
|
||||
set_default = args.SetDefault
|
||||
|
||||
# --- Phase 1: Determine object type ---
|
||||
|
||||
# Resolve ObjectPath (directory → .xml)
|
||||
if not os.path.isabs(object_path):
|
||||
object_path = os.path.join(os.getcwd(), object_path)
|
||||
if os.path.isdir(object_path):
|
||||
dir_name = os.path.basename(object_path.rstrip("/\\"))
|
||||
candidate = os.path.join(object_path, dir_name + ".xml")
|
||||
sibling = os.path.join(os.path.dirname(object_path.rstrip("/\\")), dir_name + ".xml")
|
||||
if os.path.isfile(candidate):
|
||||
object_path = candidate
|
||||
elif os.path.isfile(sibling):
|
||||
object_path = sibling
|
||||
if not os.path.isfile(object_path):
|
||||
print(f"Файл объекта не найден: {object_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
object_xml_full = os.path.abspath(object_path)
|
||||
assert_edit_allowed(object_xml_full, "editable")
|
||||
format_version = detect_format_version(os.path.dirname(object_xml_full))
|
||||
|
||||
parser_xml = etree.XMLParser(remove_blank_text=False)
|
||||
tree = etree.parse(object_xml_full, parser_xml)
|
||||
root = tree.getroot()
|
||||
|
||||
supported_types = [
|
||||
"Document", "Catalog", "DataProcessor", "Report",
|
||||
"ExternalDataProcessor", "ExternalReport",
|
||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||
"ExchangePlan", "BusinessProcess", "Task", "DocumentJournal",
|
||||
]
|
||||
|
||||
object_type = None
|
||||
object_node = None
|
||||
for t in supported_types:
|
||||
node = root.find(f".//md:{t}", NSMAP)
|
||||
if node is not None:
|
||||
object_type = t
|
||||
object_node = node
|
||||
break
|
||||
|
||||
if object_type is None:
|
||||
print(f"Не удалось определить тип объекта. Поддерживаемые типы: {', '.join(supported_types)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Object name from Properties/Name
|
||||
name_node = root.find(f".//md:{object_type}/md:Properties/md:Name", NSMAP)
|
||||
if name_node is None or not name_node.text:
|
||||
print("Не удалось определить имя объекта из Properties/Name", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
object_name = name_node.text
|
||||
|
||||
print()
|
||||
print("=== form-add ===")
|
||||
print()
|
||||
print(f"Object: {object_type}.{object_name}")
|
||||
|
||||
# --- Phase 2: Validate Purpose ---
|
||||
|
||||
# Normalize: capitalize first letter, lowercase rest
|
||||
purpose = purpose[0].upper() + purpose[1:].lower()
|
||||
|
||||
valid_purposes = ["Object", "List", "Choice", "Record"]
|
||||
if purpose not in valid_purposes:
|
||||
print(f"Недопустимое назначение: {purpose}. Допустимые: Object, List, Choice, Record", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
object_like_types = ["Document", "Catalog", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||
"ExchangePlan", "BusinessProcess", "Task"]
|
||||
processor_like_types = ["DataProcessor", "Report", "ExternalDataProcessor", "ExternalReport"]
|
||||
|
||||
if purpose == "List":
|
||||
if object_type == "DataProcessor":
|
||||
print("Purpose=List недопустим для DataProcessor", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
elif purpose == "Choice":
|
||||
if object_type in processor_like_types or object_type == "InformationRegister":
|
||||
print(f"Purpose=Choice недопустим для {object_type}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
elif purpose == "Record":
|
||||
if object_type != "InformationRegister":
|
||||
print("Purpose=Record допустим только для InformationRegister", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# --- Phase 3: Create files ---
|
||||
|
||||
object_dir = os.path.splitext(object_xml_full)[0]
|
||||
forms_dir = os.path.join(object_dir, "Forms")
|
||||
form_meta_path = os.path.join(forms_dir, f"{form_name}.xml")
|
||||
|
||||
if os.path.exists(form_meta_path):
|
||||
print(f"Форма уже существует: {form_meta_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
form_dir = os.path.join(forms_dir, form_name)
|
||||
form_ext_dir = os.path.join(form_dir, "Ext")
|
||||
form_module_dir = os.path.join(form_ext_dir, "Form")
|
||||
|
||||
os.makedirs(form_module_dir, exist_ok=True)
|
||||
|
||||
# --- 3a. Form metadata ---
|
||||
|
||||
form_uuid = str(uuid.uuid4())
|
||||
|
||||
form_meta_xml = (
|
||||
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
'<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses"'
|
||||
' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
|
||||
' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
|
||||
' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"'
|
||||
' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
|
||||
' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
|
||||
' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
|
||||
' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
|
||||
' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
|
||||
' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
|
||||
' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
|
||||
' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
|
||||
' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"'
|
||||
' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"'
|
||||
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
||||
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
f' version="{format_version}">\n'
|
||||
f'\t<Form uuid="{form_uuid}">\n'
|
||||
'\t\t<Properties>\n'
|
||||
f'\t\t\t<Name>{form_name}</Name>\n'
|
||||
'\t\t\t<Synonym>\n'
|
||||
'\t\t\t\t<v8:item>\n'
|
||||
'\t\t\t\t\t<v8:lang>ru</v8:lang>\n'
|
||||
f'\t\t\t\t\t<v8:content>{synonym}</v8:content>\n'
|
||||
'\t\t\t\t</v8:item>\n'
|
||||
'\t\t\t</Synonym>\n'
|
||||
'\t\t\t<Comment/>\n'
|
||||
'\t\t\t<FormType>Managed</FormType>\n'
|
||||
'\t\t\t<IncludeHelpInContents>false</IncludeHelpInContents>\n'
|
||||
'\t\t\t<UsePurposes>\n'
|
||||
'\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>\n'
|
||||
'\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>\n'
|
||||
'\t\t\t</UsePurposes>\n'
|
||||
+ ('\t\t\t<ExtendedPresentation/>\n' if object_type in processor_like_types else '')
|
||||
+ '\t\t</Properties>\n'
|
||||
'\t</Form>\n'
|
||||
'</MetaDataObject>'
|
||||
)
|
||||
|
||||
write_text_with_bom(form_meta_path, form_meta_xml)
|
||||
|
||||
# --- 3b. Form.xml ---
|
||||
|
||||
form_xml_path = os.path.join(form_ext_dir, "Form.xml")
|
||||
|
||||
form_ns_decl = (
|
||||
'xmlns="http://v8.1c.ru/8.3/xcf/logform"'
|
||||
' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
|
||||
' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
|
||||
' xmlns:dcscor="http://v8.1c.ru/8.1/data-composition-system/core"'
|
||||
' xmlns:dcsset="http://v8.1c.ru/8.1/data-composition-system/settings"'
|
||||
' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
|
||||
' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
|
||||
' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
|
||||
' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
|
||||
' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
|
||||
' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
|
||||
' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
|
||||
' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
|
||||
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
||||
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
)
|
||||
|
||||
if purpose in ("List", "Choice"):
|
||||
# Dynamic list
|
||||
main_table = f"{object_type}.{object_name}"
|
||||
|
||||
form_xml = (
|
||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
||||
'\t<AutoCommandBar name="\u0424\u043e\u0440\u043c\u0430\u041a\u043e\u043c\u0430\u043d\u0434\u043d\u0430\u044f\u041f\u0430\u043d\u0435\u043b\u044c" id="-1">\n'
|
||||
'\t\t<Autofill>true</Autofill>\n'
|
||||
'\t</AutoCommandBar>\n'
|
||||
'\t<ChildItems/>\n'
|
||||
'\t<Attributes>\n'
|
||||
'\t\t<Attribute name="\u0421\u043f\u0438\u0441\u043e\u043a" id="1">\n'
|
||||
'\t\t\t<Type>\n'
|
||||
'\t\t\t\t<v8:Type>cfg:DynamicList</v8:Type>\n'
|
||||
'\t\t\t</Type>\n'
|
||||
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
||||
'\t\t\t<Settings xsi:type="DynamicList">\n'
|
||||
f'\t\t\t\t<MainTable>{main_table}</MainTable>\n'
|
||||
'\t\t\t</Settings>\n'
|
||||
'\t\t</Attribute>\n'
|
||||
'\t</Attributes>\n'
|
||||
'</Form>'
|
||||
)
|
||||
|
||||
elif purpose == "Record":
|
||||
# Information register record
|
||||
main_attr_name = "\u0417\u0430\u043f\u0438\u0441\u044c"
|
||||
main_attr_type = f"InformationRegisterRecordManager.{object_name}"
|
||||
|
||||
form_xml = (
|
||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
||||
'\t<AutoCommandBar name="\u0424\u043e\u0440\u043c\u0430\u041a\u043e\u043c\u0430\u043d\u0434\u043d\u0430\u044f\u041f\u0430\u043d\u0435\u043b\u044c" id="-1">\n'
|
||||
'\t\t<Autofill>true</Autofill>\n'
|
||||
'\t</AutoCommandBar>\n'
|
||||
'\t<ChildItems/>\n'
|
||||
'\t<Attributes>\n'
|
||||
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
||||
'\t\t\t<Type>\n'
|
||||
f'\t\t\t\t<v8:Type>cfg:{main_attr_type}</v8:Type>\n'
|
||||
'\t\t\t</Type>\n'
|
||||
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
||||
'\t\t\t<SavedData>true</SavedData>\n'
|
||||
'\t\t</Attribute>\n'
|
||||
'\t</Attributes>\n'
|
||||
'</Form>'
|
||||
)
|
||||
|
||||
else:
|
||||
# Object — object form
|
||||
main_attr_name = "\u041e\u0431\u044a\u0435\u043a\u0442"
|
||||
|
||||
attr_type_map = {
|
||||
"Document": "DocumentObject",
|
||||
"Catalog": "CatalogObject",
|
||||
"DataProcessor": "DataProcessorObject",
|
||||
"Report": "ReportObject",
|
||||
"ExternalDataProcessor": "ExternalDataProcessorObject",
|
||||
"ExternalReport": "ExternalReportObject",
|
||||
"ChartOfAccounts": "ChartOfAccountsObject",
|
||||
"ChartOfCharacteristicTypes": "ChartOfCharacteristicTypesObject",
|
||||
"ExchangePlan": "ExchangePlanObject",
|
||||
"BusinessProcess": "BusinessProcessObject",
|
||||
"Task": "TaskObject",
|
||||
"InformationRegister": "InformationRegisterRecordManager",
|
||||
"AccumulationRegister": "AccumulationRegisterRecordSet",
|
||||
}
|
||||
|
||||
main_attr_type = f"{attr_type_map[object_type]}.{object_name}"
|
||||
|
||||
# SavedData: standard for Catalog/Document/etc, but not for processor-like (DataProcessor/Report/External*)
|
||||
saved_data_line = ''
|
||||
if object_type not in processor_like_types:
|
||||
saved_data_line = '\t\t\t<SavedData>true</SavedData>\n'
|
||||
|
||||
form_xml = (
|
||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
||||
'\t<AutoCommandBar name="\u0424\u043e\u0440\u043c\u0430\u041a\u043e\u043c\u0430\u043d\u0434\u043d\u0430\u044f\u041f\u0430\u043d\u0435\u043b\u044c" id="-1">\n'
|
||||
'\t\t<Autofill>true</Autofill>\n'
|
||||
'\t</AutoCommandBar>\n'
|
||||
'\t<ChildItems/>\n'
|
||||
'\t<Attributes>\n'
|
||||
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
||||
'\t\t\t<Type>\n'
|
||||
f'\t\t\t\t<v8:Type>cfg:{main_attr_type}</v8:Type>\n'
|
||||
'\t\t\t</Type>\n'
|
||||
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
||||
f'{saved_data_line}'
|
||||
'\t\t</Attribute>\n'
|
||||
'\t</Attributes>\n'
|
||||
'</Form>'
|
||||
)
|
||||
|
||||
if os.path.exists(form_xml_path):
|
||||
print(f"[SKIP] Form.xml already exists: {form_xml_path} — not overwriting")
|
||||
else:
|
||||
write_text_with_bom(form_xml_path, form_xml)
|
||||
|
||||
# --- 3c. Module.bsl ---
|
||||
|
||||
module_path = os.path.join(form_module_dir, "Module.bsl")
|
||||
|
||||
module_bsl = (
|
||||
'#\u041e\u0431\u043b\u0430\u0441\u0442\u044c \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438\u0421\u043e\u0431\u044b\u0442\u0438\u0439\u0424\u043e\u0440\u043c\u044b\n'
|
||||
'\n'
|
||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
||||
'\n'
|
||||
'#\u041e\u0431\u043b\u0430\u0441\u0442\u044c \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438\u0421\u043e\u0431\u044b\u0442\u0438\u0439\u042d\u043b\u0435\u043c\u0435\u043d\u0442\u043e\u0432\u0424\u043e\u0440\u043c\u044b\n'
|
||||
'\n'
|
||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
||||
'\n'
|
||||
'#\u041e\u0431\u043b\u0430\u0441\u0442\u044c \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438\u041a\u043e\u043c\u0430\u043d\u0434\u0424\u043e\u0440\u043c\u044b\n'
|
||||
'\n'
|
||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
||||
'\n'
|
||||
'#\u041e\u0431\u043b\u0430\u0441\u0442\u044c \u041e\u0431\u0440\u0430\u0431\u043e\u0442\u0447\u0438\u043a\u0438\u041e\u043f\u043e\u0432\u0435\u0449\u0435\u043d\u0438\u0439\n'
|
||||
'\n'
|
||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
||||
'\n'
|
||||
'#\u041e\u0431\u043b\u0430\u0441\u0442\u044c \u0421\u043b\u0443\u0436\u0435\u0431\u043d\u044b\u0435\u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u044b\u0418\u0424\u0443\u043d\u043a\u0446\u0438\u0438\n'
|
||||
'\n'
|
||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438'
|
||||
)
|
||||
|
||||
if os.path.exists(module_path):
|
||||
print(f"[SKIP] Module.bsl already exists: {module_path} — not overwriting")
|
||||
else:
|
||||
write_text_with_bom(module_path, module_bsl)
|
||||
|
||||
# --- Phase 4: Register in parent object ---
|
||||
|
||||
ns = "http://v8.1c.ru/8.3/MDClasses"
|
||||
child_objects = root.find(f".//md:{object_type}/md:ChildObjects", NSMAP)
|
||||
if child_objects is None:
|
||||
print(f"Не найден элемент ChildObjects в {object_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Add <Form>$FormName</Form> — idempotent (do not duplicate already-registered form)
|
||||
already_registered = child_objects.find(f"md:Form[.='{form_name}']", NSMAP) is not None
|
||||
|
||||
if not already_registered:
|
||||
form_elem = etree.Element(f"{{{ns}}}Form")
|
||||
form_elem.text = form_name
|
||||
|
||||
# Find first <Template> to insert before it
|
||||
first_template = child_objects.find("md:Template", NSMAP)
|
||||
# Find first <TabularSection> to insert before it (if no Template)
|
||||
first_tabular = child_objects.find("md:TabularSection", NSMAP)
|
||||
|
||||
# Determine insertion point: before Template, before TabularSection, or at end
|
||||
insert_before = None
|
||||
if first_template is not None:
|
||||
insert_before = first_template
|
||||
elif first_tabular is not None:
|
||||
insert_before = first_tabular
|
||||
|
||||
if insert_before is not None:
|
||||
# Insert before the found element
|
||||
idx = list(child_objects).index(insert_before)
|
||||
child_objects.insert(idx, form_elem)
|
||||
# Whitespace: form_elem gets "\n\t\t\t" as tail (indent before insert_before)
|
||||
form_elem.tail = "\n\t\t\t"
|
||||
else:
|
||||
# Add to end of ChildObjects
|
||||
children = list(child_objects)
|
||||
if len(children) == 0 and (child_objects.text is None or child_objects.text.strip() == ""):
|
||||
# Empty ChildObjects (self-closing)
|
||||
child_objects.text = "\n\t\t\t"
|
||||
child_objects.append(form_elem)
|
||||
form_elem.tail = "\n\t\t"
|
||||
else:
|
||||
if len(children) > 0:
|
||||
last_child = children[-1]
|
||||
old_tail = last_child.tail
|
||||
last_child.tail = "\n\t\t\t"
|
||||
child_objects.append(form_elem)
|
||||
form_elem.tail = old_tail if old_tail else "\n\t\t"
|
||||
else:
|
||||
child_objects.text = (child_objects.text or "") + "\n\t\t\t"
|
||||
child_objects.append(form_elem)
|
||||
form_elem.tail = "\n\t\t"
|
||||
|
||||
# --- SetDefault ---
|
||||
|
||||
is_first_form_for_purpose = False
|
||||
default_prop_name = None
|
||||
default_value = f"{object_type}.{object_name}.Form.{form_name}"
|
||||
|
||||
# Determine property name for DefaultForm
|
||||
if purpose == "Object":
|
||||
if object_type in processor_like_types:
|
||||
default_prop_name = "DefaultForm"
|
||||
else:
|
||||
default_prop_name = "DefaultObjectForm"
|
||||
elif purpose == "List":
|
||||
default_prop_name = "DefaultListForm"
|
||||
elif purpose == "Choice":
|
||||
default_prop_name = "DefaultChoiceForm"
|
||||
elif purpose == "Record":
|
||||
default_prop_name = "DefaultRecordForm"
|
||||
|
||||
# Check if value is already set
|
||||
default_node = root.find(f".//md:{object_type}/md:Properties/md:{default_prop_name}", NSMAP)
|
||||
if default_node is not None:
|
||||
is_first_form_for_purpose = default_node.text is None or default_node.text.strip() == ""
|
||||
|
||||
default_updated = False
|
||||
if set_default or is_first_form_for_purpose:
|
||||
if default_node is not None:
|
||||
default_node.text = default_value
|
||||
default_updated = True
|
||||
|
||||
# Save with BOM
|
||||
save_xml_with_bom(tree, object_xml_full)
|
||||
|
||||
# --- Phase 5: Output ---
|
||||
|
||||
obj_dir_name = os.path.dirname(object_path)
|
||||
obj_base_name = os.path.splitext(os.path.basename(object_path))[0]
|
||||
|
||||
print("Created:")
|
||||
print(f" Metadata: {obj_dir_name}\\{obj_base_name}\\Forms\\{form_name}.xml")
|
||||
print(f" Form: {obj_dir_name}\\{obj_base_name}\\Forms\\{form_name}\\Ext\\Form.xml")
|
||||
print(f" Module: {obj_dir_name}\\{obj_base_name}\\Forms\\{form_name}\\Ext\\Form\\Module.bsl")
|
||||
print()
|
||||
if already_registered:
|
||||
print(f"Already registered: <Form>{form_name}</Form> in ChildObjects (skipped duplicate)")
|
||||
else:
|
||||
print(f"Registered: <Form>{form_name}</Form> in ChildObjects")
|
||||
if default_updated:
|
||||
print(f"{default_prop_name}: {default_value}")
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,93 +0,0 @@
|
||||
# form-remove v1.4 — Remove form from 1C object
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Alias("ProcessorName")]
|
||||
[string]$ObjectName,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$FormName,
|
||||
|
||||
[string]$SrcDir = "src"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Проверки ---
|
||||
|
||||
$rootXmlPath = Join-Path $SrcDir "$ObjectName.xml"
|
||||
if (-not (Test-Path $rootXmlPath)) {
|
||||
Write-Error "Корневой файл обработки не найден: $rootXmlPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$processorDir = Join-Path $SrcDir $ObjectName
|
||||
$formsDir = Join-Path $processorDir "Forms"
|
||||
$formMetaPath = Join-Path $formsDir "$FormName.xml"
|
||||
$formDir = Join-Path $formsDir $FormName
|
||||
|
||||
if (-not (Test-Path $formMetaPath)) {
|
||||
Write-Error "Метаданные формы не найдены: $formMetaPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- Удаление файлов ---
|
||||
|
||||
if (Test-Path $formDir) {
|
||||
Remove-Item -Path $formDir -Recurse -Force
|
||||
Write-Host "[OK] Удалён каталог: $formDir"
|
||||
}
|
||||
|
||||
Remove-Item -Path $formMetaPath -Force
|
||||
Write-Host "[OK] Удалён файл: $formMetaPath"
|
||||
|
||||
# --- Модификация корневого XML ---
|
||||
|
||||
$rootXmlFull = Resolve-Path $rootXmlPath
|
||||
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||
$xmlDoc.PreserveWhitespace = $true
|
||||
$xmlDoc.Load($rootXmlFull.Path)
|
||||
|
||||
$nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
|
||||
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||
|
||||
# Удалить <Form>FormName</Form> из ChildObjects
|
||||
$formNodes = $xmlDoc.SelectNodes("//md:ChildObjects/md:Form", $nsMgr)
|
||||
foreach ($node in $formNodes) {
|
||||
if ($node.InnerText -eq $FormName) {
|
||||
$parent = $node.ParentNode
|
||||
# Удалить предшествующий whitespace
|
||||
$prev = $node.PreviousSibling
|
||||
if ($prev -and $prev.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
|
||||
$parent.RemoveChild($prev) | Out-Null
|
||||
}
|
||||
$parent.RemoveChild($node) | Out-Null
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# Очистить любые Default*/Auxiliary* form-слоты, указывавшие на удалённую форму
|
||||
# (form-add пишет свойство по назначению: DefaultObjectForm/DefaultListForm/
|
||||
# DefaultChoiceForm/DefaultRecordForm/DefaultForm — не только generic DefaultForm).
|
||||
$formRefRe = "Form\.$([regex]::Escape($FormName))$"
|
||||
foreach ($node in $xmlDoc.SelectNodes("//md:*", $nsMgr)) {
|
||||
if ($node.LocalName -like "*Form" -and $node.InnerText -and $node.InnerText -match $formRefRe) {
|
||||
$node.InnerText = ""
|
||||
}
|
||||
}
|
||||
|
||||
# Сохранить с BOM
|
||||
$encBom = New-Object System.Text.UTF8Encoding($true)
|
||||
$settings = New-Object System.Xml.XmlWriterSettings
|
||||
$settings.Encoding = $encBom
|
||||
$settings.Indent = $false
|
||||
|
||||
$stream = New-Object System.IO.FileStream($rootXmlFull.Path, [System.IO.FileMode]::Create)
|
||||
$writer = [System.Xml.XmlWriter]::Create($stream, $settings)
|
||||
$xmlDoc.Save($writer)
|
||||
$writer.Close()
|
||||
$stream.Close()
|
||||
|
||||
Write-Host "[OK] Форма $FormName удалена из $rootXmlPath"
|
||||
@@ -1,141 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# remove-form v1.4 — Remove form from 1C object
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
from lxml import etree
|
||||
|
||||
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
||||
|
||||
|
||||
def _detect_xml_style(path):
|
||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
||||
try:
|
||||
raw = open(path, "rb").read()
|
||||
except OSError:
|
||||
return None
|
||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
||||
body = raw[3:] if bom else raw
|
||||
crlf = b"\r\n" in body
|
||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
||||
final_nl = body.endswith(b"\n")
|
||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
||||
|
||||
|
||||
def _finalize_xml_bytes(xml_bytes, style):
|
||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
||||
enc_decl = style["enc"] if style else "utf-8"
|
||||
xml_bytes = xml_bytes.replace(
|
||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
||||
want_final_nl = style["final_nl"] if style else True
|
||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
||||
if want_final_nl:
|
||||
xml_bytes += b"\n"
|
||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
||||
if style and style["crlf"]:
|
||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
||||
return xml_bytes
|
||||
|
||||
|
||||
def save_xml_with_bom(tree, path):
|
||||
"""Save XML tree preserving the existing file's BOM/EOL/encoding-case/final-newline."""
|
||||
style = _detect_xml_style(path)
|
||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||
xml_bytes = _finalize_xml_bytes(xml_bytes, style)
|
||||
with open(path, "wb") as f:
|
||||
if style is None or style["bom"]:
|
||||
f.write(b"\xef\xbb\xbf")
|
||||
f.write(xml_bytes)
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description="Remove form from 1C object", allow_abbrev=False)
|
||||
parser.add_argument("-ObjectName", "-ProcessorName", required=True)
|
||||
parser.add_argument("-FormName", required=True)
|
||||
parser.add_argument("-SrcDir", default="src")
|
||||
args = parser.parse_args()
|
||||
|
||||
object_name = args.ObjectName
|
||||
form_name = args.FormName
|
||||
src_dir = args.SrcDir
|
||||
|
||||
# --- Checks ---
|
||||
|
||||
root_xml_path = os.path.join(src_dir, f"{object_name}.xml")
|
||||
if not os.path.exists(root_xml_path):
|
||||
print(f"Корневой файл обработки не найден: {root_xml_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
processor_dir = os.path.join(src_dir, object_name)
|
||||
forms_dir = os.path.join(processor_dir, "Forms")
|
||||
form_meta_path = os.path.join(forms_dir, f"{form_name}.xml")
|
||||
form_dir = os.path.join(forms_dir, form_name)
|
||||
|
||||
if not os.path.exists(form_meta_path):
|
||||
print(f"Метаданные формы не найдены: {form_meta_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# --- Delete files ---
|
||||
|
||||
if os.path.isdir(form_dir):
|
||||
shutil.rmtree(form_dir)
|
||||
print(f"[OK] Удалён каталог: {form_dir}")
|
||||
|
||||
os.remove(form_meta_path)
|
||||
print(f"[OK] Удалён файл: {form_meta_path}")
|
||||
|
||||
# --- Modify root XML ---
|
||||
|
||||
root_xml_full = os.path.abspath(root_xml_path)
|
||||
parser_xml = etree.XMLParser(remove_blank_text=False)
|
||||
tree = etree.parse(root_xml_full, parser_xml)
|
||||
root = tree.getroot()
|
||||
|
||||
# Remove <Form>FormName</Form> from ChildObjects
|
||||
for node in root.findall(".//md:ChildObjects/md:Form", NSMAP):
|
||||
if node.text and node.text.strip() == form_name:
|
||||
parent = node.getparent()
|
||||
prev = node.getprevious()
|
||||
if prev is not None:
|
||||
# Whitespace is in prev.tail
|
||||
if prev.tail and prev.tail.strip() == "":
|
||||
prev.tail = ""
|
||||
else:
|
||||
# First child — whitespace is in parent.text
|
||||
if parent.text and parent.text.strip() == "":
|
||||
parent.text = ""
|
||||
parent.remove(node)
|
||||
break
|
||||
|
||||
# Clear any Default*/Auxiliary* form slot that pointed to the removed form
|
||||
# (form-add writes the purpose-specific property: DefaultObjectForm / DefaultListForm /
|
||||
# DefaultChoiceForm / DefaultRecordForm / DefaultForm — not just generic DefaultForm).
|
||||
ref_re = re.compile(rf"Form\.{re.escape(form_name)}$")
|
||||
for el in root.iter():
|
||||
if not isinstance(el.tag, str):
|
||||
continue
|
||||
if etree.QName(el).localname.endswith("Form") and el.text and ref_re.search(el.text):
|
||||
el.text = ""
|
||||
|
||||
# Save with BOM
|
||||
save_xml_with_bom(tree, root_xml_full)
|
||||
|
||||
print(f"[OK] Форма {form_name} удалена из {root_xml_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,66 +0,0 @@
|
||||
---
|
||||
name: mxl-compile
|
||||
description: Компиляция табличного документа (MXL) из JSON-определения. Используй когда нужно создать макет печатной формы
|
||||
argument-hint: <JsonPath> <OutputPath>
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /mxl-compile — Компилятор макета из DSL
|
||||
|
||||
Принимает компактное JSON-определение макета и генерирует корректный Template.xml для табличного документа 1С. Claude описывает *что* нужно (области, параметры, стили), скрипт обеспечивает *корректность* XML (палитры, индексы, объединения, namespace).
|
||||
|
||||
## Использование
|
||||
|
||||
```
|
||||
/mxl-compile <JsonPath> <OutputPath>
|
||||
```
|
||||
|
||||
## Параметры
|
||||
|
||||
| Параметр | Обязательный | Описание |
|
||||
|------------|:------------:|------------------------------------|
|
||||
| JsonPath | да | Путь к JSON-определению макета |
|
||||
| OutputPath | да | Путь для генерации Template.xml |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/mxl-compile.ps1" -JsonPath "<путь>.json" -OutputPath "<путь>/Template.xml"
|
||||
```
|
||||
|
||||
## Рабочий процесс
|
||||
|
||||
1. Написать JSON-определение (Write tool) → файл `.json`
|
||||
2. Вызвать `/mxl-compile` для генерации Template.xml
|
||||
3. Вызвать `/mxl-validate` для проверки корректности
|
||||
4. Вызвать `/mxl-info` для верификации структуры
|
||||
|
||||
**Если макет создаётся по изображению** (скриншот, скан печатной формы) — сначала вызвать `/img-grid` для наложения сетки, по ней определить границы колонок и пропорции, затем использовать `"Nx"` ширины + `"page"` для автоматического расчёта размеров.
|
||||
|
||||
## JSON-схема DSL
|
||||
|
||||
Ниже — компактная структура и ключевые правила, достаточные для типового макета. Полные таблицы полей (все свойства шрифтов, стилей, ячеек), развёрнутый пример и ограничения формата — в **`reference/dsl-spec.md`**; нужны не всегда, читать по необходимости.
|
||||
|
||||
Краткая структура:
|
||||
|
||||
```
|
||||
{ columns, page, defaultWidth, columnWidths,
|
||||
fonts: { name: { face, size, bold, italic, underline, strikeout } },
|
||||
styles: { name: { font, align, valign, border, borderWidth, wrap, format } },
|
||||
areas: [{ name, rows: [{ height, rowStyle, cells: [
|
||||
{ col, span, rowspan, style, param, detail, text, template }
|
||||
]}]}]
|
||||
}
|
||||
```
|
||||
|
||||
Ключевые правила:
|
||||
- `page` — формат страницы (`"A4-landscape"`, `"A4-portrait"` или число). Автоматически вычисляет `defaultWidth` из суммы пропорций `"Nx"`
|
||||
- `col` — 1-based позиция колонки
|
||||
- `rowStyle` — автозаполнение пустот стилем (рамки по всей ширине)
|
||||
- Тип заполнения определяется автоматически: `param` → Parameter, `text` → Text, `template` → Template
|
||||
- `rowspan` — объединение строк вниз (rowStyle учитывает занятые ячейки)
|
||||
- `empty` в строке — шорткат для N подряд пустых строк (`{ "empty": 3 }` = три `{}`)
|
||||
@@ -1,160 +0,0 @@
|
||||
# Спецификация MXL DSL — JSON-формат описания табличного документа
|
||||
|
||||
Компактный JSON-формат для описания макетов табличных документов 1С (SpreadsheetDocument). Используется навыком `/mxl-compile` (JSON → XML).
|
||||
|
||||
## Пример
|
||||
|
||||
```json
|
||||
{
|
||||
"columns": 10,
|
||||
"defaultWidth": 30,
|
||||
"columnWidths": { "1": 15, "2-8": 40, "9-10": 50 },
|
||||
|
||||
"fonts": {
|
||||
"default": { "face": "Arial", "size": 10 },
|
||||
"bold": { "face": "Arial", "size": 10, "bold": true },
|
||||
"header": { "face": "Arial", "size": 14, "bold": true }
|
||||
},
|
||||
|
||||
"styles": {
|
||||
"default": {},
|
||||
"header": { "font": "header", "align": "center" },
|
||||
"label": { "font": "bold" },
|
||||
"bordered": { "border": "all" },
|
||||
"bordered-right": { "border": "all", "align": "right" },
|
||||
"total-right": { "font": "bold", "border": "top", "align": "right" }
|
||||
},
|
||||
|
||||
"areas": [
|
||||
{
|
||||
"name": "Заголовок",
|
||||
"rows": [
|
||||
{ "height": 20, "cells": [
|
||||
{ "col": 1, "span": 10, "style": "header", "param": "ТекстЗаголовка" }
|
||||
]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "ШапкаТаблицы",
|
||||
"rows": [
|
||||
{ "rowStyle": "bordered", "cells": [
|
||||
{ "col": 1, "text": "№" },
|
||||
{ "col": 2, "span": 6, "text": "Наименование" },
|
||||
{ "col": 9, "text": "Кол-во" },
|
||||
{ "col": 10, "text": "Сумма" }
|
||||
]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Строка",
|
||||
"rows": [
|
||||
{ "rowStyle": "bordered", "cells": [
|
||||
{ "col": 1, "param": "НомерСтроки" },
|
||||
{ "col": 2, "span": 6, "param": "Товар", "detail": "Номенклатура" },
|
||||
{ "col": 9, "style": "bordered-right", "param": "Количество" },
|
||||
{ "col": 10, "style": "bordered-right", "param": "Сумма" }
|
||||
]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Итого",
|
||||
"rows": [
|
||||
{ "cells": [
|
||||
{ "col": 8, "span": 2, "style": "total-right", "text": "Итого:" },
|
||||
{ "col": 10, "style": "total-right", "param": "Всего" }
|
||||
]}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Верхний уровень
|
||||
|
||||
| Поле | Обяз. | По умолч. | Описание |
|
||||
|------|:-----:|-----------|----------|
|
||||
| `columns` | да | — | Количество колонок |
|
||||
| `page` | нет | — | Формат страницы: `"A4-landscape"` (780), `"A4-portrait"` (540) или число. Автоматически вычисляет `defaultWidth` из суммы пропорций `"Nx"` |
|
||||
| `defaultWidth` | нет | 10 | Ширина колонок по умолчанию. Игнорируется если задан `page` и все колонки используют `"Nx"` |
|
||||
| `columnWidths` | нет | `{}` | Ширины колонок. Ключи 1-based: `"1"`, `"3-14"`, `"5,7,9"`. Значения: число (абсолют) или `"Nx"` (множитель от defaultWidth, напр. `"2x"`, `"0.5x"`) |
|
||||
| `fonts` | нет | — | Именованные шрифты (если не задано, создаётся Arial 10) |
|
||||
| `styles` | нет | `{}` | Именованные стили |
|
||||
| `areas` | да | — | Массив именованных областей (порядок = порядок в документе) |
|
||||
|
||||
## Шрифты (`fonts.<name>`)
|
||||
|
||||
| Поле | По умолч. | Описание |
|
||||
|------|-----------|----------|
|
||||
| `face` | `"Arial"` | Имя шрифта |
|
||||
| `size` | `10` | Размер |
|
||||
| `bold` | `false` | Жирный |
|
||||
| `italic` | `false` | Курсив |
|
||||
| `underline` | `false` | Подчёркнутый |
|
||||
| `strikeout` | `false` | Зачёркнутый |
|
||||
|
||||
Шрифт `"default"` используется когда стиль не указывает шрифт явно. Если не определён, создаётся автоматически (Arial 10).
|
||||
|
||||
## Стили (`styles.<name>`)
|
||||
|
||||
| Поле | По умолч. | Описание |
|
||||
|------|-----------|----------|
|
||||
| `font` | `"default"` | Ссылка на имя шрифта |
|
||||
| `align` | — | `left`, `center`, `right` |
|
||||
| `valign` | — | `top`, `center` |
|
||||
| `border` | — | Стороны рамки: `all`, `top`, `bottom`, `left`, `right`, `none`. Через запятую: `"top,bottom"` |
|
||||
| `borderWidth` | `"thin"` | Толщина рамки: `thin` (1px) или `thick` (2px) |
|
||||
| `wrap` | `false` | Перенос текста |
|
||||
| `format` | — | Формат данных 1С: `"ЧЦ=15; ЧДЦ=2"`, `"ДФ=dd.MM.yyyy"` и т.д. |
|
||||
|
||||
## Области (`areas[]`)
|
||||
|
||||
| Поле | Обяз. | Описание |
|
||||
|------|:-----:|----------|
|
||||
| `name` | да | Имя области для `Макет.ПолучитьОбласть("Имя")` |
|
||||
| `rows` | да | Массив строк |
|
||||
|
||||
## Строки (`rows[]`)
|
||||
|
||||
| Поле | По умолч. | Описание |
|
||||
|------|-----------|----------|
|
||||
| `height` | — | Высота строки (если не задана, используется авто) |
|
||||
| `rowStyle` | — | Стиль для ВСЕХ колонок (заполняет пустоты рамками) |
|
||||
| `cells` | `[]` | Массив ячеек |
|
||||
| `empty` | — | Количество подряд идущих пустых строк (заменяет N отдельных `{}`) |
|
||||
|
||||
Строка без `cells` и `rowStyle` → пустая строка. `{ "empty": 3 }` эквивалентно трём `{}`.
|
||||
|
||||
## Ячейки (`cells[]`)
|
||||
|
||||
| Поле | Обяз. | По умолч. | Описание |
|
||||
|------|:-----:|-----------|----------|
|
||||
| `col` | да | — | Позиция колонки (1-based) |
|
||||
| `span` | нет | `1` | Объединение по горизонтали (количество колонок) |
|
||||
| `rowspan` | нет | `1` | Объединение по вертикали (количество строк) |
|
||||
| `style` | нет | rowStyle | Стиль ячейки (переопределяет rowStyle) |
|
||||
| `param` | нет | — | Параметр заполнения |
|
||||
| `detail` | нет | — | Параметр расшифровки (только с `param`) |
|
||||
| `text` | нет | — | Статический текст |
|
||||
| `template` | нет | — | Шаблонный текст с `[Параметр]` |
|
||||
|
||||
### Тип заполнения
|
||||
|
||||
Определяется автоматически по содержимому ячейки:
|
||||
- `param` → fillType=Parameter
|
||||
- `template` → fillType=Template
|
||||
- `text` → fillType=Text
|
||||
- ничего → без fillType (пустая ячейка или рамка)
|
||||
|
||||
## `rowStyle` — автозаполнение
|
||||
|
||||
Когда задан `rowStyle`, компилятор создаёт ячейки для ВСЕХ колонок строки. Позиции без явных ячеек заполняются пустыми ячейками с указанным стилем. Это обеспечивает сплошные рамки в табличных строках.
|
||||
|
||||
Если в предыдущих строках той же области есть ячейки с `rowspan`, их колонки при автозаполнении пропускаются.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Текущая версия не поддерживает:
|
||||
- Множественные наборы колонок (`columnsID`)
|
||||
- Области типа Columns / Rectangle
|
||||
- Рисунки (штрихкоды, картинки)
|
||||
- Фон ячеек
|
||||
@@ -1,868 +0,0 @@
|
||||
# mxl-compile v1.5 — Compile 1C spreadsheet from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$JsonPath,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$OutputPath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Support guard (Ext/ParentConfigurations.bin) ---
|
||||
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
|
||||
# read-only configs unless allowed. Trigger = bin present; reaction from
|
||||
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
|
||||
# throws — guard errors degrade to allow.
|
||||
function Get-RootUuid([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $null }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
|
||||
} catch {}
|
||||
return $null
|
||||
}
|
||||
function Test-ExternalObjectRoot([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $false }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
||||
} catch {}
|
||||
return $false
|
||||
}
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Get-EditMode([string]$cfgDir) {
|
||||
try {
|
||||
$pj = Find-V8Project (Get-Location).Path
|
||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
||||
if (-not $pj) { return 'deny' }
|
||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
||||
if ($proj.databases) {
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($db.configSrc) {
|
||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
||||
return 'deny'
|
||||
} catch { return 'deny' }
|
||||
}
|
||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
||||
try {
|
||||
$rp = $targetPath
|
||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if (Test-ExternalObjectRoot $rp) { return }
|
||||
$elemUuid = Get-RootUuid $rp
|
||||
$cfgDir = $null; $binPath = $null
|
||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
||||
if (-not $cfgDir) {
|
||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
||||
}
|
||||
if ($elemUuid -and $cfgDir) { break }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
# New object (no element file): fall back to config root uuid.
|
||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
||||
if ($bytes.Length -le 32) { return }
|
||||
$start = 0
|
||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
||||
if (-not $hm.Success) { return }
|
||||
$G = [int]$hm.Groups[1].Value
|
||||
$K = [int]$hm.Groups[2].Value
|
||||
if ($K -eq 0) { return }
|
||||
$best = $null
|
||||
if ($elemUuid) {
|
||||
$u = [regex]::Escape($elemUuid.ToLower())
|
||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
||||
$f1 = [int]$m.Groups[1].Value
|
||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
||||
}
|
||||
}
|
||||
$blocked = $false; $code = ""; $reason = ""
|
||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
||||
elseif ($require -eq 'removed') {
|
||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
||||
}
|
||||
else {
|
||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
||||
}
|
||||
if (-not $blocked) { return }
|
||||
$mode = Get-EditMode $cfgDir
|
||||
if ($mode -eq 'off') { return }
|
||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
||||
# latter throws and would be swallowed by this function's own catch.
|
||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if ($code -eq "capability-off") {
|
||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
} elseif ($code -eq "not-removed") {
|
||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
||||
} else {
|
||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
||||
}
|
||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
||||
exit 1
|
||||
} catch { return }
|
||||
}
|
||||
|
||||
# --- 1. Load and validate JSON ---
|
||||
|
||||
if (-not (Test-Path $JsonPath)) {
|
||||
Write-Error "File not found: $JsonPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$json = Get-Content -Raw -Encoding UTF8 $JsonPath
|
||||
$def = $json | ConvertFrom-Json
|
||||
|
||||
if (-not $def.columns) {
|
||||
Write-Error "Required field 'columns' is missing"
|
||||
exit 1
|
||||
}
|
||||
if (-not $def.areas) {
|
||||
Write-Error "Required field 'areas' is missing"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$totalColumns = [int]$def.columns
|
||||
$defaultWidth = if ($def.defaultWidth) { [int]$def.defaultWidth } else { 10 }
|
||||
|
||||
# --- 2. Build font palette ---
|
||||
|
||||
$fontMap = [ordered]@{} # name -> 0-based index
|
||||
$fontEntries = @() # array of hashtables
|
||||
|
||||
function Add-Font {
|
||||
param([string]$name, $fontDef)
|
||||
$face = if ($fontDef.face) { $fontDef.face } else { "Arial" }
|
||||
$size = if ($fontDef.size) { [int]$fontDef.size } else { 10 }
|
||||
$bold = if ($fontDef.bold -eq $true) { "true" } else { "false" }
|
||||
$italic = if ($fontDef.italic -eq $true) { "true" } else { "false" }
|
||||
$underline = if ($fontDef.underline -eq $true) { "true" } else { "false" }
|
||||
$strikeout = if ($fontDef.strikeout -eq $true) { "true" } else { "false" }
|
||||
|
||||
$idx = $script:fontEntries.Count
|
||||
$script:fontMap[$name] = $idx
|
||||
$script:fontEntries += @{
|
||||
Face = $face
|
||||
Size = $size
|
||||
Bold = $bold
|
||||
Italic = $italic
|
||||
Underline = $underline
|
||||
Strikeout = $strikeout
|
||||
}
|
||||
}
|
||||
|
||||
# Add user-defined fonts
|
||||
$hasDefault = $false
|
||||
if ($def.fonts) {
|
||||
foreach ($prop in $def.fonts.PSObject.Properties) {
|
||||
if ($prop.Name -eq "default") { $hasDefault = $true }
|
||||
Add-Font -name $prop.Name -fontDef $prop.Value
|
||||
}
|
||||
}
|
||||
|
||||
# Ensure default font exists
|
||||
if (-not $hasDefault) {
|
||||
$defaultDef = New-Object PSObject -Property @{ face = "Arial"; size = 10 }
|
||||
Add-Font -name "default" -fontDef $defaultDef
|
||||
}
|
||||
|
||||
# --- 3. Determine line palette ---
|
||||
|
||||
$hasThinBorders = $false
|
||||
$hasThickBorders = $false
|
||||
|
||||
# Scan styles for border usage
|
||||
if ($def.styles) {
|
||||
foreach ($prop in $def.styles.PSObject.Properties) {
|
||||
$s = $prop.Value
|
||||
if ($s.border -and $s.border -ne "none") {
|
||||
if ($s.borderWidth -eq "thick") {
|
||||
$hasThickBorders = $true
|
||||
} else {
|
||||
$hasThinBorders = $true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$thinLineIndex = -1
|
||||
$thickLineIndex = -1
|
||||
$lineCount = 0
|
||||
if ($hasThinBorders) {
|
||||
$thinLineIndex = $lineCount; $lineCount++
|
||||
}
|
||||
if ($hasThickBorders) {
|
||||
$thickLineIndex = $lineCount; $lineCount++
|
||||
}
|
||||
|
||||
# --- 4. Parse column width specs ---
|
||||
|
||||
function Parse-ColumnSpec {
|
||||
param([string]$spec)
|
||||
$cols = @()
|
||||
foreach ($part in $spec -split ',') {
|
||||
$part = $part.Trim()
|
||||
if ($part -match '^(\d+)-(\d+)$') {
|
||||
$from = [int]$Matches[1]
|
||||
$to = [int]$Matches[2]
|
||||
for ($i = $from; $i -le $to; $i++) { $cols += $i }
|
||||
} else {
|
||||
$cols += [int]$part
|
||||
}
|
||||
}
|
||||
return $cols
|
||||
}
|
||||
|
||||
# --- 4a. Auto-calculate defaultWidth from page format ---
|
||||
|
||||
$pageTargets = @{
|
||||
"A4-landscape" = 780
|
||||
"A4-portrait" = 540
|
||||
}
|
||||
|
||||
if ($def.page) {
|
||||
$pageName = "$($def.page)"
|
||||
$targetWidth = $null
|
||||
|
||||
if ($pageName -match '^\d+$') {
|
||||
$targetWidth = [int]$pageName
|
||||
} elseif ($pageTargets.ContainsKey($pageName)) {
|
||||
$targetWidth = $pageTargets[$pageName]
|
||||
} else {
|
||||
Write-Warning "Unknown page format '$pageName'. Known: $($pageTargets.Keys -join ', '), or a number."
|
||||
}
|
||||
|
||||
if ($targetWidth) {
|
||||
$totalUnits = 0.0
|
||||
$absoluteSum = 0
|
||||
$specifiedCols = @{}
|
||||
|
||||
if ($def.columnWidths) {
|
||||
foreach ($prop in $def.columnWidths.PSObject.Properties) {
|
||||
$val = "$($prop.Value)"
|
||||
$cols = Parse-ColumnSpec $prop.Name
|
||||
foreach ($c in $cols) {
|
||||
$specifiedCols[[int]$c] = $true
|
||||
if ($val -match '^([0-9.]+)x$') {
|
||||
$totalUnits += [double]$Matches[1]
|
||||
} else {
|
||||
$absoluteSum += [int]$val
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ($c = 1; $c -le $totalColumns; $c++) {
|
||||
if (-not $specifiedCols.ContainsKey($c)) {
|
||||
$totalUnits += 1.0
|
||||
}
|
||||
}
|
||||
|
||||
if ($totalUnits -gt 0) {
|
||||
$defaultWidth = [int][math]::Round(($targetWidth - $absoluteSum) / $totalUnits)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Build column width map: 1-based col -> width
|
||||
$colWidthMap = @{}
|
||||
if ($def.columnWidths) {
|
||||
foreach ($prop in $def.columnWidths.PSObject.Properties) {
|
||||
$val = "$($prop.Value)"
|
||||
if ($val -match '^([0-9.]+)x$') {
|
||||
$width = [int][math]::Round([double]$Matches[1] * $defaultWidth)
|
||||
} else {
|
||||
$width = [int]$val
|
||||
}
|
||||
$columns = Parse-ColumnSpec $prop.Name
|
||||
foreach ($c in $columns) {
|
||||
$colWidthMap[$c] = $width
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- 5. Style resolver ---
|
||||
|
||||
function Resolve-Style {
|
||||
param([string]$styleName, [string]$fillType)
|
||||
|
||||
$fontIdx = $fontMap["default"]
|
||||
$lb = -1; $tb = -1; $rb = -1; $bb = -1
|
||||
$ha = ""; $va = ""; $nf = ""
|
||||
$wrap = $false
|
||||
|
||||
if ($styleName -and $def.styles) {
|
||||
$style = $def.styles.$styleName
|
||||
if ($style) {
|
||||
# Font
|
||||
if ($style.font -and $fontMap.Contains($style.font)) {
|
||||
$fontIdx = $fontMap[$style.font]
|
||||
}
|
||||
|
||||
# Borders
|
||||
if ($style.border -and $style.border -ne "none") {
|
||||
$lineIdx = if ($style.borderWidth -eq "thick") { $thickLineIndex } else { $thinLineIndex }
|
||||
foreach ($side in ($style.border -split ',')) {
|
||||
switch ($side.Trim()) {
|
||||
"all" { $lb = $lineIdx; $tb = $lineIdx; $rb = $lineIdx; $bb = $lineIdx }
|
||||
"left" { $lb = $lineIdx }
|
||||
"top" { $tb = $lineIdx }
|
||||
"right" { $rb = $lineIdx }
|
||||
"bottom" { $bb = $lineIdx }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Alignment
|
||||
if ($style.align) {
|
||||
switch ($style.align) {
|
||||
"left" { $ha = "Left" }
|
||||
"center" { $ha = "Center" }
|
||||
"right" { $ha = "Right" }
|
||||
}
|
||||
}
|
||||
if ($style.valign) {
|
||||
switch ($style.valign) {
|
||||
"top" { $va = "Top" }
|
||||
"center" { $va = "Center" }
|
||||
}
|
||||
}
|
||||
|
||||
# Wrap
|
||||
if ($style.wrap -eq $true) { $wrap = $true }
|
||||
|
||||
# Number format
|
||||
if ($style.format) { $nf = $style.format }
|
||||
}
|
||||
}
|
||||
|
||||
return @{
|
||||
FontIdx = $fontIdx
|
||||
LB = $lb; TB = $tb; RB = $rb; BB = $bb
|
||||
HA = $ha; VA = $va
|
||||
Wrap = $wrap
|
||||
FillType = $fillType
|
||||
NumberFormat = $nf
|
||||
}
|
||||
}
|
||||
|
||||
# --- 6. Format palette builder ---
|
||||
|
||||
$formatRegistry = [ordered]@{} # key -> hashtable with properties
|
||||
$formatOrder = @() # ordered keys for index assignment
|
||||
|
||||
function Get-FormatKey {
|
||||
param(
|
||||
[int]$fontIdx = -1,
|
||||
[int]$lb = -1, [int]$tb = -1, [int]$rb = -1, [int]$bb = -1,
|
||||
[string]$ha = "", [string]$va = "",
|
||||
[bool]$wrap = $false,
|
||||
[string]$fillType = "",
|
||||
[string]$numberFormat = "",
|
||||
[int]$width = -1,
|
||||
[int]$height = -1
|
||||
)
|
||||
return "f=$fontIdx|lb=$lb|tb=$tb|rb=$rb|bb=$bb|ha=$ha|va=$va|wr=$wrap|ft=$fillType|nf=$numberFormat|w=$width|h=$height"
|
||||
}
|
||||
|
||||
function Register-Format {
|
||||
param([string]$key, [hashtable]$props)
|
||||
if (-not $script:formatRegistry.Contains($key)) {
|
||||
$script:formatRegistry[$key] = $props
|
||||
$script:formatOrder += $key
|
||||
}
|
||||
# Return 1-based index
|
||||
$idx = 0
|
||||
foreach ($k in $script:formatRegistry.Keys) {
|
||||
$idx++
|
||||
if ($k -eq $key) { return $idx }
|
||||
}
|
||||
return $idx
|
||||
}
|
||||
|
||||
# 6a. Default width format
|
||||
$defaultFormatKey = Get-FormatKey -width $defaultWidth
|
||||
$defaultFormatIndex = Register-Format -key $defaultFormatKey -props @{ Width = $defaultWidth }
|
||||
|
||||
# 6b. Column width formats
|
||||
$colFormatMap = @{} # 1-based col -> format index
|
||||
foreach ($col in ($colWidthMap.Keys | Sort-Object)) {
|
||||
$w = $colWidthMap[$col]
|
||||
$key = Get-FormatKey -width $w
|
||||
$idx = Register-Format -key $key -props @{ Width = $w }
|
||||
$colFormatMap[[int]$col] = $idx
|
||||
}
|
||||
|
||||
# 6c. Scan areas for row heights and cell formats
|
||||
# We need to do two passes: first collect all formats, then generate XML
|
||||
|
||||
# Helper: escape XML special characters
|
||||
function Esc-Xml {
|
||||
# Экранирование ТЕКСТА элемента: только & < > . Кавычки в тексте платформа НЕ экранирует —
|
||||
# пишет литерально (проверено: 92142 сырых кавычки на корпус, ни одной "). " платформа
|
||||
# принимает, но при выгрузке нормализует обратно в кавычку → лишний шум в роундтрипе.
|
||||
param([string]$s)
|
||||
return $s.Replace('&','&').Replace('<','<').Replace('>','>')
|
||||
}
|
||||
|
||||
# Helper: determine fillType from cell content
|
||||
function Get-FillType {
|
||||
param($cell)
|
||||
if ($cell.param) { return "Parameter" }
|
||||
if ($cell.template) { return "Template" }
|
||||
if ($cell.text) { return "Text" }
|
||||
return ""
|
||||
}
|
||||
|
||||
# Helper: register a cell format and return its index
|
||||
function Register-CellFormat {
|
||||
param($styleName, [string]$fillType)
|
||||
$resolved = Resolve-Style -styleName $styleName -fillType $fillType
|
||||
$key = Get-FormatKey -fontIdx $resolved.FontIdx `
|
||||
-lb $resolved.LB -tb $resolved.TB -rb $resolved.RB -bb $resolved.BB `
|
||||
-ha $resolved.HA -va $resolved.VA `
|
||||
-wrap $resolved.Wrap -fillType $resolved.FillType `
|
||||
-numberFormat $resolved.NumberFormat
|
||||
$props = @{
|
||||
FontIdx = $resolved.FontIdx
|
||||
LB = $resolved.LB; TB = $resolved.TB
|
||||
RB = $resolved.RB; BB = $resolved.BB
|
||||
HA = $resolved.HA; VA = $resolved.VA
|
||||
Wrap = $resolved.Wrap
|
||||
FillType = $resolved.FillType
|
||||
NumberFormat = $resolved.NumberFormat
|
||||
}
|
||||
return Register-Format -key $key -props $props
|
||||
}
|
||||
|
||||
# Pre-register all formats from areas
|
||||
foreach ($area in $def.areas) {
|
||||
foreach ($row in $area.rows) {
|
||||
# Skip empty row placeholder
|
||||
if ($row.empty) { continue }
|
||||
|
||||
# Row height format
|
||||
if ($row.height) {
|
||||
$hKey = Get-FormatKey -height ([int]$row.height)
|
||||
Register-Format -key $hKey -props @{ Height = [int]$row.height } | Out-Null
|
||||
}
|
||||
|
||||
# rowStyle gap-fill format (no content → no fillType)
|
||||
if ($row.rowStyle) {
|
||||
Register-CellFormat -styleName $row.rowStyle -fillType "" | Out-Null
|
||||
}
|
||||
|
||||
# Explicit cell formats
|
||||
if ($row.cells) {
|
||||
foreach ($cell in $row.cells) {
|
||||
$cellStyle = if ($cell.style) { $cell.style } elseif ($row.rowStyle) { $row.rowStyle } else { "default" }
|
||||
$ft = Get-FillType $cell
|
||||
Register-CellFormat -styleName $cellStyle -fillType $ft | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- 7. Generate XML ---
|
||||
|
||||
$xml = New-Object System.Text.StringBuilder 4096
|
||||
|
||||
function X {
|
||||
param([string]$text)
|
||||
$script:xml.AppendLine($text) | Out-Null
|
||||
}
|
||||
|
||||
# 7a. Header
|
||||
X '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
X '<document xmlns="http://v8.1c.ru/8.2/data/spreadsheet" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
|
||||
|
||||
# 7b. Language settings
|
||||
X "`t<languageSettings>"
|
||||
X "`t`t<currentLanguage>ru</currentLanguage>"
|
||||
X "`t`t<defaultLanguage>ru</defaultLanguage>"
|
||||
X "`t`t<languageInfo>"
|
||||
X "`t`t`t<id>ru</id>"
|
||||
X "`t`t`t<code>Русский</code>"
|
||||
X "`t`t`t<description>Русский</description>"
|
||||
X "`t`t</languageInfo>"
|
||||
X "`t</languageSettings>"
|
||||
|
||||
# 7c. Columns
|
||||
X "`t<columns>"
|
||||
X "`t`t<size>$totalColumns</size>"
|
||||
|
||||
# Emit columnsItem for columns with non-default widths
|
||||
foreach ($col in ($colFormatMap.Keys | Sort-Object)) {
|
||||
$fmtIdx = $colFormatMap[$col]
|
||||
$colIdx = $col - 1 # Convert to 0-based
|
||||
X "`t`t<columnsItem>"
|
||||
X "`t`t`t<index>$colIdx</index>"
|
||||
X "`t`t`t<column>"
|
||||
X "`t`t`t`t<formatIndex>$fmtIdx</formatIndex>"
|
||||
X "`t`t`t</column>"
|
||||
X "`t`t</columnsItem>"
|
||||
}
|
||||
|
||||
X "`t</columns>"
|
||||
|
||||
# 7d. Rows — main generation loop
|
||||
$globalRow = 0
|
||||
$merges = @()
|
||||
$namedItems = @()
|
||||
$totalRowCount = 0
|
||||
|
||||
foreach ($area in $def.areas) {
|
||||
$areaStartRow = $globalRow
|
||||
$areaName = $area.name
|
||||
$activeRowspans = @() # @{ColStart=1-based; ColEnd=1-based; EndLocalRow=int}
|
||||
$localRow = 0
|
||||
|
||||
foreach ($row in $area.rows) {
|
||||
# Empty row placeholder: emit N empty rows
|
||||
if ($row.empty) {
|
||||
$count = [int]$row.empty
|
||||
for ($ei = 0; $ei -lt $count; $ei++) {
|
||||
X "`t<rowsItem>"
|
||||
X "`t`t<index>$globalRow</index>"
|
||||
X "`t`t<row>"
|
||||
X "`t`t`t<empty>true</empty>"
|
||||
X "`t`t</row>"
|
||||
X "`t</rowsItem>"
|
||||
$globalRow++; $localRow++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
# Build set of columns occupied by rowspans from previous rows
|
||||
$rowspanOccupied = @{} # 1-based col -> $true
|
||||
foreach ($rs in $activeRowspans) {
|
||||
if ($localRow -gt $rs.StartLocalRow -and $localRow -le $rs.EndLocalRow) {
|
||||
for ($c = $rs.ColStart; $c -le $rs.ColEnd; $c++) {
|
||||
$rowspanOccupied[$c] = $true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$rowHasContent = $false
|
||||
$rowCells = @() # array of { Col(0-based), FormatIdx, Content }
|
||||
|
||||
# Determine row height format
|
||||
$rowFormatIdx = 0
|
||||
if ($row.height) {
|
||||
$hKey = Get-FormatKey -height ([int]$row.height)
|
||||
# Find format index for this key
|
||||
$rIdx = 0
|
||||
foreach ($k in $formatRegistry.Keys) {
|
||||
$rIdx++
|
||||
if ($k -eq $hKey) { $rowFormatIdx = $rIdx; break }
|
||||
}
|
||||
}
|
||||
|
||||
if ($row.cells -and $row.cells.Count -gt 0) {
|
||||
$rowHasContent = $true
|
||||
|
||||
# Build set of occupied columns (1-based): explicit cells + rowspan from above
|
||||
$occupiedCols = @{}
|
||||
foreach ($rsk in $rowspanOccupied.Keys) { $occupiedCols[$rsk] = $true }
|
||||
foreach ($cell in $row.cells) {
|
||||
$colStart = [int]$cell.col
|
||||
$colSpan = if ($cell.span) { [int]$cell.span } else { 1 }
|
||||
for ($c = $colStart; $c -lt ($colStart + $colSpan); $c++) {
|
||||
$occupiedCols[$c] = $true
|
||||
}
|
||||
}
|
||||
|
||||
# Generate explicit cells
|
||||
foreach ($cell in $row.cells) {
|
||||
$colStart = [int]$cell.col
|
||||
$colSpan = if ($cell.span) { [int]$cell.span } else { 1 }
|
||||
$rowspan = if ($cell.rowspan) { [int]$cell.rowspan } else { 1 }
|
||||
$cellStyle = if ($cell.style) { $cell.style } elseif ($row.rowStyle) { $row.rowStyle } else { "default" }
|
||||
$ft = Get-FillType $cell
|
||||
$fmtIdx = Register-CellFormat -styleName $cellStyle -fillType $ft
|
||||
|
||||
$cellInfo = @{
|
||||
Col = $colStart - 1 # 0-based
|
||||
FormatIdx = $fmtIdx
|
||||
Param = $cell.param
|
||||
Detail = $cell.detail
|
||||
Text = $cell.text
|
||||
Template = $cell.template
|
||||
}
|
||||
$rowCells += $cellInfo
|
||||
|
||||
# Track rowspan for subsequent rows
|
||||
if ($rowspan -gt 1) {
|
||||
$activeRowspans += @{
|
||||
ColStart = $colStart
|
||||
ColEnd = $colStart + $colSpan - 1
|
||||
StartLocalRow = $localRow
|
||||
EndLocalRow = $localRow + $rowspan - 1
|
||||
}
|
||||
}
|
||||
|
||||
# Collect merge (horizontal, vertical, or both)
|
||||
if ($colSpan -gt 1 -or $rowspan -gt 1) {
|
||||
$merge = @{ R = $globalRow; C = $colStart - 1; W = $colSpan - 1 }
|
||||
if ($rowspan -gt 1) { $merge.H = $rowspan - 1 }
|
||||
$merges += $merge
|
||||
}
|
||||
}
|
||||
|
||||
# Generate gap-fill cells for rowStyle
|
||||
if ($row.rowStyle) {
|
||||
$gapFmtIdx = Register-CellFormat -styleName $row.rowStyle -fillType ""
|
||||
for ($c = 1; $c -le $totalColumns; $c++) {
|
||||
if (-not $occupiedCols.ContainsKey($c)) {
|
||||
$rowCells += @{
|
||||
Col = $c - 1 # 0-based
|
||||
FormatIdx = $gapFmtIdx
|
||||
Param = $null
|
||||
Detail = $null
|
||||
Text = $null
|
||||
Template = $null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Sort cells by column
|
||||
$rowCells = $rowCells | Sort-Object { $_.Col }
|
||||
|
||||
} elseif ($row.rowStyle) {
|
||||
# Row with only rowStyle, no explicit cells — fill non-rowspan columns
|
||||
$rowHasContent = $true
|
||||
$gapFmtIdx = Register-CellFormat -styleName $row.rowStyle -fillType ""
|
||||
for ($c = 1; $c -le $totalColumns; $c++) {
|
||||
if ($rowspanOccupied.ContainsKey($c)) { continue }
|
||||
$rowCells += @{
|
||||
Col = $c - 1
|
||||
FormatIdx = $gapFmtIdx
|
||||
Param = $null
|
||||
Detail = $null
|
||||
Text = $null
|
||||
Template = $null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Emit rowsItem
|
||||
X "`t<rowsItem>"
|
||||
X "`t`t<index>$globalRow</index>"
|
||||
X "`t`t<row>"
|
||||
|
||||
if ($rowFormatIdx -gt 0) {
|
||||
X "`t`t`t<formatIndex>$rowFormatIdx</formatIndex>"
|
||||
}
|
||||
|
||||
if (-not $rowHasContent) {
|
||||
X "`t`t`t<empty>true</empty>"
|
||||
} else {
|
||||
foreach ($cellInfo in $rowCells) {
|
||||
X "`t`t`t<c>"
|
||||
X "`t`t`t`t<i>$($cellInfo.Col)</i>"
|
||||
X "`t`t`t`t<c>"
|
||||
X "`t`t`t`t`t<f>$($cellInfo.FormatIdx)</f>"
|
||||
|
||||
if ($cellInfo.Param) {
|
||||
X "`t`t`t`t`t<parameter>$($cellInfo.Param)</parameter>"
|
||||
if ($cellInfo.Detail) {
|
||||
X "`t`t`t`t`t<detailParameter>$($cellInfo.Detail)</detailParameter>"
|
||||
}
|
||||
}
|
||||
|
||||
if ($cellInfo.Text) {
|
||||
X "`t`t`t`t`t<tl>"
|
||||
X "`t`t`t`t`t`t<v8:item>"
|
||||
X "`t`t`t`t`t`t`t<v8:lang>ru</v8:lang>"
|
||||
X "`t`t`t`t`t`t`t<v8:content>$(Esc-Xml $cellInfo.Text)</v8:content>"
|
||||
X "`t`t`t`t`t`t</v8:item>"
|
||||
X "`t`t`t`t`t</tl>"
|
||||
}
|
||||
|
||||
if ($cellInfo.Template) {
|
||||
X "`t`t`t`t`t<tl>"
|
||||
X "`t`t`t`t`t`t<v8:item>"
|
||||
X "`t`t`t`t`t`t`t<v8:lang>ru</v8:lang>"
|
||||
X "`t`t`t`t`t`t`t<v8:content>$(Esc-Xml $cellInfo.Template)</v8:content>"
|
||||
X "`t`t`t`t`t`t</v8:item>"
|
||||
X "`t`t`t`t`t</tl>"
|
||||
}
|
||||
|
||||
X "`t`t`t`t</c>"
|
||||
X "`t`t`t</c>"
|
||||
}
|
||||
}
|
||||
|
||||
X "`t`t</row>"
|
||||
X "`t</rowsItem>"
|
||||
|
||||
$localRow++
|
||||
$globalRow++
|
||||
}
|
||||
|
||||
$areaEndRow = $globalRow - 1
|
||||
$namedItems += @{
|
||||
Name = $areaName
|
||||
BeginRow = $areaStartRow
|
||||
EndRow = $areaEndRow
|
||||
}
|
||||
}
|
||||
|
||||
$totalRowCount = $globalRow
|
||||
|
||||
# 7e. Scalar metadata
|
||||
X "`t<templateMode>true</templateMode>"
|
||||
X "`t<defaultFormatIndex>$defaultFormatIndex</defaultFormatIndex>"
|
||||
X "`t<height>$totalRowCount</height>"
|
||||
X "`t<vgRows>$totalRowCount</vgRows>"
|
||||
|
||||
# 7f. Merges
|
||||
foreach ($m in $merges) {
|
||||
X "`t<merge>"
|
||||
X "`t`t<r>$($m.R)</r>"
|
||||
X "`t`t<c>$($m.C)</c>"
|
||||
if ($m.H) { X "`t`t<h>$($m.H)</h>" }
|
||||
X "`t`t<w>$($m.W)</w>"
|
||||
X "`t</merge>"
|
||||
}
|
||||
|
||||
# 7g. Named items
|
||||
foreach ($ni in $namedItems) {
|
||||
X "`t<namedItem xsi:type=`"NamedItemCells`">"
|
||||
X "`t`t<name>$($ni.Name)</name>"
|
||||
X "`t`t<area>"
|
||||
X "`t`t`t<type>Rows</type>"
|
||||
X "`t`t`t<beginRow>$($ni.BeginRow)</beginRow>"
|
||||
X "`t`t`t<endRow>$($ni.EndRow)</endRow>"
|
||||
X "`t`t`t<beginColumn>-1</beginColumn>"
|
||||
X "`t`t`t<endColumn>-1</endColumn>"
|
||||
X "`t`t</area>"
|
||||
X "`t</namedItem>"
|
||||
}
|
||||
|
||||
# 7h. Line palette
|
||||
if ($hasThinBorders) {
|
||||
X "`t<line width=`"1`" gap=`"false`">"
|
||||
X "`t`t<v8ui:style xsi:type=`"v8ui:SpreadsheetDocumentCellLineType`">Solid</v8ui:style>"
|
||||
X "`t</line>"
|
||||
}
|
||||
if ($hasThickBorders) {
|
||||
X "`t<line width=`"2`" gap=`"false`">"
|
||||
X "`t`t<v8ui:style xsi:type=`"v8ui:SpreadsheetDocumentCellLineType`">Solid</v8ui:style>"
|
||||
X "`t</line>"
|
||||
}
|
||||
|
||||
# 7i. Font palette
|
||||
foreach ($fe in $fontEntries) {
|
||||
X "`t<font faceName=`"$($fe.Face)`" height=`"$($fe.Size)`" bold=`"$($fe.Bold)`" italic=`"$($fe.Italic)`" underline=`"$($fe.Underline)`" strikeout=`"$($fe.Strikeout)`" kind=`"Absolute`" scale=`"100`"/>"
|
||||
}
|
||||
|
||||
# 7j. Format palette
|
||||
foreach ($key in $formatRegistry.Keys) {
|
||||
$fmt = $formatRegistry[$key]
|
||||
X "`t<format>"
|
||||
|
||||
if ($fmt.FontIdx -ne $null -and $fmt.FontIdx -ge 0) {
|
||||
X "`t`t<font>$($fmt.FontIdx)</font>"
|
||||
}
|
||||
if ($fmt.LB -ne $null -and $fmt.LB -ge 0) {
|
||||
X "`t`t<leftBorder>$($fmt.LB)</leftBorder>"
|
||||
}
|
||||
if ($fmt.TB -ne $null -and $fmt.TB -ge 0) {
|
||||
X "`t`t<topBorder>$($fmt.TB)</topBorder>"
|
||||
}
|
||||
if ($fmt.RB -ne $null -and $fmt.RB -ge 0) {
|
||||
X "`t`t<rightBorder>$($fmt.RB)</rightBorder>"
|
||||
}
|
||||
if ($fmt.BB -ne $null -and $fmt.BB -ge 0) {
|
||||
X "`t`t<bottomBorder>$($fmt.BB)</bottomBorder>"
|
||||
}
|
||||
if ($fmt.Width) {
|
||||
X "`t`t<width>$($fmt.Width)</width>"
|
||||
}
|
||||
if ($fmt.Height) {
|
||||
X "`t`t<height>$($fmt.Height)</height>"
|
||||
}
|
||||
if ($fmt.HA) {
|
||||
X "`t`t<horizontalAlignment>$($fmt.HA)</horizontalAlignment>"
|
||||
}
|
||||
if ($fmt.VA) {
|
||||
X "`t`t<verticalAlignment>$($fmt.VA)</verticalAlignment>"
|
||||
}
|
||||
if ($fmt.Wrap -eq $true) {
|
||||
X "`t`t<textPlacement>Wrap</textPlacement>"
|
||||
}
|
||||
if ($fmt.FillType) {
|
||||
X "`t`t<fillType>$($fmt.FillType)</fillType>"
|
||||
}
|
||||
if ($fmt.NumberFormat) {
|
||||
X "`t`t<format>"
|
||||
X "`t`t`t<v8:item>"
|
||||
X "`t`t`t`t<v8:lang>ru</v8:lang>"
|
||||
X "`t`t`t`t<v8:content>$(Esc-Xml $fmt.NumberFormat)</v8:content>"
|
||||
X "`t`t`t</v8:item>"
|
||||
X "`t`t</format>"
|
||||
}
|
||||
|
||||
X "`t</format>"
|
||||
}
|
||||
|
||||
# 7k. Close document
|
||||
X '</document>'
|
||||
|
||||
# --- 8. Write output ---
|
||||
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
$resolvedPath = if ([System.IO.Path]::IsPathRooted($OutputPath)) { $OutputPath } else { Join-Path (Get-Location) $OutputPath }
|
||||
Assert-EditAllowed $resolvedPath 'editable'
|
||||
[System.IO.File]::WriteAllText($resolvedPath, $xml.ToString(), $enc)
|
||||
|
||||
# --- 9. Summary ---
|
||||
|
||||
Write-Host "[OK] Compiled: $OutputPath"
|
||||
if ($def.page) {
|
||||
Write-Host " Page: $pageName -> target $targetWidth, defaultWidth=$defaultWidth"
|
||||
}
|
||||
Write-Host " Areas: $($namedItems.Count), Rows: $totalRowCount, Columns: $totalColumns"
|
||||
Write-Host " Fonts: $($fontEntries.Count), Lines: $lineCount, Formats: $($formatRegistry.Count)"
|
||||
Write-Host " Merges: $($merges.Count)"
|
||||
@@ -1,818 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# mxl-compile v1.5 — Compile 1C spreadsheet from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
from lxml import etree
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
|
||||
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
|
||||
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
|
||||
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
|
||||
# ============================================================
|
||||
|
||||
def _sg_root_uuid(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return None
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str) and child.get("uuid"):
|
||||
return child.get("uuid")
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _sg_is_external_root(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return False
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str):
|
||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
|
||||
def _sg_get_edit_mode(cfg_dir):
|
||||
try:
|
||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
||||
if not pj:
|
||||
return "deny"
|
||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
||||
for db in proj.get("databases", []):
|
||||
src = db.get("configSrc")
|
||||
if src:
|
||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
||||
if db.get("editingAllowedCheck"):
|
||||
return db["editingAllowedCheck"]
|
||||
if proj.get("editingAllowedCheck"):
|
||||
return proj["editingAllowedCheck"]
|
||||
return "deny"
|
||||
except Exception:
|
||||
return "deny"
|
||||
|
||||
|
||||
def assert_edit_allowed(target_path, require):
|
||||
try:
|
||||
rp = os.path.abspath(target_path)
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if _sg_is_external_root(rp):
|
||||
return
|
||||
elem_uuid = _sg_root_uuid(rp)
|
||||
cfg_dir = None
|
||||
bin_path = None
|
||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
||||
for _ in range(12):
|
||||
if not d:
|
||||
break
|
||||
if _sg_is_external_root(d + ".xml"):
|
||||
return
|
||||
if not elem_uuid:
|
||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
||||
if not cfg_dir:
|
||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
||||
cfg_dir = d
|
||||
bin_path = cand
|
||||
if elem_uuid and cfg_dir:
|
||||
break
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
if not elem_uuid and cfg_dir:
|
||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
||||
if not bin_path or not os.path.exists(bin_path):
|
||||
return
|
||||
data = open(bin_path, "rb").read()
|
||||
if len(data) <= 32:
|
||||
return
|
||||
if data[:3] == b"\xef\xbb\xbf":
|
||||
data = data[3:]
|
||||
text = data.decode("utf-8", "replace")
|
||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
||||
if not h:
|
||||
return
|
||||
g = int(h.group(1))
|
||||
k = int(h.group(2))
|
||||
if k == 0:
|
||||
return
|
||||
best = None
|
||||
if elem_uuid:
|
||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
||||
f1 = int(m.group(1))
|
||||
if best is None or f1 < best:
|
||||
best = f1
|
||||
blocked = False
|
||||
code = ""
|
||||
reason = ""
|
||||
if g == 1:
|
||||
blocked = True
|
||||
code = "capability-off"
|
||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
||||
elif require == "removed":
|
||||
if best is not None and best != 2:
|
||||
blocked = True
|
||||
code = "not-removed"
|
||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
||||
else:
|
||||
if best is not None and best == 0:
|
||||
blocked = True
|
||||
code = "locked"
|
||||
reason = "объект на замке — редактирование сломает обновления"
|
||||
if not blocked:
|
||||
return
|
||||
mode = _sg_get_edit_mode(cfg_dir)
|
||||
if mode == "off":
|
||||
return
|
||||
if mode == "warn":
|
||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
||||
return
|
||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if code == "capability-off":
|
||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
||||
fix = (
|
||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
)
|
||||
elif code == "not-removed":
|
||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
fix = (
|
||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
||||
)
|
||||
else:
|
||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
fix = (
|
||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
||||
)
|
||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
||||
sys.exit(1)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def esc_xml(s):
|
||||
"""Экранирование ТЕКСТА элемента: только & < > . Кавычки платформа в тексте не экранирует
|
||||
(92142 сырых кавычки на корпус, ни одной "); " она принимает, но нормализует обратно."""
|
||||
return s.replace('&', '&').replace('<', '<').replace('>', '>')
|
||||
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Compile 1C spreadsheet from JSON', allow_abbrev=False)
|
||||
parser.add_argument('-JsonPath', type=str, required=True)
|
||||
parser.add_argument('-OutputPath', type=str, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
# --- 1. Load and validate JSON ---
|
||||
json_path = args.JsonPath
|
||||
if not os.path.exists(json_path):
|
||||
print(f"File not found: {json_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
with open(json_path, 'r', encoding='utf-8-sig') as f:
|
||||
defn = json.load(f)
|
||||
|
||||
if not defn.get('columns'):
|
||||
print("Required field 'columns' is missing", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if not defn.get('areas'):
|
||||
print("Required field 'areas' is missing", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
total_columns = int(defn['columns'])
|
||||
default_width = int(defn['defaultWidth']) if defn.get('defaultWidth') else 10
|
||||
|
||||
# --- 2. Build font palette ---
|
||||
font_map = {} # name -> 0-based index
|
||||
font_entries = [] # list of dicts
|
||||
|
||||
def add_font(name, font_def):
|
||||
face = font_def.get('face', 'Arial') if font_def else 'Arial'
|
||||
size = int(font_def.get('size', 10)) if font_def else 10
|
||||
bold = 'true' if font_def and font_def.get('bold') is True else 'false'
|
||||
italic = 'true' if font_def and font_def.get('italic') is True else 'false'
|
||||
underline = 'true' if font_def and font_def.get('underline') is True else 'false'
|
||||
strikeout = 'true' if font_def and font_def.get('strikeout') is True else 'false'
|
||||
|
||||
idx = len(font_entries)
|
||||
font_map[name] = idx
|
||||
font_entries.append({
|
||||
'Face': face,
|
||||
'Size': size,
|
||||
'Bold': bold,
|
||||
'Italic': italic,
|
||||
'Underline': underline,
|
||||
'Strikeout': strikeout,
|
||||
})
|
||||
|
||||
# Add user-defined fonts
|
||||
has_default = False
|
||||
if defn.get('fonts'):
|
||||
for fname, fdef in defn['fonts'].items():
|
||||
if fname == 'default':
|
||||
has_default = True
|
||||
add_font(fname, fdef)
|
||||
|
||||
# Ensure default font exists
|
||||
if not has_default:
|
||||
add_font('default', {'face': 'Arial', 'size': 10})
|
||||
|
||||
# --- 3. Determine line palette ---
|
||||
has_thin_borders = False
|
||||
has_thick_borders = False
|
||||
|
||||
if defn.get('styles'):
|
||||
for sname, sval in defn['styles'].items():
|
||||
if sval.get('border') and sval['border'] != 'none':
|
||||
if sval.get('borderWidth') == 'thick':
|
||||
has_thick_borders = True
|
||||
else:
|
||||
has_thin_borders = True
|
||||
|
||||
thin_line_index = -1
|
||||
thick_line_index = -1
|
||||
line_count = 0
|
||||
if has_thin_borders:
|
||||
thin_line_index = line_count
|
||||
line_count += 1
|
||||
if has_thick_borders:
|
||||
thick_line_index = line_count
|
||||
line_count += 1
|
||||
|
||||
# --- 4. Parse column width specs ---
|
||||
def parse_column_spec(spec):
|
||||
cols = []
|
||||
for part in spec.split(','):
|
||||
part = part.strip()
|
||||
m = re.match(r'^(\d+)-(\d+)$', part)
|
||||
if m:
|
||||
from_col = int(m.group(1))
|
||||
to_col = int(m.group(2))
|
||||
for i in range(from_col, to_col + 1):
|
||||
cols.append(i)
|
||||
else:
|
||||
cols.append(int(part))
|
||||
return cols
|
||||
|
||||
# --- 4a. Auto-calculate defaultWidth from page format ---
|
||||
page_targets = {
|
||||
'A4-landscape': 780,
|
||||
'A4-portrait': 540,
|
||||
}
|
||||
|
||||
page_name = None
|
||||
target_width = None
|
||||
if defn.get('page'):
|
||||
page_name = str(defn['page'])
|
||||
|
||||
if re.match(r'^\d+$', page_name):
|
||||
target_width = int(page_name)
|
||||
elif page_name in page_targets:
|
||||
target_width = page_targets[page_name]
|
||||
else:
|
||||
print(f"WARNING: Unknown page format '{page_name}'. Known: {', '.join(page_targets.keys())}, or a number.", file=sys.stderr)
|
||||
|
||||
if target_width:
|
||||
total_units = 0.0
|
||||
absolute_sum = 0
|
||||
specified_cols = {}
|
||||
|
||||
if defn.get('columnWidths'):
|
||||
for prop_name, prop_value in defn['columnWidths'].items():
|
||||
val = str(prop_value)
|
||||
cols = parse_column_spec(prop_name)
|
||||
for c in cols:
|
||||
specified_cols[int(c)] = True
|
||||
m = re.match(r'^([0-9.]+)x$', val)
|
||||
if m:
|
||||
total_units += float(m.group(1))
|
||||
else:
|
||||
absolute_sum += int(val)
|
||||
|
||||
for c in range(1, total_columns + 1):
|
||||
if c not in specified_cols:
|
||||
total_units += 1.0
|
||||
|
||||
if total_units > 0:
|
||||
default_width = round((target_width - absolute_sum) / total_units)
|
||||
|
||||
# Build column width map: 1-based col -> width
|
||||
col_width_map = {}
|
||||
if defn.get('columnWidths'):
|
||||
for prop_name, prop_value in defn['columnWidths'].items():
|
||||
val = str(prop_value)
|
||||
m = re.match(r'^([0-9.]+)x$', val)
|
||||
if m:
|
||||
width = round(float(m.group(1)) * default_width)
|
||||
else:
|
||||
width = int(val)
|
||||
columns = parse_column_spec(prop_name)
|
||||
for c in columns:
|
||||
col_width_map[c] = width
|
||||
|
||||
# --- 5. Style resolver ---
|
||||
def resolve_style(style_name, fill_type):
|
||||
font_idx = font_map.get('default', 0)
|
||||
lb = -1; tb = -1; rb = -1; bb = -1
|
||||
ha = ''; va = ''; nf = ''
|
||||
wrap = False
|
||||
|
||||
if style_name and defn.get('styles'):
|
||||
style = defn['styles'].get(style_name)
|
||||
if style:
|
||||
# Font
|
||||
if style.get('font') and style['font'] in font_map:
|
||||
font_idx = font_map[style['font']]
|
||||
|
||||
# Borders
|
||||
if style.get('border') and style['border'] != 'none':
|
||||
line_idx = thick_line_index if style.get('borderWidth') == 'thick' else thin_line_index
|
||||
for side in style['border'].split(','):
|
||||
side = side.strip()
|
||||
if side == 'all':
|
||||
lb = line_idx; tb = line_idx; rb = line_idx; bb = line_idx
|
||||
elif side == 'left':
|
||||
lb = line_idx
|
||||
elif side == 'top':
|
||||
tb = line_idx
|
||||
elif side == 'right':
|
||||
rb = line_idx
|
||||
elif side == 'bottom':
|
||||
bb = line_idx
|
||||
|
||||
# Alignment
|
||||
if style.get('align'):
|
||||
align_map = {'left': 'Left', 'center': 'Center', 'right': 'Right'}
|
||||
ha = align_map.get(style['align'], '')
|
||||
if style.get('valign'):
|
||||
valign_map = {'top': 'Top', 'center': 'Center'}
|
||||
va = valign_map.get(style['valign'], '')
|
||||
|
||||
# Wrap
|
||||
if style.get('wrap') is True:
|
||||
wrap = True
|
||||
|
||||
# Number format
|
||||
if style.get('format'):
|
||||
nf = style['format']
|
||||
|
||||
return {
|
||||
'FontIdx': font_idx,
|
||||
'LB': lb, 'TB': tb, 'RB': rb, 'BB': bb,
|
||||
'HA': ha, 'VA': va,
|
||||
'Wrap': wrap,
|
||||
'FillType': fill_type,
|
||||
'NumberFormat': nf,
|
||||
}
|
||||
|
||||
# --- 6. Format palette builder ---
|
||||
format_registry = {} # key -> props
|
||||
format_order = [] # ordered keys for index assignment
|
||||
|
||||
def get_format_key(font_idx=-1, lb=-1, tb=-1, rb=-1, bb=-1, ha='', va='',
|
||||
wrap=False, fill_type='', number_format='', width=-1, height=-1):
|
||||
return f'f={font_idx}|lb={lb}|tb={tb}|rb={rb}|bb={bb}|ha={ha}|va={va}|wr={wrap}|ft={fill_type}|nf={number_format}|w={width}|h={height}'
|
||||
|
||||
def register_format(key, props):
|
||||
if key not in format_registry:
|
||||
format_registry[key] = props
|
||||
format_order.append(key)
|
||||
# Return 1-based index
|
||||
return format_order.index(key) + 1
|
||||
|
||||
# 6a. Default width format
|
||||
default_format_key = get_format_key(width=default_width)
|
||||
default_format_index = register_format(default_format_key, {'Width': default_width})
|
||||
|
||||
# 6b. Column width formats
|
||||
col_format_map = {} # 1-based col -> format index
|
||||
for col in sorted(col_width_map):
|
||||
w = col_width_map[col]
|
||||
key = get_format_key(width=w)
|
||||
idx = register_format(key, {'Width': w})
|
||||
col_format_map[int(col)] = idx
|
||||
|
||||
# 6c. Helper: determine fillType from cell content
|
||||
def get_fill_type(cell):
|
||||
if cell.get('param'):
|
||||
return 'Parameter'
|
||||
if cell.get('template'):
|
||||
return 'Template'
|
||||
if cell.get('text'):
|
||||
return 'Text'
|
||||
return ''
|
||||
|
||||
# Helper: register a cell format and return its index
|
||||
def register_cell_format(style_name, fill_type):
|
||||
resolved = resolve_style(style_name, fill_type)
|
||||
key = get_format_key(
|
||||
font_idx=resolved['FontIdx'],
|
||||
lb=resolved['LB'], tb=resolved['TB'], rb=resolved['RB'], bb=resolved['BB'],
|
||||
ha=resolved['HA'], va=resolved['VA'],
|
||||
wrap=resolved['Wrap'], fill_type=resolved['FillType'],
|
||||
number_format=resolved['NumberFormat'])
|
||||
props = {
|
||||
'FontIdx': resolved['FontIdx'],
|
||||
'LB': resolved['LB'], 'TB': resolved['TB'],
|
||||
'RB': resolved['RB'], 'BB': resolved['BB'],
|
||||
'HA': resolved['HA'], 'VA': resolved['VA'],
|
||||
'Wrap': resolved['Wrap'],
|
||||
'FillType': resolved['FillType'],
|
||||
'NumberFormat': resolved['NumberFormat'],
|
||||
}
|
||||
return register_format(key, props)
|
||||
|
||||
# Pre-register all formats from areas
|
||||
for area in defn['areas']:
|
||||
for row in area.get('rows', []):
|
||||
# Skip list-of-values shorthand rows (treated as empty rows like PS1)
|
||||
if isinstance(row, list):
|
||||
continue
|
||||
# Skip empty row placeholder
|
||||
if row.get('empty'):
|
||||
continue
|
||||
|
||||
# Row height format
|
||||
if row.get('height'):
|
||||
h_key = get_format_key(height=int(row['height']))
|
||||
register_format(h_key, {'Height': int(row['height'])})
|
||||
|
||||
# rowStyle gap-fill format
|
||||
if row.get('rowStyle'):
|
||||
register_cell_format(row['rowStyle'], '')
|
||||
|
||||
# Explicit cell formats
|
||||
if row.get('cells'):
|
||||
for cell in row['cells']:
|
||||
cell_style = cell.get('style') or row.get('rowStyle') or 'default'
|
||||
ft = get_fill_type(cell)
|
||||
register_cell_format(cell_style, ft)
|
||||
|
||||
# --- 7. Generate XML ---
|
||||
lines = []
|
||||
|
||||
# 7a. Header
|
||||
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
|
||||
lines.append('<document xmlns="http://v8.1c.ru/8.2/data/spreadsheet" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">')
|
||||
|
||||
# 7b. Language settings
|
||||
lines.append('\t<languageSettings>')
|
||||
lines.append('\t\t<currentLanguage>ru</currentLanguage>')
|
||||
lines.append('\t\t<defaultLanguage>ru</defaultLanguage>')
|
||||
lines.append('\t\t<languageInfo>')
|
||||
lines.append('\t\t\t<id>ru</id>')
|
||||
lines.append('\t\t\t<code>\u0420\u0443\u0441\u0441\u043a\u0438\u0439</code>')
|
||||
lines.append('\t\t\t<description>\u0420\u0443\u0441\u0441\u043a\u0438\u0439</description>')
|
||||
lines.append('\t\t</languageInfo>')
|
||||
lines.append('\t</languageSettings>')
|
||||
|
||||
# 7c. Columns
|
||||
lines.append('\t<columns>')
|
||||
lines.append(f'\t\t<size>{total_columns}</size>')
|
||||
|
||||
# Emit columnsItem for columns with non-default widths
|
||||
for col in sorted(col_format_map.keys()):
|
||||
fmt_idx = col_format_map[col]
|
||||
col_idx = col - 1 # Convert to 0-based
|
||||
lines.append('\t\t<columnsItem>')
|
||||
lines.append(f'\t\t\t<index>{col_idx}</index>')
|
||||
lines.append('\t\t\t<column>')
|
||||
lines.append(f'\t\t\t\t<formatIndex>{fmt_idx}</formatIndex>')
|
||||
lines.append('\t\t\t</column>')
|
||||
lines.append('\t\t</columnsItem>')
|
||||
|
||||
lines.append('\t</columns>')
|
||||
|
||||
# 7d. Rows -- main generation loop
|
||||
global_row = 0
|
||||
merges = []
|
||||
named_items = []
|
||||
active_rowspans = [] # list of {ColStart, ColEnd, StartLocalRow, EndLocalRow}
|
||||
|
||||
for area in defn['areas']:
|
||||
area_start_row = global_row
|
||||
area_name = area.get('name', '')
|
||||
active_rowspans = []
|
||||
local_row = 0
|
||||
|
||||
for row in area.get('rows', []):
|
||||
# List-of-values shorthand: treat as row with no properties (like PS1)
|
||||
if isinstance(row, list):
|
||||
row = {}
|
||||
# Empty row placeholder: emit N empty rows
|
||||
if row.get('empty'):
|
||||
count = int(row['empty'])
|
||||
for ei in range(count):
|
||||
lines.append('\t<rowsItem>')
|
||||
lines.append(f'\t\t<index>{global_row}</index>')
|
||||
lines.append('\t\t<row>')
|
||||
lines.append('\t\t\t<empty>true</empty>')
|
||||
lines.append('\t\t</row>')
|
||||
lines.append('\t</rowsItem>')
|
||||
global_row += 1
|
||||
local_row += 1
|
||||
continue
|
||||
|
||||
# Build set of columns occupied by rowspans from previous rows
|
||||
rowspan_occupied = {}
|
||||
for rs in active_rowspans:
|
||||
if local_row > rs['StartLocalRow'] and local_row <= rs['EndLocalRow']:
|
||||
for c in range(rs['ColStart'], rs['ColEnd'] + 1):
|
||||
rowspan_occupied[c] = True
|
||||
|
||||
row_has_content = False
|
||||
row_cells = []
|
||||
|
||||
# Determine row height format
|
||||
row_format_idx = 0
|
||||
if row.get('height'):
|
||||
h_key = get_format_key(height=int(row['height']))
|
||||
if h_key in format_registry:
|
||||
row_format_idx = format_order.index(h_key) + 1
|
||||
|
||||
if row.get('cells') and len(row['cells']) > 0:
|
||||
row_has_content = True
|
||||
|
||||
# Build set of occupied columns (1-based)
|
||||
occupied_cols = dict(rowspan_occupied)
|
||||
for cell in row['cells']:
|
||||
col_start = int(cell['col'])
|
||||
col_span = int(cell.get('span', 1))
|
||||
for c in range(col_start, col_start + col_span):
|
||||
occupied_cols[c] = True
|
||||
|
||||
# Generate explicit cells
|
||||
for cell in row['cells']:
|
||||
col_start = int(cell['col'])
|
||||
col_span = int(cell.get('span', 1))
|
||||
rowspan = int(cell.get('rowspan', 1))
|
||||
cell_style = cell.get('style') or row.get('rowStyle') or 'default'
|
||||
ft = get_fill_type(cell)
|
||||
fmt_idx = register_cell_format(cell_style, ft)
|
||||
|
||||
cell_info = {
|
||||
'Col': col_start - 1, # 0-based
|
||||
'FormatIdx': fmt_idx,
|
||||
'Param': cell.get('param'),
|
||||
'Detail': cell.get('detail'),
|
||||
'Text': cell.get('text'),
|
||||
'Template': cell.get('template'),
|
||||
}
|
||||
row_cells.append(cell_info)
|
||||
|
||||
# Track rowspan for subsequent rows
|
||||
if rowspan > 1:
|
||||
active_rowspans.append({
|
||||
'ColStart': col_start,
|
||||
'ColEnd': col_start + col_span - 1,
|
||||
'StartLocalRow': local_row,
|
||||
'EndLocalRow': local_row + rowspan - 1,
|
||||
})
|
||||
|
||||
# Collect merge
|
||||
if col_span > 1 or rowspan > 1:
|
||||
merge = {'R': global_row, 'C': col_start - 1, 'W': col_span - 1}
|
||||
if rowspan > 1:
|
||||
merge['H'] = rowspan - 1
|
||||
merges.append(merge)
|
||||
|
||||
# Generate gap-fill cells for rowStyle
|
||||
if row.get('rowStyle'):
|
||||
gap_fmt_idx = register_cell_format(row['rowStyle'], '')
|
||||
for c in range(1, total_columns + 1):
|
||||
if c not in occupied_cols:
|
||||
row_cells.append({
|
||||
'Col': c - 1,
|
||||
'FormatIdx': gap_fmt_idx,
|
||||
'Param': None,
|
||||
'Detail': None,
|
||||
'Text': None,
|
||||
'Template': None,
|
||||
})
|
||||
|
||||
# Sort cells by column
|
||||
row_cells.sort(key=lambda x: x['Col'])
|
||||
|
||||
elif row.get('rowStyle'):
|
||||
# Row with only rowStyle, no explicit cells
|
||||
row_has_content = True
|
||||
gap_fmt_idx = register_cell_format(row['rowStyle'], '')
|
||||
for c in range(1, total_columns + 1):
|
||||
if c in rowspan_occupied:
|
||||
continue
|
||||
row_cells.append({
|
||||
'Col': c - 1,
|
||||
'FormatIdx': gap_fmt_idx,
|
||||
'Param': None,
|
||||
'Detail': None,
|
||||
'Text': None,
|
||||
'Template': None,
|
||||
})
|
||||
|
||||
# Emit rowsItem
|
||||
lines.append('\t<rowsItem>')
|
||||
lines.append(f'\t\t<index>{global_row}</index>')
|
||||
lines.append('\t\t<row>')
|
||||
|
||||
if row_format_idx > 0:
|
||||
lines.append(f'\t\t\t<formatIndex>{row_format_idx}</formatIndex>')
|
||||
|
||||
if not row_has_content:
|
||||
lines.append('\t\t\t<empty>true</empty>')
|
||||
else:
|
||||
for cell_info in row_cells:
|
||||
lines.append('\t\t\t<c>')
|
||||
lines.append(f'\t\t\t\t<i>{cell_info["Col"]}</i>')
|
||||
lines.append('\t\t\t\t<c>')
|
||||
lines.append(f'\t\t\t\t\t<f>{cell_info["FormatIdx"]}</f>')
|
||||
|
||||
if cell_info['Param']:
|
||||
lines.append(f'\t\t\t\t\t<parameter>{cell_info["Param"]}</parameter>')
|
||||
if cell_info['Detail']:
|
||||
lines.append(f'\t\t\t\t\t<detailParameter>{cell_info["Detail"]}</detailParameter>')
|
||||
|
||||
if cell_info['Text']:
|
||||
lines.append('\t\t\t\t\t<tl>')
|
||||
lines.append('\t\t\t\t\t\t<v8:item>')
|
||||
lines.append('\t\t\t\t\t\t\t<v8:lang>ru</v8:lang>')
|
||||
lines.append(f'\t\t\t\t\t\t\t<v8:content>{esc_xml(cell_info["Text"])}</v8:content>')
|
||||
lines.append('\t\t\t\t\t\t</v8:item>')
|
||||
lines.append('\t\t\t\t\t</tl>')
|
||||
|
||||
if cell_info['Template']:
|
||||
lines.append('\t\t\t\t\t<tl>')
|
||||
lines.append('\t\t\t\t\t\t<v8:item>')
|
||||
lines.append('\t\t\t\t\t\t\t<v8:lang>ru</v8:lang>')
|
||||
lines.append(f'\t\t\t\t\t\t\t<v8:content>{esc_xml(cell_info["Template"])}</v8:content>')
|
||||
lines.append('\t\t\t\t\t\t</v8:item>')
|
||||
lines.append('\t\t\t\t\t</tl>')
|
||||
|
||||
lines.append('\t\t\t\t</c>')
|
||||
lines.append('\t\t\t</c>')
|
||||
|
||||
lines.append('\t\t</row>')
|
||||
lines.append('\t</rowsItem>')
|
||||
|
||||
local_row += 1
|
||||
global_row += 1
|
||||
|
||||
area_end_row = global_row - 1
|
||||
named_items.append({
|
||||
'Name': area_name,
|
||||
'BeginRow': area_start_row,
|
||||
'EndRow': area_end_row,
|
||||
})
|
||||
|
||||
total_row_count = global_row
|
||||
|
||||
# 7e. Scalar metadata
|
||||
lines.append(f'\t<templateMode>true</templateMode>')
|
||||
lines.append(f'\t<defaultFormatIndex>{default_format_index}</defaultFormatIndex>')
|
||||
lines.append(f'\t<height>{total_row_count}</height>')
|
||||
lines.append(f'\t<vgRows>{total_row_count}</vgRows>')
|
||||
|
||||
# 7f. Merges
|
||||
for m in merges:
|
||||
lines.append('\t<merge>')
|
||||
lines.append(f'\t\t<r>{m["R"]}</r>')
|
||||
lines.append(f'\t\t<c>{m["C"]}</c>')
|
||||
if m.get('H'):
|
||||
lines.append(f'\t\t<h>{m["H"]}</h>')
|
||||
lines.append(f'\t\t<w>{m["W"]}</w>')
|
||||
lines.append('\t</merge>')
|
||||
|
||||
# 7g. Named items
|
||||
for ni in named_items:
|
||||
lines.append('\t<namedItem xsi:type="NamedItemCells">')
|
||||
lines.append(f'\t\t<name>{ni["Name"]}</name>')
|
||||
lines.append('\t\t<area>')
|
||||
lines.append('\t\t\t<type>Rows</type>')
|
||||
lines.append(f'\t\t\t<beginRow>{ni["BeginRow"]}</beginRow>')
|
||||
lines.append(f'\t\t\t<endRow>{ni["EndRow"]}</endRow>')
|
||||
lines.append('\t\t\t<beginColumn>-1</beginColumn>')
|
||||
lines.append('\t\t\t<endColumn>-1</endColumn>')
|
||||
lines.append('\t\t</area>')
|
||||
lines.append('\t</namedItem>')
|
||||
|
||||
# 7h. Line palette
|
||||
if has_thin_borders:
|
||||
lines.append('\t<line width="1" gap="false">')
|
||||
lines.append('\t\t<v8ui:style xsi:type="v8ui:SpreadsheetDocumentCellLineType">Solid</v8ui:style>')
|
||||
lines.append('\t</line>')
|
||||
if has_thick_borders:
|
||||
lines.append('\t<line width="2" gap="false">')
|
||||
lines.append('\t\t<v8ui:style xsi:type="v8ui:SpreadsheetDocumentCellLineType">Solid</v8ui:style>')
|
||||
lines.append('\t</line>')
|
||||
|
||||
# 7i. Font palette
|
||||
for fe in font_entries:
|
||||
lines.append(f'\t<font faceName="{fe["Face"]}" height="{fe["Size"]}" bold="{fe["Bold"]}" italic="{fe["Italic"]}" underline="{fe["Underline"]}" strikeout="{fe["Strikeout"]}" kind="Absolute" scale="100"/>')
|
||||
|
||||
# 7j. Format palette
|
||||
for key in format_order:
|
||||
fmt = format_registry[key]
|
||||
lines.append('\t<format>')
|
||||
|
||||
if fmt.get('FontIdx') is not None and fmt.get('FontIdx', -1) >= 0:
|
||||
lines.append(f'\t\t<font>{fmt["FontIdx"]}</font>')
|
||||
if fmt.get('LB') is not None and fmt.get('LB', -1) >= 0:
|
||||
lines.append(f'\t\t<leftBorder>{fmt["LB"]}</leftBorder>')
|
||||
if fmt.get('TB') is not None and fmt.get('TB', -1) >= 0:
|
||||
lines.append(f'\t\t<topBorder>{fmt["TB"]}</topBorder>')
|
||||
if fmt.get('RB') is not None and fmt.get('RB', -1) >= 0:
|
||||
lines.append(f'\t\t<rightBorder>{fmt["RB"]}</rightBorder>')
|
||||
if fmt.get('BB') is not None and fmt.get('BB', -1) >= 0:
|
||||
lines.append(f'\t\t<bottomBorder>{fmt["BB"]}</bottomBorder>')
|
||||
if fmt.get('Width'):
|
||||
lines.append(f'\t\t<width>{fmt["Width"]}</width>')
|
||||
if fmt.get('Height'):
|
||||
lines.append(f'\t\t<height>{fmt["Height"]}</height>')
|
||||
if fmt.get('HA'):
|
||||
lines.append(f'\t\t<horizontalAlignment>{fmt["HA"]}</horizontalAlignment>')
|
||||
if fmt.get('VA'):
|
||||
lines.append(f'\t\t<verticalAlignment>{fmt["VA"]}</verticalAlignment>')
|
||||
if fmt.get('Wrap') is True:
|
||||
lines.append('\t\t<textPlacement>Wrap</textPlacement>')
|
||||
if fmt.get('FillType'):
|
||||
lines.append(f'\t\t<fillType>{fmt["FillType"]}</fillType>')
|
||||
if fmt.get('NumberFormat'):
|
||||
lines.append('\t\t<format>')
|
||||
lines.append('\t\t\t<v8:item>')
|
||||
lines.append('\t\t\t\t<v8:lang>ru</v8:lang>')
|
||||
lines.append(f'\t\t\t\t<v8:content>{esc_xml(fmt["NumberFormat"])}</v8:content>')
|
||||
lines.append('\t\t\t</v8:item>')
|
||||
lines.append('\t\t</format>')
|
||||
|
||||
lines.append('\t</format>')
|
||||
|
||||
# 7k. Close document
|
||||
lines.append('</document>')
|
||||
|
||||
# --- 8. Write output ---
|
||||
out_path = args.OutputPath
|
||||
if not os.path.isabs(out_path):
|
||||
out_path = os.path.join(os.getcwd(), out_path)
|
||||
|
||||
assert_edit_allowed(out_path, "editable")
|
||||
|
||||
out_dir = os.path.dirname(out_path)
|
||||
if out_dir and not os.path.exists(out_dir):
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
|
||||
content = '\n'.join(lines) + '\n'
|
||||
write_utf8_bom(out_path, content)
|
||||
|
||||
# --- 9. Summary ---
|
||||
print(f"[OK] Compiled: {args.OutputPath}")
|
||||
if defn.get('page'):
|
||||
print(f" Page: {page_name} -> target {target_width}, defaultWidth={default_width}")
|
||||
print(f" Areas: {len(named_items)}, Rows: {total_row_count}, Columns: {total_columns}")
|
||||
print(f" Fonts: {len(font_entries)}, Lines: {line_count}, Formats: {len(format_registry)}")
|
||||
print(f" Merges: {len(merges)}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,44 +0,0 @@
|
||||
---
|
||||
name: mxl-decompile
|
||||
description: Декомпиляция табличного документа (MXL) в JSON-определение. Используй когда нужно получить редактируемое описание существующего макета
|
||||
argument-hint: <TemplatePath> [OutputPath]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /mxl-decompile — Декомпилятор макета в DSL
|
||||
|
||||
Принимает Template.xml табличного документа 1С и генерирует компактное JSON-определение (DSL). Обратная операция к `/mxl-compile`.
|
||||
|
||||
## Использование
|
||||
|
||||
```
|
||||
/mxl-decompile <TemplatePath> [OutputPath]
|
||||
```
|
||||
|
||||
## Параметры
|
||||
|
||||
| Параметр | Обязательный | Описание |
|
||||
|--------------|:------------:|-----------------------------------------|
|
||||
| TemplatePath | да | Путь к Template.xml |
|
||||
| OutputPath | нет | Путь для JSON (если не указан — stdout) |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/mxl-decompile.ps1" -TemplatePath "<путь>/Template.xml" [-OutputPath "<путь>.json"]
|
||||
```
|
||||
|
||||
## Рабочий процесс
|
||||
|
||||
Декомпиляция существующего макета для анализа или доработки:
|
||||
|
||||
1. Вызвать `/mxl-decompile` для получения JSON из Template.xml
|
||||
2. Проанализировать или изменить JSON (добавить области, поменять стили)
|
||||
3. Вызвать `/mxl-compile` для генерации нового Template.xml
|
||||
4. Вызвать `/mxl-validate` для проверки
|
||||
|
||||
Формат JSON на выходе — тот же DSL, что принимает `/mxl-compile`; его полное описание живёт в навыке `/mxl-compile`.
|
||||
@@ -1,646 +0,0 @@
|
||||
# mxl-decompile v1.0 — Decompile 1C spreadsheet to JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Alias('Path')]
|
||||
[string]$TemplatePath,
|
||||
|
||||
[string]$OutputPath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- 1. Load and parse XML ---
|
||||
|
||||
if (-not (Test-Path $TemplatePath)) {
|
||||
Write-Error "File not found: $TemplatePath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||
$xmlDoc.PreserveWhitespace = $false
|
||||
$xmlDoc.Load((Resolve-Path $TemplatePath).Path)
|
||||
|
||||
$root = $xmlDoc.DocumentElement
|
||||
$ns = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
|
||||
$ns.AddNamespace("d", "http://v8.1c.ru/8.2/data/spreadsheet")
|
||||
$ns.AddNamespace("v8", "http://v8.1c.ru/8.1/data/core")
|
||||
$ns.AddNamespace("v8ui", "http://v8.1c.ru/8.1/data/ui")
|
||||
$ns.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")
|
||||
|
||||
# --- 2. Extract font palette ---
|
||||
|
||||
$rawFonts = @()
|
||||
foreach ($fNode in $root.SelectNodes("d:font", $ns)) {
|
||||
$rawFonts += @{
|
||||
Face = $fNode.GetAttribute("faceName")
|
||||
Size = [int]$fNode.GetAttribute("height")
|
||||
Bold = $fNode.GetAttribute("bold") -eq "true"
|
||||
Italic = $fNode.GetAttribute("italic") -eq "true"
|
||||
Underline = $fNode.GetAttribute("underline") -eq "true"
|
||||
Strikeout = $fNode.GetAttribute("strikeout") -eq "true"
|
||||
}
|
||||
}
|
||||
|
||||
# --- 3. Extract line palette ---
|
||||
|
||||
$rawLines = @()
|
||||
foreach ($lNode in $root.SelectNodes("d:line", $ns)) {
|
||||
$rawLines += @{ Width = [int]$lNode.GetAttribute("width") }
|
||||
}
|
||||
|
||||
# --- 4. Extract format palette ---
|
||||
|
||||
$rawFormats = @()
|
||||
foreach ($fmtNode in $root.SelectNodes("d:format", $ns)) {
|
||||
$fmt = @{
|
||||
FontIdx = -1
|
||||
LB = -1; TB = -1; RB = -1; BB = -1
|
||||
Width = 0; Height = 0
|
||||
HA = ""; VA = ""
|
||||
Wrap = $false; FillType = ""; DataFormat = ""
|
||||
}
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:font", $ns)
|
||||
if ($n) { $fmt.FontIdx = [int]$n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:leftBorder", $ns)
|
||||
if ($n) { $fmt.LB = [int]$n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:topBorder", $ns)
|
||||
if ($n) { $fmt.TB = [int]$n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:rightBorder", $ns)
|
||||
if ($n) { $fmt.RB = [int]$n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:bottomBorder", $ns)
|
||||
if ($n) { $fmt.BB = [int]$n.InnerText }
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:width", $ns)
|
||||
if ($n) { $fmt.Width = [int]$n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:height", $ns)
|
||||
if ($n) { $fmt.Height = [int]$n.InnerText }
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:horizontalAlignment", $ns)
|
||||
if ($n) { $fmt.HA = $n.InnerText }
|
||||
$n = $fmtNode.SelectSingleNode("d:verticalAlignment", $ns)
|
||||
if ($n) { $fmt.VA = $n.InnerText }
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:textPlacement", $ns)
|
||||
if ($n -and $n.InnerText -eq "Wrap") { $fmt.Wrap = $true }
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:fillType", $ns)
|
||||
if ($n) { $fmt.FillType = $n.InnerText }
|
||||
|
||||
$n = $fmtNode.SelectSingleNode("d:format/v8:item/v8:content", $ns)
|
||||
if ($n) { $fmt.DataFormat = $n.InnerText }
|
||||
|
||||
$rawFormats += $fmt
|
||||
}
|
||||
|
||||
function Get-Format {
|
||||
param([int]$idx)
|
||||
if ($idx -le 0 -or $idx -gt $rawFormats.Count) { return $null }
|
||||
return $rawFormats[$idx - 1]
|
||||
}
|
||||
|
||||
# --- 5. Extract columns and default width ---
|
||||
|
||||
$colNode = $root.SelectSingleNode("d:columns", $ns)
|
||||
$totalColumns = [int]$colNode.SelectSingleNode("d:size", $ns).InnerText
|
||||
|
||||
$colFormatIndices = @{}
|
||||
foreach ($ci in $colNode.SelectNodes("d:columnsItem", $ns)) {
|
||||
$colIdx = [int]$ci.SelectSingleNode("d:index", $ns).InnerText
|
||||
$fmtIdx = [int]$ci.SelectSingleNode("d:column/d:formatIndex", $ns).InnerText
|
||||
$colFormatIndices[$colIdx] = $fmtIdx
|
||||
}
|
||||
|
||||
$defaultFmtIdx = 0
|
||||
$n = $root.SelectSingleNode("d:defaultFormatIndex", $ns)
|
||||
if ($n) { $defaultFmtIdx = [int]$n.InnerText }
|
||||
|
||||
$defaultWidth = 10
|
||||
if ($defaultFmtIdx -gt 0) {
|
||||
$defFmt = Get-Format $defaultFmtIdx
|
||||
if ($defFmt -and $defFmt.Width -gt 0) { $defaultWidth = $defFmt.Width }
|
||||
}
|
||||
|
||||
# Build column width map (1-based col → width), only non-default
|
||||
$colWidthMap = [ordered]@{}
|
||||
foreach ($col0 in ($colFormatIndices.Keys | Sort-Object)) {
|
||||
$fmt = Get-Format $colFormatIndices[$col0]
|
||||
if ($fmt -and $fmt.Width -gt 0 -and $fmt.Width -ne $defaultWidth) {
|
||||
$col1 = [string]($col0 + 1)
|
||||
$colWidthMap.Add($col1, $fmt.Width)
|
||||
}
|
||||
}
|
||||
|
||||
# --- 6. Extract merges ---
|
||||
|
||||
$mergeMap = @{}
|
||||
foreach ($mNode in $root.SelectNodes("d:merge", $ns)) {
|
||||
$r = [int]$mNode.SelectSingleNode("d:r", $ns).InnerText
|
||||
$c = [int]$mNode.SelectSingleNode("d:c", $ns).InnerText
|
||||
$w = [int]$mNode.SelectSingleNode("d:w", $ns).InnerText
|
||||
$hNode = $mNode.SelectSingleNode("d:h", $ns)
|
||||
$h = if ($hNode) { [int]$hNode.InnerText } else { 0 }
|
||||
$mergeMap["$r,$c"] = @{ W = $w; H = $h }
|
||||
}
|
||||
|
||||
# --- 7. Extract named items ---
|
||||
|
||||
$namedAreas = @()
|
||||
foreach ($niNode in $root.SelectNodes("d:namedItem", $ns)) {
|
||||
$xsiType = $niNode.GetAttribute("type", "http://www.w3.org/2001/XMLSchema-instance")
|
||||
if ($xsiType -ne "NamedItemCells") { continue }
|
||||
|
||||
$areaNode = $niNode.SelectSingleNode("d:area", $ns)
|
||||
$areaType = $areaNode.SelectSingleNode("d:type", $ns).InnerText
|
||||
if ($areaType -ne "Rows") { continue }
|
||||
|
||||
$namedAreas += @{
|
||||
Name = $niNode.SelectSingleNode("d:name", $ns).InnerText
|
||||
BeginRow = [int]$areaNode.SelectSingleNode("d:beginRow", $ns).InnerText
|
||||
EndRow = [int]$areaNode.SelectSingleNode("d:endRow", $ns).InnerText
|
||||
}
|
||||
}
|
||||
|
||||
# --- 8. Extract rows ---
|
||||
|
||||
$rowData = @{}
|
||||
foreach ($riNode in $root.SelectNodes("d:rowsItem", $ns)) {
|
||||
$rowIdx = [int]$riNode.SelectSingleNode("d:index", $ns).InnerText
|
||||
$rowNode = $riNode.SelectSingleNode("d:row", $ns)
|
||||
|
||||
$indexTo = $rowIdx
|
||||
$itNode = $riNode.SelectSingleNode("d:indexTo", $ns)
|
||||
if ($itNode) { $indexTo = [int]$itNode.InnerText }
|
||||
|
||||
$rowFmtIdx = 0
|
||||
$fmtNode = $rowNode.SelectSingleNode("d:formatIndex", $ns)
|
||||
if ($fmtNode) { $rowFmtIdx = [int]$fmtNode.InnerText }
|
||||
|
||||
$isEmpty = $false
|
||||
$emptyNode = $rowNode.SelectSingleNode("d:empty", $ns)
|
||||
if ($emptyNode -and $emptyNode.InnerText -eq "true") { $isEmpty = $true }
|
||||
|
||||
$cells = @()
|
||||
if (-not $isEmpty) {
|
||||
$col = -1
|
||||
foreach ($cGroup in $rowNode.SelectNodes("d:c", $ns)) {
|
||||
$iNode = $cGroup.SelectSingleNode("d:i", $ns)
|
||||
if ($iNode) { $col = [int]$iNode.InnerText }
|
||||
else { $col++ }
|
||||
|
||||
$cContent = $cGroup.SelectSingleNode("d:c", $ns)
|
||||
if (-not $cContent) { continue }
|
||||
|
||||
$cellFmtIdx = 0
|
||||
$fNode = $cContent.SelectSingleNode("d:f", $ns)
|
||||
if ($fNode) { $cellFmtIdx = [int]$fNode.InnerText }
|
||||
|
||||
$param = $null
|
||||
$pNode = $cContent.SelectSingleNode("d:parameter", $ns)
|
||||
if ($pNode) { $param = $pNode.InnerText }
|
||||
|
||||
$detail = $null
|
||||
$dNode = $cContent.SelectSingleNode("d:detailParameter", $ns)
|
||||
if ($dNode) { $detail = $dNode.InnerText }
|
||||
|
||||
$text = $null
|
||||
$tNode = $cContent.SelectSingleNode("d:tl/v8:item/v8:content", $ns)
|
||||
if ($tNode) { $text = $tNode.InnerText }
|
||||
|
||||
$cells += @{
|
||||
Col = $col
|
||||
FormatIdx = $cellFmtIdx
|
||||
Param = $param
|
||||
Detail = $detail
|
||||
Text = $text
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ($r = $rowIdx; $r -le $indexTo; $r++) {
|
||||
$rowData[$r] = @{
|
||||
FormatIdx = $rowFmtIdx
|
||||
Cells = $cells
|
||||
Empty = $isEmpty
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- 9. Build style key (ignoring fillType) ---
|
||||
|
||||
function Get-BorderDesc {
|
||||
param($fmt)
|
||||
if (-not $fmt) { return @{ Border = "none"; Thick = $false } }
|
||||
|
||||
$lb = $fmt.LB -ge 0; $tb = $fmt.TB -ge 0
|
||||
$rb = $fmt.RB -ge 0; $bb = $fmt.BB -ge 0
|
||||
|
||||
if (-not $lb -and -not $tb -and -not $rb -and -not $bb) {
|
||||
return @{ Border = "none"; Thick = $false }
|
||||
}
|
||||
|
||||
$thick = $false
|
||||
foreach ($bIdx in @($fmt.LB, $fmt.TB, $fmt.RB, $fmt.BB)) {
|
||||
if ($bIdx -ge 0 -and $bIdx -lt $rawLines.Count -and $rawLines[$bIdx].Width -ge 2) {
|
||||
$thick = $true; break
|
||||
}
|
||||
}
|
||||
|
||||
if ($lb -and $tb -and $rb -and $bb) {
|
||||
return @{ Border = "all"; Thick = $thick }
|
||||
}
|
||||
|
||||
$sides = @()
|
||||
if ($tb) { $sides += "top" }
|
||||
if ($bb) { $sides += "bottom" }
|
||||
if ($lb) { $sides += "left" }
|
||||
if ($rb) { $sides += "right" }
|
||||
|
||||
return @{ Border = ($sides -join ","); Thick = $thick }
|
||||
}
|
||||
|
||||
function Get-StyleKey {
|
||||
param($fmt)
|
||||
if (-not $fmt) { return "empty" }
|
||||
$fi = if ($fmt.FontIdx -ge 0) { $fmt.FontIdx } else { 0 }
|
||||
$bd = Get-BorderDesc $fmt
|
||||
return "f=$fi|b=$($bd.Border)|bw=$($bd.Thick)|ha=$($fmt.HA)|va=$($fmt.VA)|wr=$($fmt.Wrap)|df=$($fmt.DataFormat)"
|
||||
}
|
||||
|
||||
# --- 10. Name fonts ---
|
||||
|
||||
$fontNames = @{}
|
||||
$fontDefs = [ordered]@{}
|
||||
|
||||
if ($rawFonts.Count -gt 0) {
|
||||
$fontNames[0] = "default"
|
||||
$fontDefs["default"] = $rawFonts[0]
|
||||
}
|
||||
|
||||
function Get-FontKey {
|
||||
param($f)
|
||||
return "$($f.Face)|$($f.Size)|$($f.Bold)|$($f.Italic)|$($f.Underline)|$($f.Strikeout)"
|
||||
}
|
||||
|
||||
$fontKeyMap = @{}
|
||||
$fontKeyMap[(Get-FontKey $rawFonts[0])] = "default"
|
||||
|
||||
for ($i = 1; $i -lt $rawFonts.Count; $i++) {
|
||||
$f = $rawFonts[$i]
|
||||
$df = $rawFonts[0]
|
||||
|
||||
# Dedup: if identical font already named, reuse
|
||||
$fKey = Get-FontKey $f
|
||||
if ($fontKeyMap.ContainsKey($fKey)) {
|
||||
$fontNames[$i] = $fontKeyMap[$fKey]
|
||||
continue
|
||||
}
|
||||
|
||||
$name = $null
|
||||
|
||||
if ($f.Face -eq $df.Face -and $f.Size -eq $df.Size) {
|
||||
if ($f.Bold -and -not $df.Bold -and -not $f.Italic -and -not $f.Underline -and -not $f.Strikeout) {
|
||||
$name = "bold"
|
||||
} elseif ($f.Italic -and -not $df.Italic -and -not $f.Bold) {
|
||||
$name = "italic"
|
||||
} elseif ($f.Underline -and -not $df.Underline -and -not $f.Bold -and -not $f.Italic) {
|
||||
$name = "underline"
|
||||
}
|
||||
} elseif ($f.Face -eq $df.Face -and $f.Size -gt $df.Size -and $f.Bold) {
|
||||
$name = "header"
|
||||
} elseif ($f.Face -eq $df.Face -and $f.Size -lt $df.Size) {
|
||||
$name = "small"
|
||||
}
|
||||
|
||||
if (-not $name) {
|
||||
$parts = @()
|
||||
if ($f.Face -and $f.Face -ne $df.Face) { $parts += $f.Face.ToLower() }
|
||||
$parts += "$($f.Size)"
|
||||
if ($f.Bold) { $parts += "bold" }
|
||||
if ($f.Italic) { $parts += "italic" }
|
||||
if ($f.Underline) { $parts += "underline" }
|
||||
if ($f.Strikeout) { $parts += "strikeout" }
|
||||
$name = $parts -join "-"
|
||||
}
|
||||
|
||||
$baseName = $name; $suffix = 2
|
||||
while ($fontDefs.Contains($name)) { $name = "$baseName$suffix"; $suffix++ }
|
||||
|
||||
$fontNames[$i] = $name
|
||||
$fontDefs[$name] = $f
|
||||
$fontKeyMap[$fKey] = $name
|
||||
}
|
||||
|
||||
# --- 11. Collect and name styles ---
|
||||
|
||||
$styleKeys = [ordered]@{}
|
||||
$formatToStyleKey = @{}
|
||||
|
||||
foreach ($r in $rowData.Values) {
|
||||
foreach ($cell in $r.Cells) {
|
||||
$fmt = Get-Format $cell.FormatIdx
|
||||
if (-not $fmt) { continue }
|
||||
$key = Get-StyleKey $fmt
|
||||
if (-not $styleKeys.Contains($key)) { $styleKeys[$key] = $fmt }
|
||||
$formatToStyleKey[$cell.FormatIdx] = $key
|
||||
}
|
||||
}
|
||||
|
||||
function Name-Style {
|
||||
param($fmt)
|
||||
if (-not $fmt) { return "default" }
|
||||
$parts = @()
|
||||
|
||||
$fi = if ($fmt.FontIdx -ge 0) { $fmt.FontIdx } else { 0 }
|
||||
if ($fontNames.ContainsKey($fi) -and $fontNames[$fi] -ne "default") {
|
||||
$parts += $fontNames[$fi]
|
||||
}
|
||||
|
||||
$bd = Get-BorderDesc $fmt
|
||||
if ($bd.Border -ne "none") {
|
||||
if ($bd.Border -eq "all") { $parts += "bordered" }
|
||||
else { $parts += "border-$($bd.Border)" }
|
||||
}
|
||||
|
||||
if ($fmt.HA -eq "Center") { $parts += "center" }
|
||||
elseif ($fmt.HA -eq "Right") { $parts += "right" }
|
||||
if ($fmt.VA -eq "Center") { $parts += "vcenter" }
|
||||
elseif ($fmt.VA -eq "Top") { $parts += "vtop" }
|
||||
if ($fmt.Wrap) { $parts += "wrap" }
|
||||
if ($fmt.DataFormat) { $parts += "fmt" }
|
||||
|
||||
if ($parts.Count -eq 0) { return "default" }
|
||||
return ($parts -join "-")
|
||||
}
|
||||
|
||||
$styleNames = [ordered]@{}
|
||||
$styleDefs = [ordered]@{}
|
||||
|
||||
foreach ($key in $styleKeys.Keys) {
|
||||
$fmt = $styleKeys[$key]
|
||||
$name = Name-Style $fmt
|
||||
|
||||
$baseName = $name; $suffix = 2
|
||||
while ($styleDefs.Contains($name)) { $name = "$baseName$suffix"; $suffix++ }
|
||||
|
||||
$styleNames[$key] = $name
|
||||
|
||||
$sDef = [ordered]@{}
|
||||
$fi = if ($fmt.FontIdx -ge 0) { $fmt.FontIdx } else { 0 }
|
||||
if ($fontNames.ContainsKey($fi) -and $fontNames[$fi] -ne "default") {
|
||||
$sDef["font"] = $fontNames[$fi]
|
||||
}
|
||||
if ($fmt.HA) {
|
||||
$a = switch ($fmt.HA) { "Left" { "left" } "Center" { "center" } "Right" { "right" } }
|
||||
if ($a) { $sDef["align"] = $a }
|
||||
}
|
||||
if ($fmt.VA) {
|
||||
$a = switch ($fmt.VA) { "Top" { "top" } "Center" { "center" } }
|
||||
if ($a) { $sDef["valign"] = $a }
|
||||
}
|
||||
$bd = Get-BorderDesc $fmt
|
||||
if ($bd.Border -ne "none") {
|
||||
$sDef["border"] = $bd.Border
|
||||
if ($bd.Thick) { $sDef["borderWidth"] = "thick" }
|
||||
}
|
||||
if ($fmt.Wrap) { $sDef["wrap"] = $true }
|
||||
if ($fmt.DataFormat) { $sDef["format"] = $fmt.DataFormat }
|
||||
|
||||
$styleDefs[$name] = $sDef
|
||||
}
|
||||
|
||||
function Get-StyleName {
|
||||
param([int]$fmtIdx)
|
||||
$key = $formatToStyleKey[$fmtIdx]
|
||||
if ($key -and $styleNames.Contains($key)) { return $styleNames[$key] }
|
||||
return "default"
|
||||
}
|
||||
|
||||
# --- 12. Build areas ---
|
||||
|
||||
$dslAreas = @()
|
||||
|
||||
foreach ($area in $namedAreas) {
|
||||
$areaRows = @()
|
||||
|
||||
for ($globalRow = $area.BeginRow; $globalRow -le $area.EndRow; $globalRow++) {
|
||||
$rd = $rowData[$globalRow]
|
||||
|
||||
if (-not $rd -or $rd.Empty) {
|
||||
$areaRows += [ordered]@{}
|
||||
continue
|
||||
}
|
||||
|
||||
$dslRow = [ordered]@{}
|
||||
|
||||
# Row height
|
||||
if ($rd.FormatIdx -gt 0) {
|
||||
$rowFmt = Get-Format $rd.FormatIdx
|
||||
if ($rowFmt -and $rowFmt.Height -gt 0) { $dslRow["height"] = $rowFmt.Height }
|
||||
}
|
||||
|
||||
# Separate content cells from gap-fill cells
|
||||
$contentCells = @()
|
||||
$gapCells = @()
|
||||
|
||||
foreach ($cell in $rd.Cells) {
|
||||
$hasContent = $cell.Param -or $cell.Text
|
||||
$hasMerge = $mergeMap.ContainsKey("$globalRow,$($cell.Col)")
|
||||
|
||||
if ($hasContent -or $hasMerge) {
|
||||
$contentCells += $cell
|
||||
} else {
|
||||
$gapCells += $cell
|
||||
}
|
||||
}
|
||||
|
||||
# Detect rowStyle
|
||||
$rowStyleName = $null
|
||||
$rowStyleKey = $null
|
||||
|
||||
if ($gapCells.Count -gt 0) {
|
||||
$gapKeys = @{}
|
||||
foreach ($gc in $gapCells) {
|
||||
$fmt = Get-Format $gc.FormatIdx
|
||||
$gapKeys[(Get-StyleKey $fmt)] = $true
|
||||
}
|
||||
|
||||
if ($gapKeys.Count -eq 1) {
|
||||
$rowStyleKey = @($gapKeys.Keys)[0]
|
||||
if ($styleNames.Contains($rowStyleKey)) {
|
||||
$rowStyleName = $styleNames[$rowStyleKey]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($rowStyleName -and $rowStyleName -ne "default") { $dslRow["rowStyle"] = $rowStyleName }
|
||||
|
||||
# Build cell list
|
||||
$dslCells = @()
|
||||
|
||||
foreach ($cell in ($contentCells | Sort-Object { $_.Col })) {
|
||||
$dslCell = [ordered]@{ col = $cell.Col + 1 }
|
||||
|
||||
# Span/rowspan from merge
|
||||
$mk = "$globalRow,$($cell.Col)"
|
||||
if ($mergeMap.ContainsKey($mk)) {
|
||||
$m = $mergeMap[$mk]
|
||||
if ($m.W -gt 0) { $dslCell["span"] = $m.W + 1 }
|
||||
if ($m.H -gt 0) { $dslCell["rowspan"] = $m.H + 1 }
|
||||
}
|
||||
|
||||
# Style
|
||||
$cellFmt = Get-Format $cell.FormatIdx
|
||||
$cellStyleKey = Get-StyleKey $cellFmt
|
||||
|
||||
if ($rowStyleKey -and $cellStyleKey -eq $rowStyleKey) {
|
||||
# Inherits rowStyle
|
||||
} else {
|
||||
$sn = Get-StyleName $cell.FormatIdx
|
||||
if ($sn -ne "default" -or -not $rowStyleName) {
|
||||
$dslCell["style"] = $sn
|
||||
}
|
||||
}
|
||||
|
||||
# Content
|
||||
$fillType = if ($cellFmt) { $cellFmt.FillType } else { "" }
|
||||
|
||||
if ($cell.Param) {
|
||||
$dslCell["param"] = $cell.Param
|
||||
if ($cell.Detail) { $dslCell["detail"] = $cell.Detail }
|
||||
} elseif ($fillType -eq "Template" -and $cell.Text) {
|
||||
$dslCell["template"] = $cell.Text
|
||||
} elseif ($cell.Text) {
|
||||
$dslCell["text"] = $cell.Text
|
||||
}
|
||||
|
||||
$dslCells += $dslCell
|
||||
}
|
||||
|
||||
if ($dslCells.Count -gt 0) { $dslRow["cells"] = [array]$dslCells }
|
||||
$areaRows += $dslRow
|
||||
}
|
||||
|
||||
# Compress consecutive empty rows ({}) into { empty = N }
|
||||
$compressedRows = @()
|
||||
$emptyRun = 0
|
||||
foreach ($r in $areaRows) {
|
||||
if ($r.Count -eq 0) {
|
||||
$emptyRun++
|
||||
} else {
|
||||
if ($emptyRun -gt 0) {
|
||||
if ($emptyRun -eq 1) { $compressedRows += [ordered]@{} }
|
||||
else { $compressedRows += [ordered]@{ empty = $emptyRun } }
|
||||
$emptyRun = 0
|
||||
}
|
||||
$compressedRows += $r
|
||||
}
|
||||
}
|
||||
if ($emptyRun -gt 0) {
|
||||
if ($emptyRun -eq 1) { $compressedRows += [ordered]@{} }
|
||||
else { $compressedRows += [ordered]@{ empty = $emptyRun } }
|
||||
}
|
||||
|
||||
$dslAreas += [ordered]@{
|
||||
name = $area.Name
|
||||
rows = [array]$compressedRows
|
||||
}
|
||||
}
|
||||
|
||||
# --- 13. Compress columnWidths ---
|
||||
|
||||
$compressedWidths = [ordered]@{}
|
||||
if ($colWidthMap.Count -gt 0) {
|
||||
$grouped = $colWidthMap.Keys | Group-Object { $colWidthMap[$_] }
|
||||
foreach ($g in $grouped) {
|
||||
$width = [int]$g.Name
|
||||
$cols = @($g.Group | Sort-Object { [int]$_ })
|
||||
|
||||
$ranges = @()
|
||||
$rangeStart = $cols[0]; $rangePrev = $cols[0]
|
||||
|
||||
for ($i = 1; $i -lt $cols.Count; $i++) {
|
||||
if ([int]$cols[$i] -eq [int]$rangePrev + 1) {
|
||||
$rangePrev = $cols[$i]
|
||||
} else {
|
||||
if ($rangeStart -eq $rangePrev) { $ranges += "$rangeStart" }
|
||||
else { $ranges += "$rangeStart-$rangePrev" }
|
||||
$rangeStart = $cols[$i]; $rangePrev = $cols[$i]
|
||||
}
|
||||
}
|
||||
if ($rangeStart -eq $rangePrev) { $ranges += "$rangeStart" }
|
||||
else { $ranges += "$rangeStart-$rangePrev" }
|
||||
|
||||
foreach ($range in $ranges) { $compressedWidths[$range] = $width }
|
||||
}
|
||||
}
|
||||
|
||||
# --- 14. Build fonts output ---
|
||||
|
||||
$fontsOut = [ordered]@{}
|
||||
foreach ($name in $fontDefs.Keys) {
|
||||
$f = $fontDefs[$name]
|
||||
$fOut = [ordered]@{ face = $f.Face; size = $f.Size }
|
||||
if ($f.Bold) { $fOut["bold"] = $true }
|
||||
if ($f.Italic) { $fOut["italic"] = $true }
|
||||
if ($f.Underline) { $fOut["underline"] = $true }
|
||||
if ($f.Strikeout) { $fOut["strikeout"] = $true }
|
||||
$fontsOut[$name] = $fOut
|
||||
}
|
||||
|
||||
# --- 15. Assemble result ---
|
||||
|
||||
$result = [ordered]@{
|
||||
columns = $totalColumns
|
||||
defaultWidth = $defaultWidth
|
||||
}
|
||||
if ($compressedWidths.Count -gt 0) { $result["columnWidths"] = $compressedWidths }
|
||||
# Remove empty "default" style
|
||||
if ($styleDefs.Contains("default") -and $styleDefs["default"].Count -eq 0) {
|
||||
$styleDefs.Remove("default")
|
||||
}
|
||||
|
||||
# Remove unused styles
|
||||
$usedStyles = @{}
|
||||
foreach ($a in $dslAreas) {
|
||||
foreach ($r in $a.rows) {
|
||||
if ($r.rowStyle) { $usedStyles[$r.rowStyle] = $true }
|
||||
if ($r.cells) { foreach ($c in $r.cells) { if ($c.style) { $usedStyles[$c.style] = $true } } }
|
||||
}
|
||||
}
|
||||
$toRemove = @($styleDefs.Keys | Where-Object { -not $usedStyles.ContainsKey($_) })
|
||||
foreach ($s in $toRemove) { $styleDefs.Remove($s)
|
||||
}
|
||||
|
||||
$result["fonts"] = $fontsOut
|
||||
$result["styles"] = $styleDefs
|
||||
$result["areas"] = [array]$dslAreas
|
||||
|
||||
# --- 16. Convert to JSON and fix Unicode ---
|
||||
|
||||
$json = $result | ConvertTo-Json -Depth 10
|
||||
|
||||
# PS 5.1 escapes non-ASCII as \uXXXX — unescape back to UTF-8
|
||||
$json = [regex]::Replace($json, '\\u([0-9A-Fa-f]{4})', {
|
||||
param($m)
|
||||
[char][int]("0x" + $m.Groups[1].Value)
|
||||
})
|
||||
|
||||
# --- 17. Output ---
|
||||
|
||||
if ($OutputPath) {
|
||||
$enc = New-Object System.Text.UTF8Encoding($false)
|
||||
[System.IO.File]::WriteAllText(
|
||||
(Join-Path (Get-Location) $OutputPath),
|
||||
$json,
|
||||
$enc
|
||||
)
|
||||
Write-Host "[OK] Decompiled: $OutputPath"
|
||||
} else {
|
||||
Write-Output $json
|
||||
}
|
||||
|
||||
Write-Host " Areas: $($namedAreas.Count), Rows: $($rowData.Count), Columns: $totalColumns" -ForegroundColor DarkGray
|
||||
Write-Host " Fonts: $($fontDefs.Count), Styles: $($styleDefs.Count), Merges: $($mergeMap.Count)" -ForegroundColor DarkGray
|
||||
@@ -1,705 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# mxl-decompile v1.0 — Decompile 1C spreadsheet to JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from lxml import etree
|
||||
|
||||
# --- Namespace map ---
|
||||
|
||||
NSMAP = {
|
||||
"d": "http://v8.1c.ru/8.2/data/spreadsheet",
|
||||
"v8": "http://v8.1c.ru/8.1/data/core",
|
||||
"v8ui": "http://v8.1c.ru/8.1/data/ui",
|
||||
"xsi": "http://www.w3.org/2001/XMLSchema-instance",
|
||||
}
|
||||
|
||||
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
|
||||
|
||||
|
||||
def find(node, xpath):
|
||||
return node.find(xpath, NSMAP)
|
||||
|
||||
|
||||
def findall(node, xpath):
|
||||
return node.findall(xpath, NSMAP)
|
||||
|
||||
|
||||
def text_of(node):
|
||||
if node is not None and node.text:
|
||||
return node.text
|
||||
return None
|
||||
|
||||
|
||||
def int_of(node, default=0):
|
||||
if node is not None and node.text:
|
||||
return int(node.text)
|
||||
return default
|
||||
|
||||
|
||||
# --- Main ---
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description="Decompile 1C spreadsheet to JSON", allow_abbrev=False)
|
||||
parser.add_argument("-TemplatePath", "-Path", required=True, help="Path to Template.xml")
|
||||
parser.add_argument("-OutputPath", default=None, help="Output JSON path (stdout if omitted)")
|
||||
args = parser.parse_args()
|
||||
|
||||
template_path = args.TemplatePath
|
||||
output_path = args.OutputPath
|
||||
|
||||
# --- 1. Load and parse XML ---
|
||||
|
||||
if not os.path.isfile(template_path):
|
||||
print(f"File not found: {template_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
parser_xml = etree.XMLParser(remove_blank_text=False)
|
||||
tree = etree.parse(template_path, parser_xml)
|
||||
root = tree.getroot()
|
||||
|
||||
# --- 2. Extract font palette ---
|
||||
|
||||
raw_fonts = []
|
||||
for f_node in findall(root, "d:font"):
|
||||
raw_fonts.append({
|
||||
"Face": f_node.get("faceName", ""),
|
||||
"Size": int(f_node.get("height", "0")),
|
||||
"Bold": f_node.get("bold") == "true",
|
||||
"Italic": f_node.get("italic") == "true",
|
||||
"Underline": f_node.get("underline") == "true",
|
||||
"Strikeout": f_node.get("strikeout") == "true",
|
||||
})
|
||||
|
||||
# --- 3. Extract line palette ---
|
||||
|
||||
raw_lines = []
|
||||
for l_node in findall(root, "d:line"):
|
||||
raw_lines.append({"Width": int(l_node.get("width", "0"))})
|
||||
|
||||
# --- 4. Extract format palette ---
|
||||
|
||||
raw_formats = []
|
||||
for fmt_node in findall(root, "d:format"):
|
||||
fmt = {
|
||||
"FontIdx": -1,
|
||||
"LB": -1, "TB": -1, "RB": -1, "BB": -1,
|
||||
"Width": 0, "Height": 0,
|
||||
"HA": "", "VA": "",
|
||||
"Wrap": False, "FillType": "", "DataFormat": "",
|
||||
}
|
||||
|
||||
n = find(fmt_node, "d:font")
|
||||
if n is not None and n.text:
|
||||
fmt["FontIdx"] = int(n.text)
|
||||
n = find(fmt_node, "d:leftBorder")
|
||||
if n is not None and n.text:
|
||||
fmt["LB"] = int(n.text)
|
||||
n = find(fmt_node, "d:topBorder")
|
||||
if n is not None and n.text:
|
||||
fmt["TB"] = int(n.text)
|
||||
n = find(fmt_node, "d:rightBorder")
|
||||
if n is not None and n.text:
|
||||
fmt["RB"] = int(n.text)
|
||||
n = find(fmt_node, "d:bottomBorder")
|
||||
if n is not None and n.text:
|
||||
fmt["BB"] = int(n.text)
|
||||
|
||||
n = find(fmt_node, "d:width")
|
||||
if n is not None and n.text:
|
||||
fmt["Width"] = int(n.text)
|
||||
n = find(fmt_node, "d:height")
|
||||
if n is not None and n.text:
|
||||
fmt["Height"] = int(n.text)
|
||||
|
||||
n = find(fmt_node, "d:horizontalAlignment")
|
||||
if n is not None and n.text:
|
||||
fmt["HA"] = n.text
|
||||
n = find(fmt_node, "d:verticalAlignment")
|
||||
if n is not None and n.text:
|
||||
fmt["VA"] = n.text
|
||||
|
||||
n = find(fmt_node, "d:textPlacement")
|
||||
if n is not None and n.text == "Wrap":
|
||||
fmt["Wrap"] = True
|
||||
|
||||
n = find(fmt_node, "d:fillType")
|
||||
if n is not None and n.text:
|
||||
fmt["FillType"] = n.text
|
||||
|
||||
n = find(fmt_node, "d:format/v8:item/v8:content")
|
||||
if n is not None and n.text:
|
||||
fmt["DataFormat"] = n.text
|
||||
|
||||
raw_formats.append(fmt)
|
||||
|
||||
def get_format(idx):
|
||||
if idx <= 0 or idx > len(raw_formats):
|
||||
return None
|
||||
return raw_formats[idx - 1]
|
||||
|
||||
# --- 5. Extract columns and default width ---
|
||||
|
||||
col_node = find(root, "d:columns")
|
||||
total_columns = int_of(find(col_node, "d:size"))
|
||||
|
||||
col_format_indices = {}
|
||||
for ci in findall(col_node, "d:columnsItem"):
|
||||
col_idx = int_of(find(ci, "d:index"))
|
||||
fmt_idx = int_of(find(ci, "d:column/d:formatIndex"))
|
||||
col_format_indices[col_idx] = fmt_idx
|
||||
|
||||
default_fmt_idx = 0
|
||||
n = find(root, "d:defaultFormatIndex")
|
||||
if n is not None and n.text:
|
||||
default_fmt_idx = int(n.text)
|
||||
|
||||
default_width = 10
|
||||
if default_fmt_idx > 0:
|
||||
def_fmt = get_format(default_fmt_idx)
|
||||
if def_fmt and def_fmt["Width"] > 0:
|
||||
default_width = def_fmt["Width"]
|
||||
|
||||
# Build column width map (1-based col -> width), only non-default
|
||||
col_width_map = OrderedDict()
|
||||
for col0 in sorted(col_format_indices.keys()):
|
||||
fmt = get_format(col_format_indices[col0])
|
||||
if fmt and fmt["Width"] > 0 and fmt["Width"] != default_width:
|
||||
col1 = str(col0 + 1)
|
||||
col_width_map[col1] = fmt["Width"]
|
||||
|
||||
# --- 6. Extract merges ---
|
||||
|
||||
merge_map = {}
|
||||
for m_node in findall(root, "d:merge"):
|
||||
r = int_of(find(m_node, "d:r"))
|
||||
c = int_of(find(m_node, "d:c"))
|
||||
w = int_of(find(m_node, "d:w"))
|
||||
h_node = find(m_node, "d:h")
|
||||
h = int_of(h_node) if h_node is not None else 0
|
||||
merge_map[f"{r},{c}"] = {"W": w, "H": h}
|
||||
|
||||
# --- 7. Extract named items ---
|
||||
|
||||
named_areas = []
|
||||
for ni_node in findall(root, "d:namedItem"):
|
||||
xsi_type = ni_node.get(f"{{{XSI_NS}}}type", "")
|
||||
if xsi_type != "NamedItemCells":
|
||||
continue
|
||||
|
||||
area_node = find(ni_node, "d:area")
|
||||
area_type_node = find(area_node, "d:type")
|
||||
area_type = text_of(area_type_node) or ""
|
||||
if area_type != "Rows":
|
||||
continue
|
||||
|
||||
named_areas.append({
|
||||
"Name": text_of(find(ni_node, "d:name")) or "",
|
||||
"BeginRow": int_of(find(area_node, "d:beginRow")),
|
||||
"EndRow": int_of(find(area_node, "d:endRow")),
|
||||
})
|
||||
|
||||
# --- 8. Extract rows ---
|
||||
|
||||
row_data = {}
|
||||
for ri_node in findall(root, "d:rowsItem"):
|
||||
row_idx = int_of(find(ri_node, "d:index"))
|
||||
row_node = find(ri_node, "d:row")
|
||||
|
||||
index_to = row_idx
|
||||
it_node = find(ri_node, "d:indexTo")
|
||||
if it_node is not None and it_node.text:
|
||||
index_to = int(it_node.text)
|
||||
|
||||
row_fmt_idx = 0
|
||||
fmt_node = find(row_node, "d:formatIndex")
|
||||
if fmt_node is not None and fmt_node.text:
|
||||
row_fmt_idx = int(fmt_node.text)
|
||||
|
||||
is_empty = False
|
||||
empty_node = find(row_node, "d:empty")
|
||||
if empty_node is not None and empty_node.text == "true":
|
||||
is_empty = True
|
||||
|
||||
cells = []
|
||||
if not is_empty:
|
||||
col = -1
|
||||
for c_group in findall(row_node, "d:c"):
|
||||
i_node = find(c_group, "d:i")
|
||||
if i_node is not None and i_node.text:
|
||||
col = int(i_node.text)
|
||||
else:
|
||||
col += 1
|
||||
|
||||
c_content = find(c_group, "d:c")
|
||||
if c_content is None:
|
||||
continue
|
||||
|
||||
cell_fmt_idx = 0
|
||||
f_node = find(c_content, "d:f")
|
||||
if f_node is not None and f_node.text:
|
||||
cell_fmt_idx = int(f_node.text)
|
||||
|
||||
param = None
|
||||
p_node = find(c_content, "d:parameter")
|
||||
if p_node is not None and p_node.text:
|
||||
param = p_node.text
|
||||
|
||||
detail = None
|
||||
d_node = find(c_content, "d:detailParameter")
|
||||
if d_node is not None and d_node.text:
|
||||
detail = d_node.text
|
||||
|
||||
text = None
|
||||
t_node = find(c_content, "d:tl/v8:item/v8:content")
|
||||
if t_node is not None and t_node.text:
|
||||
text = t_node.text
|
||||
|
||||
cells.append({
|
||||
"Col": col,
|
||||
"FormatIdx": cell_fmt_idx,
|
||||
"Param": param,
|
||||
"Detail": detail,
|
||||
"Text": text,
|
||||
})
|
||||
|
||||
for r in range(row_idx, index_to + 1):
|
||||
row_data[r] = {
|
||||
"FormatIdx": row_fmt_idx,
|
||||
"Cells": cells,
|
||||
"Empty": is_empty,
|
||||
}
|
||||
|
||||
# --- 9. Build style key (ignoring fillType) ---
|
||||
|
||||
def get_border_desc(fmt):
|
||||
if not fmt:
|
||||
return {"Border": "none", "Thick": False}
|
||||
|
||||
lb = fmt["LB"] >= 0
|
||||
tb = fmt["TB"] >= 0
|
||||
rb = fmt["RB"] >= 0
|
||||
bb = fmt["BB"] >= 0
|
||||
|
||||
if not lb and not tb and not rb and not bb:
|
||||
return {"Border": "none", "Thick": False}
|
||||
|
||||
thick = False
|
||||
for b_idx in [fmt["LB"], fmt["TB"], fmt["RB"], fmt["BB"]]:
|
||||
if b_idx >= 0 and b_idx < len(raw_lines) and raw_lines[b_idx]["Width"] >= 2:
|
||||
thick = True
|
||||
break
|
||||
|
||||
if lb and tb and rb and bb:
|
||||
return {"Border": "all", "Thick": thick}
|
||||
|
||||
sides = []
|
||||
if tb:
|
||||
sides.append("top")
|
||||
if bb:
|
||||
sides.append("bottom")
|
||||
if lb:
|
||||
sides.append("left")
|
||||
if rb:
|
||||
sides.append("right")
|
||||
|
||||
return {"Border": ",".join(sides), "Thick": thick}
|
||||
|
||||
def get_style_key(fmt):
|
||||
if not fmt:
|
||||
return "empty"
|
||||
fi = fmt["FontIdx"] if fmt["FontIdx"] >= 0 else 0
|
||||
bd = get_border_desc(fmt)
|
||||
return f"f={fi}|b={bd['Border']}|bw={bd['Thick']}|ha={fmt['HA']}|va={fmt['VA']}|wr={fmt['Wrap']}|df={fmt['DataFormat']}"
|
||||
|
||||
# --- 10. Name fonts ---
|
||||
|
||||
font_names = {}
|
||||
font_defs = OrderedDict()
|
||||
|
||||
if len(raw_fonts) > 0:
|
||||
font_names[0] = "default"
|
||||
font_defs["default"] = raw_fonts[0]
|
||||
|
||||
def get_font_key(f):
|
||||
return f"{f['Face']}|{f['Size']}|{f['Bold']}|{f['Italic']}|{f['Underline']}|{f['Strikeout']}"
|
||||
|
||||
font_key_map = {}
|
||||
if len(raw_fonts) > 0:
|
||||
font_key_map[get_font_key(raw_fonts[0])] = "default"
|
||||
|
||||
for i in range(1, len(raw_fonts)):
|
||||
f = raw_fonts[i]
|
||||
df = raw_fonts[0]
|
||||
|
||||
# Dedup: if identical font already named, reuse
|
||||
f_key = get_font_key(f)
|
||||
if f_key in font_key_map:
|
||||
font_names[i] = font_key_map[f_key]
|
||||
continue
|
||||
|
||||
name = None
|
||||
|
||||
if f["Face"] == df["Face"] and f["Size"] == df["Size"]:
|
||||
if f["Bold"] and not df["Bold"] and not f["Italic"] and not f["Underline"] and not f["Strikeout"]:
|
||||
name = "bold"
|
||||
elif f["Italic"] and not df["Italic"] and not f["Bold"]:
|
||||
name = "italic"
|
||||
elif f["Underline"] and not df["Underline"] and not f["Bold"] and not f["Italic"]:
|
||||
name = "underline"
|
||||
elif f["Face"] == df["Face"] and f["Size"] > df["Size"] and f["Bold"]:
|
||||
name = "header"
|
||||
elif f["Face"] == df["Face"] and f["Size"] < df["Size"]:
|
||||
name = "small"
|
||||
|
||||
if not name:
|
||||
parts = []
|
||||
if f["Face"] and f["Face"] != df["Face"]:
|
||||
parts.append(f["Face"].lower())
|
||||
parts.append(str(f["Size"]))
|
||||
if f["Bold"]:
|
||||
parts.append("bold")
|
||||
if f["Italic"]:
|
||||
parts.append("italic")
|
||||
if f["Underline"]:
|
||||
parts.append("underline")
|
||||
if f["Strikeout"]:
|
||||
parts.append("strikeout")
|
||||
name = "-".join(parts)
|
||||
|
||||
base_name = name
|
||||
suffix = 2
|
||||
while name in font_defs:
|
||||
name = f"{base_name}{suffix}"
|
||||
suffix += 1
|
||||
|
||||
font_names[i] = name
|
||||
font_defs[name] = f
|
||||
font_key_map[f_key] = name
|
||||
|
||||
# --- 11. Collect and name styles ---
|
||||
|
||||
style_keys = OrderedDict()
|
||||
format_to_style_key = {}
|
||||
|
||||
for rd in row_data.values():
|
||||
for cell in rd["Cells"]:
|
||||
fmt = get_format(cell["FormatIdx"])
|
||||
if not fmt:
|
||||
continue
|
||||
key = get_style_key(fmt)
|
||||
if key not in style_keys:
|
||||
style_keys[key] = fmt
|
||||
format_to_style_key[cell["FormatIdx"]] = key
|
||||
|
||||
def name_style(fmt):
|
||||
if not fmt:
|
||||
return "default"
|
||||
parts = []
|
||||
|
||||
fi = fmt["FontIdx"] if fmt["FontIdx"] >= 0 else 0
|
||||
if fi in font_names and font_names[fi] != "default":
|
||||
parts.append(font_names[fi])
|
||||
|
||||
bd = get_border_desc(fmt)
|
||||
if bd["Border"] != "none":
|
||||
if bd["Border"] == "all":
|
||||
parts.append("bordered")
|
||||
else:
|
||||
parts.append(f"border-{bd['Border']}")
|
||||
|
||||
if fmt["HA"] == "Center":
|
||||
parts.append("center")
|
||||
elif fmt["HA"] == "Right":
|
||||
parts.append("right")
|
||||
if fmt["VA"] == "Center":
|
||||
parts.append("vcenter")
|
||||
elif fmt["VA"] == "Top":
|
||||
parts.append("vtop")
|
||||
if fmt["Wrap"]:
|
||||
parts.append("wrap")
|
||||
if fmt["DataFormat"]:
|
||||
parts.append("fmt")
|
||||
|
||||
if len(parts) == 0:
|
||||
return "default"
|
||||
return "-".join(parts)
|
||||
|
||||
style_names = OrderedDict()
|
||||
style_defs = OrderedDict()
|
||||
|
||||
for key in style_keys:
|
||||
fmt = style_keys[key]
|
||||
name = name_style(fmt)
|
||||
|
||||
base_name = name
|
||||
suffix = 2
|
||||
while name in style_defs:
|
||||
name = f"{base_name}{suffix}"
|
||||
suffix += 1
|
||||
|
||||
style_names[key] = name
|
||||
|
||||
s_def = OrderedDict()
|
||||
fi = fmt["FontIdx"] if fmt["FontIdx"] >= 0 else 0
|
||||
if fi in font_names and font_names[fi] != "default":
|
||||
s_def["font"] = font_names[fi]
|
||||
if fmt["HA"]:
|
||||
a_map = {"Left": "left", "Center": "center", "Right": "right"}
|
||||
a = a_map.get(fmt["HA"])
|
||||
if a:
|
||||
s_def["align"] = a
|
||||
if fmt["VA"]:
|
||||
va_map = {"Top": "top", "Center": "center"}
|
||||
a = va_map.get(fmt["VA"])
|
||||
if a:
|
||||
s_def["valign"] = a
|
||||
bd = get_border_desc(fmt)
|
||||
if bd["Border"] != "none":
|
||||
s_def["border"] = bd["Border"]
|
||||
if bd["Thick"]:
|
||||
s_def["borderWidth"] = "thick"
|
||||
if fmt["Wrap"]:
|
||||
s_def["wrap"] = True
|
||||
if fmt["DataFormat"]:
|
||||
s_def["format"] = fmt["DataFormat"]
|
||||
|
||||
style_defs[name] = s_def
|
||||
|
||||
def get_style_name(fmt_idx):
|
||||
key = format_to_style_key.get(fmt_idx)
|
||||
if key and key in style_names:
|
||||
return style_names[key]
|
||||
return "default"
|
||||
|
||||
# --- 12. Build areas ---
|
||||
|
||||
dsl_areas = []
|
||||
|
||||
for area in named_areas:
|
||||
area_rows = []
|
||||
|
||||
for global_row in range(area["BeginRow"], area["EndRow"] + 1):
|
||||
rd = row_data.get(global_row)
|
||||
|
||||
if not rd or rd["Empty"]:
|
||||
area_rows.append(OrderedDict())
|
||||
continue
|
||||
|
||||
dsl_row = OrderedDict()
|
||||
|
||||
# Row height
|
||||
if rd["FormatIdx"] > 0:
|
||||
row_fmt = get_format(rd["FormatIdx"])
|
||||
if row_fmt and row_fmt["Height"] > 0:
|
||||
dsl_row["height"] = row_fmt["Height"]
|
||||
|
||||
# Separate content cells from gap-fill cells
|
||||
content_cells = []
|
||||
gap_cells = []
|
||||
|
||||
for cell in rd["Cells"]:
|
||||
has_content = cell["Param"] or cell["Text"]
|
||||
has_merge = f"{global_row},{cell['Col']}" in merge_map
|
||||
|
||||
if has_content or has_merge:
|
||||
content_cells.append(cell)
|
||||
else:
|
||||
gap_cells.append(cell)
|
||||
|
||||
# Detect rowStyle
|
||||
row_style_name = None
|
||||
row_style_key = None
|
||||
|
||||
if len(gap_cells) > 0:
|
||||
gap_keys = {}
|
||||
for gc in gap_cells:
|
||||
fmt = get_format(gc["FormatIdx"])
|
||||
gap_keys[get_style_key(fmt)] = True
|
||||
|
||||
if len(gap_keys) == 1:
|
||||
row_style_key = list(gap_keys.keys())[0]
|
||||
if row_style_key in style_names:
|
||||
row_style_name = style_names[row_style_key]
|
||||
|
||||
if row_style_name and row_style_name != "default":
|
||||
dsl_row["rowStyle"] = row_style_name
|
||||
|
||||
# Build cell list
|
||||
dsl_cells = []
|
||||
|
||||
for cell in sorted(content_cells, key=lambda c: c["Col"]):
|
||||
dsl_cell = OrderedDict()
|
||||
dsl_cell["col"] = cell["Col"] + 1
|
||||
|
||||
# Span/rowspan from merge
|
||||
mk = f"{global_row},{cell['Col']}"
|
||||
if mk in merge_map:
|
||||
m = merge_map[mk]
|
||||
if m["W"] > 0:
|
||||
dsl_cell["span"] = m["W"] + 1
|
||||
if m["H"] > 0:
|
||||
dsl_cell["rowspan"] = m["H"] + 1
|
||||
|
||||
# Style
|
||||
cell_fmt = get_format(cell["FormatIdx"])
|
||||
cell_style_key = get_style_key(cell_fmt)
|
||||
|
||||
if row_style_key and cell_style_key == row_style_key:
|
||||
pass # Inherits rowStyle
|
||||
else:
|
||||
sn = get_style_name(cell["FormatIdx"])
|
||||
if sn != "default" or not row_style_name:
|
||||
dsl_cell["style"] = sn
|
||||
|
||||
# Content
|
||||
fill_type = cell_fmt["FillType"] if cell_fmt else ""
|
||||
|
||||
if cell["Param"]:
|
||||
dsl_cell["param"] = cell["Param"]
|
||||
if cell["Detail"]:
|
||||
dsl_cell["detail"] = cell["Detail"]
|
||||
elif fill_type == "Template" and cell["Text"]:
|
||||
dsl_cell["template"] = cell["Text"]
|
||||
elif cell["Text"]:
|
||||
dsl_cell["text"] = cell["Text"]
|
||||
|
||||
dsl_cells.append(dsl_cell)
|
||||
|
||||
if len(dsl_cells) > 0:
|
||||
dsl_row["cells"] = dsl_cells
|
||||
area_rows.append(dsl_row)
|
||||
|
||||
# Compress consecutive empty rows ({}) into { empty = N }
|
||||
compressed_rows = []
|
||||
empty_run = 0
|
||||
for r in area_rows:
|
||||
if len(r) == 0:
|
||||
empty_run += 1
|
||||
else:
|
||||
if empty_run > 0:
|
||||
if empty_run == 1:
|
||||
compressed_rows.append(OrderedDict())
|
||||
else:
|
||||
compressed_rows.append(OrderedDict([("empty", empty_run)]))
|
||||
empty_run = 0
|
||||
compressed_rows.append(r)
|
||||
if empty_run > 0:
|
||||
if empty_run == 1:
|
||||
compressed_rows.append(OrderedDict())
|
||||
else:
|
||||
compressed_rows.append(OrderedDict([("empty", empty_run)]))
|
||||
|
||||
dsl_areas.append(OrderedDict([
|
||||
("name", area["Name"]),
|
||||
("rows", compressed_rows),
|
||||
]))
|
||||
|
||||
# --- 13. Compress columnWidths ---
|
||||
|
||||
compressed_widths = OrderedDict()
|
||||
if len(col_width_map) > 0:
|
||||
# Group columns by width
|
||||
width_to_cols = {}
|
||||
for col_str, width in col_width_map.items():
|
||||
width_to_cols.setdefault(width, []).append(col_str)
|
||||
|
||||
for width, cols in width_to_cols.items():
|
||||
cols_sorted = sorted(cols, key=lambda x: int(x))
|
||||
|
||||
ranges = []
|
||||
range_start = cols_sorted[0]
|
||||
range_prev = cols_sorted[0]
|
||||
|
||||
for i in range(1, len(cols_sorted)):
|
||||
if int(cols_sorted[i]) == int(range_prev) + 1:
|
||||
range_prev = cols_sorted[i]
|
||||
else:
|
||||
if range_start == range_prev:
|
||||
ranges.append(range_start)
|
||||
else:
|
||||
ranges.append(f"{range_start}-{range_prev}")
|
||||
range_start = cols_sorted[i]
|
||||
range_prev = cols_sorted[i]
|
||||
|
||||
if range_start == range_prev:
|
||||
ranges.append(range_start)
|
||||
else:
|
||||
ranges.append(f"{range_start}-{range_prev}")
|
||||
|
||||
for rng in ranges:
|
||||
compressed_widths[rng] = width
|
||||
|
||||
# --- 14. Build fonts output ---
|
||||
|
||||
fonts_out = OrderedDict()
|
||||
for name, f in font_defs.items():
|
||||
f_out = OrderedDict()
|
||||
f_out["face"] = f["Face"]
|
||||
f_out["size"] = f["Size"]
|
||||
if f["Bold"]:
|
||||
f_out["bold"] = True
|
||||
if f["Italic"]:
|
||||
f_out["italic"] = True
|
||||
if f["Underline"]:
|
||||
f_out["underline"] = True
|
||||
if f["Strikeout"]:
|
||||
f_out["strikeout"] = True
|
||||
fonts_out[name] = f_out
|
||||
|
||||
# --- 15. Assemble result ---
|
||||
|
||||
result = OrderedDict()
|
||||
result["columns"] = total_columns
|
||||
result["defaultWidth"] = default_width
|
||||
if len(compressed_widths) > 0:
|
||||
result["columnWidths"] = compressed_widths
|
||||
|
||||
# Remove empty "default" style
|
||||
if "default" in style_defs and len(style_defs["default"]) == 0:
|
||||
del style_defs["default"]
|
||||
|
||||
# Remove unused styles
|
||||
used_styles = set()
|
||||
for a in dsl_areas:
|
||||
for r in a["rows"]:
|
||||
if "rowStyle" in r:
|
||||
used_styles.add(r["rowStyle"])
|
||||
if "cells" in r:
|
||||
for c in r["cells"]:
|
||||
if "style" in c:
|
||||
used_styles.add(c["style"])
|
||||
to_remove = [s for s in style_defs if s not in used_styles]
|
||||
for s in to_remove:
|
||||
del style_defs[s]
|
||||
|
||||
result["fonts"] = fonts_out
|
||||
result["styles"] = style_defs
|
||||
result["areas"] = dsl_areas
|
||||
|
||||
# --- 16. Convert to JSON ---
|
||||
|
||||
json_str = json.dumps(result, ensure_ascii=False, indent=2)
|
||||
|
||||
# --- 17. Output ---
|
||||
|
||||
if output_path:
|
||||
abs_path = os.path.join(os.getcwd(), output_path) if not os.path.isabs(output_path) else output_path
|
||||
with open(abs_path, "w", encoding="utf-8") as fh:
|
||||
fh.write(json_str)
|
||||
print(f"[OK] Decompiled: {output_path}")
|
||||
else:
|
||||
print(json_str)
|
||||
|
||||
print(f" Areas: {len(named_areas)}, Rows: {len(row_data)}, Columns: {total_columns}", file=sys.stderr)
|
||||
print(f" Fonts: {len(font_defs)}, Styles: {len(style_defs)}, Merges: {len(merge_map)}", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,109 +0,0 @@
|
||||
---
|
||||
name: role-compile
|
||||
description: Создание роли 1С из описания прав. Используй когда нужно создать новую роль с набором прав на объекты
|
||||
argument-hint: <JsonPath> <OutputDir>
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Write
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /role-compile — генерация роли 1С из JSON DSL
|
||||
|
||||
Принимает JSON-определение роли → генерирует `Roles/Имя.xml` (метаданные) и `Roles/Имя/Ext/Rights.xml` (права). UUID автоматически.
|
||||
|
||||
## Параметры и команда
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `JsonPath` | Путь к JSON-определению роли |
|
||||
| `OutputDir` | Корень выгрузки конфигурации (где `Configuration.xml`, `Roles/` и т.д.) |
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/role-compile.ps1" -JsonPath "<json>" -OutputDir "<ConfigDir>"
|
||||
```
|
||||
|
||||
Создаёт `{OutputDir}/Roles/Имя.xml` и `{OutputDir}/Roles/Имя/Ext/Rights.xml`. Регистрирует `<Role>` в `Configuration.xml`.
|
||||
|
||||
## JSON DSL
|
||||
|
||||
### Структура
|
||||
|
||||
```json
|
||||
{ "name": "ИмяРоли", "synonym": "Отображаемое имя", "objects": [...], "templates": [...] }
|
||||
```
|
||||
|
||||
Необязательные: `comment` (""), `setForNewObjects` (false), `setForAttributesByDefault` (true), `independentRightsOfChildObjects` (false).
|
||||
|
||||
### Shorthand-строки и объектная форма
|
||||
|
||||
```json
|
||||
"objects": [
|
||||
"Catalog.Номенклатура: @view",
|
||||
"Document.Реализация: @edit",
|
||||
"DataProcessor.Загрузка: @view",
|
||||
"InformationRegister.Цены: Read, Update",
|
||||
{ "name": "Document.Продажа", "preset": "view", "rights": {"Delete": false}, "rls": {"Read": "#Шаблон(\"\")"} }
|
||||
]
|
||||
```
|
||||
|
||||
- Shorthand: `"Тип.Имя: @пресет"` или `"Тип.Имя: Право1, Право2"`
|
||||
- Объектная форма: `preset` + `rights` (переопределения) + `rls` (ограничения)
|
||||
|
||||
### Пресеты
|
||||
|
||||
| Пресет | Действие |
|
||||
|--------|----------|
|
||||
| `@view` | Просмотр — Read, View (+InputByString для справочников/документов; Use+View для обработок/отчётов) |
|
||||
| `@edit` | Полное редактирование — CRUD + Interactive* + Posting (документы) |
|
||||
|
||||
`@` обязателен в shorthand. В объектной форме — `"preset": "view"` без `@`.
|
||||
|
||||
Для сервисов (WebService, HTTPService, IntegrationService) пресеты не определены — используй явные права: `"WebService.Имя: Use"`.
|
||||
|
||||
### Русские синонимы
|
||||
|
||||
Поддерживаются русские типы (`Справочник`→Catalog, `Документ`→Document) и права (`Чтение`→Read, `Просмотр`→View). Смешивание допустимо: `"Справочник.Контрагенты: Чтение, View"`.
|
||||
|
||||
### Шаблоны RLS
|
||||
|
||||
```json
|
||||
"templates": [{"name": "ДляОбъекта(Мод)", "condition": "ГДЕ Организация = &ТекОрг"}]
|
||||
```
|
||||
|
||||
Ссылка в `rls`: `"#ДляОбъекта(\"\")"`. Символ `&` автоматически экранируется в XML.
|
||||
|
||||
## Примеры
|
||||
|
||||
### Простая роль
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ЧтениеНоменклатуры", "synonym": "Чтение номенклатуры",
|
||||
"objects": ["Catalog.Номенклатура: @view", "Catalog.Контрагенты: @view", "DataProcessor.Загрузка: @view"]
|
||||
}
|
||||
```
|
||||
|
||||
### Роль с RLS
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ЧтениеДокументовПоОрганизации",
|
||||
"synonym": "Чтение документов (ограничение по организации)",
|
||||
"objects": [
|
||||
"Catalog.Организации: @view",
|
||||
{"name": "Document.РеализацияТоваровУслуг", "preset": "view", "rls": {"Read": "#ДляОбъекта(\"\")"}}
|
||||
],
|
||||
"templates": [{"name": "ДляОбъекта(Модификатор)", "condition": "ГДЕ Организация = &ТекущаяОрганизация"}]
|
||||
}
|
||||
```
|
||||
|
||||
Подробные таблицы пресетов, русских синонимов и дополнительные примеры — в `dsl-reference.md`.
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/role-validate <RightsPath> [MetadataPath] — проверка корректности XML, прав, RLS
|
||||
/role-info <RightsPath> — визуальная сводка структуры
|
||||
```
|
||||
@@ -1,313 +0,0 @@
|
||||
# Role DSL — полная справка
|
||||
|
||||
Подробная справка по JSON DSL для `/role-compile`. Компактное описание — в [SKILL.md](SKILL.md).
|
||||
|
||||
## Структура верхнего уровня
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ИмяРоли",
|
||||
"synonym": "Отображаемое имя роли",
|
||||
"comment": "",
|
||||
"setForNewObjects": false,
|
||||
"setForAttributesByDefault": true,
|
||||
"independentRightsOfChildObjects": false,
|
||||
"objects": [ ... ],
|
||||
"templates": [ ... ]
|
||||
}
|
||||
```
|
||||
|
||||
- `name` — программное имя роли (обязательно)
|
||||
- `synonym` — отображаемое имя (по умолчанию = name)
|
||||
- `comment` — комментарий (по умолчанию пусто)
|
||||
- Глобальные флаги — по умолчанию `false`, `true`, `false`
|
||||
|
||||
## Объекты: два формата
|
||||
|
||||
Массив `objects` принимает строки (shorthand) и объекты (полная форма).
|
||||
|
||||
### Строковый shorthand
|
||||
|
||||
```
|
||||
"ОбъектМетаданных: @пресет"
|
||||
"ОбъектМетаданных: Право1, Право2"
|
||||
```
|
||||
|
||||
Примеры:
|
||||
```json
|
||||
"objects": [
|
||||
"Catalog.Номенклатура: @view",
|
||||
"Document.Реализация: @edit",
|
||||
"InformationRegister.Цены: Read, Update",
|
||||
"DataProcessor.Загрузка: @view"
|
||||
]
|
||||
```
|
||||
|
||||
### Объектная форма (для RLS и переопределений)
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Document.Реализация",
|
||||
"preset": "view",
|
||||
"rights": { "Delete": false },
|
||||
"rls": { "Read": "#ДляОбъекта(\"\")" }
|
||||
}
|
||||
```
|
||||
|
||||
- `preset` — базовый набор прав (`"view"`, `"edit"`)
|
||||
- `rights` — переопределения: dict `{"Right": true/false}` или массив `["Right1", "Right2"]`
|
||||
- `rls` — RLS-ограничения: `{"ИмяПрава": "текст условия"}`
|
||||
|
||||
## Пресеты — подробные таблицы
|
||||
|
||||
Пресеты обозначаются `@` в строковом формате. В объектной форме ключ `preset` без `@`.
|
||||
|
||||
### `@view` — просмотр
|
||||
|
||||
| Тип объекта | Права |
|
||||
|-------------|-------|
|
||||
| Catalog, ExchangePlan, Document, ChartOfAccounts, ChartOfCharacteristicTypes, ChartOfCalculationTypes, BusinessProcess, Task | Read, View, InputByString |
|
||||
| InformationRegister, AccumulationRegister, AccountingRegister, CalculationRegister, Constant, DocumentJournal | Read, View |
|
||||
| Sequence | Read |
|
||||
| CommonForm, CommonCommand, Subsystem, FilterCriterion, CommonAttribute | View |
|
||||
| DataProcessor, Report | Use, View |
|
||||
| SessionParameter | Get |
|
||||
| Configuration | ThinClient, WebClient, Output, SaveUserData, MainWindowModeNormal |
|
||||
|
||||
### `@edit` — полное редактирование
|
||||
|
||||
| Тип объекта | Права |
|
||||
|-------------|-------|
|
||||
| Catalog, ExchangePlan, ChartOfAccounts, ChartOfCharacteristicTypes, ChartOfCalculationTypes | Read, Insert, Update, Delete, View, Edit, InputByString, InteractiveInsert, InteractiveSetDeletionMark, InteractiveClearDeletionMark |
|
||||
| Document | Read, Insert, Update, Delete, View, Edit, InputByString, Posting, UndoPosting, InteractiveInsert, InteractiveSetDeletionMark, InteractiveClearDeletionMark, InteractivePosting, InteractivePostingRegular, InteractiveUndoPosting, InteractiveChangeOfPosted |
|
||||
| BusinessProcess | Read, Insert, Update, Delete, View, Edit, InputByString, Start, InteractiveInsert, InteractiveSetDeletionMark, InteractiveClearDeletionMark, InteractiveActivate, InteractiveStart |
|
||||
| Task | Read, Insert, Update, Delete, View, Edit, InputByString, Execute, InteractiveInsert, InteractiveSetDeletionMark, InteractiveClearDeletionMark, InteractiveActivate, InteractiveExecute |
|
||||
| InformationRegister, AccumulationRegister, AccountingRegister, Constant | Read, Update, View, Edit |
|
||||
| DocumentJournal | Read, View |
|
||||
| Sequence | Read, Update |
|
||||
| SessionParameter | Get, Set |
|
||||
| CommonAttribute | View, Edit |
|
||||
|
||||
Для сервисов (WebService, HTTPService, IntegrationService) пресеты не определены — используй явные права: `"WebService.Имя: Use"`.
|
||||
|
||||
Если пресет не определён для типа объекта — предупреждение с подсказкой доступных.
|
||||
|
||||
## Русские синонимы
|
||||
|
||||
Скрипт автоматически транслирует русские имена в английские. Можно смешивать: `"Справочник.Контрагенты: Чтение, View"` — работает.
|
||||
|
||||
### Типы объектов
|
||||
|
||||
| Русский | English |
|
||||
|---------|---------|
|
||||
| `Справочник` | Catalog |
|
||||
| `Документ` | Document |
|
||||
| `РегистрСведений` | InformationRegister |
|
||||
| `РегистрНакопления` | AccumulationRegister |
|
||||
| `РегистрБухгалтерии` | AccountingRegister |
|
||||
| `РегистрРасчета` | CalculationRegister |
|
||||
| `Константа` | Constant |
|
||||
| `ПланСчетов` | ChartOfAccounts |
|
||||
| `ПланВидовХарактеристик` | ChartOfCharacteristicTypes |
|
||||
| `ПланВидовРасчета` | ChartOfCalculationTypes |
|
||||
| `ПланОбмена` | ExchangePlan |
|
||||
| `БизнесПроцесс` | BusinessProcess |
|
||||
| `Задача` | Task |
|
||||
| `Обработка` | DataProcessor |
|
||||
| `Отчет` | Report |
|
||||
| `ОбщаяФорма` | CommonForm |
|
||||
| `ОбщаяКоманда` | CommonCommand |
|
||||
| `Подсистема` | Subsystem |
|
||||
| `КритерийОтбора` | FilterCriterion |
|
||||
| `ЖурналДокументов` | DocumentJournal |
|
||||
| `Последовательность` | Sequence |
|
||||
| `ВебСервис` | WebService |
|
||||
| `HTTPСервис` | HTTPService |
|
||||
| `СервисИнтеграции` | IntegrationService |
|
||||
| `ПараметрСеанса` | SessionParameter |
|
||||
| `ОбщийРеквизит` | CommonAttribute |
|
||||
| `Конфигурация` | Configuration |
|
||||
| `Перечисление` | Enum |
|
||||
|
||||
### Вложенные типы
|
||||
|
||||
| Русский | English |
|
||||
|---------|---------|
|
||||
| `Реквизит` | Attribute |
|
||||
| `СтандартныйРеквизит` | StandardAttribute |
|
||||
| `ТабличнаяЧасть` | TabularSection |
|
||||
| `Измерение` | Dimension |
|
||||
| `Ресурс` | Resource |
|
||||
| `Команда` | Command |
|
||||
| `РеквизитАдресации` | AddressingAttribute |
|
||||
|
||||
### Права (основные)
|
||||
|
||||
| Русский | English |
|
||||
|---------|---------|
|
||||
| `Чтение` | Read |
|
||||
| `Добавление` | Insert |
|
||||
| `Изменение` | Update |
|
||||
| `Удаление` | Delete |
|
||||
| `Просмотр` | View |
|
||||
| `Редактирование` | Edit |
|
||||
| `ВводПоСтроке` | InputByString |
|
||||
| `Проведение` | Posting |
|
||||
| `ОтменаПроведения` | UndoPosting |
|
||||
| `Использование` | Use |
|
||||
| `Получение` | Get |
|
||||
| `Установка` | Set |
|
||||
| `Старт` | Start |
|
||||
| `Выполнение` | Execute |
|
||||
| `УправлениеИтогами` | TotalsControl |
|
||||
|
||||
### Права (интерактивные)
|
||||
|
||||
| Русский | English |
|
||||
|---------|---------|
|
||||
| `ИнтерактивноеДобавление` | InteractiveInsert |
|
||||
| `ИнтерактивнаяПометкаУдаления` | InteractiveSetDeletionMark |
|
||||
| `ИнтерактивноеСнятиеПометкиУдаления` | InteractiveClearDeletionMark |
|
||||
| `ИнтерактивноеУдаление` | InteractiveDelete |
|
||||
| `ИнтерактивноеУдалениеПомеченных` | InteractiveDeleteMarked |
|
||||
| `ИнтерактивноеПроведение` | InteractivePosting |
|
||||
| `ИнтерактивноеПроведениеНеоперативное` | InteractivePostingRegular |
|
||||
| `ИнтерактивнаяОтменаПроведения` | InteractiveUndoPosting |
|
||||
| `ИнтерактивноеИзменениеПроведенных` | InteractiveChangeOfPosted |
|
||||
| `ИнтерактивныйСтарт` | InteractiveStart |
|
||||
| `ИнтерактивнаяАктивация` | InteractiveActivate |
|
||||
| `ИнтерактивноеВыполнение` | InteractiveExecute |
|
||||
|
||||
### Права (конфигурация)
|
||||
|
||||
| Русский | English |
|
||||
|---------|---------|
|
||||
| `Администрирование` | Administration |
|
||||
| `АдминистрированиеДанных` | DataAdministration |
|
||||
| `ТонкийКлиент` | ThinClient |
|
||||
| `ТолстыйКлиент` | ThickClient |
|
||||
| `ВебКлиент` | WebClient |
|
||||
| `МобильныйКлиент` | MobileClient |
|
||||
| `ВнешнееСоединение` | ExternalConnection |
|
||||
| `Вывод` | Output |
|
||||
| `СохранениеДанныхПользователя` | SaveUserData |
|
||||
|
||||
## Типы объектов без прав в ролях
|
||||
|
||||
Следующие типы 1С **не могут** иметь права в ролях (не добавляются в `objects`):
|
||||
|
||||
| Тип | Причина |
|
||||
|-----|---------|
|
||||
| Enum (Перечисление) | Права наследуются от конфигурации, явное назначение невозможно |
|
||||
| CommonModule (ОбщийМодуль) | Не имеет собственных прав в роли |
|
||||
| DefinedType (ОпределяемыйТип) | Тип данных, не объект прав |
|
||||
| CommonPicture (ОбщаяКартинка) | Ресурс, не объект прав |
|
||||
| CommonTemplate (ОбщийМакет) | Ресурс, не объект прав |
|
||||
| Language (Язык) | Конфигурационный элемент |
|
||||
| FunctionalOption (ФункциональнаяОпция) | Не объект прав |
|
||||
| FunctionalOptionsParameter | Не объект прав |
|
||||
| EventSubscription (ПодпискаНаСобытие) | Не объект прав |
|
||||
| ScheduledJob (РегламентноеЗадание) | Не объект прав |
|
||||
| StyleItem (ЭлементСтиля) | Ресурс оформления |
|
||||
|
||||
## Шаблоны ограничений (RLS templates)
|
||||
|
||||
```json
|
||||
"templates": [
|
||||
{
|
||||
"name": "ДляОбъекта(Модификатор)",
|
||||
"condition": "// текст шаблона\nГДЕ 1=1\n&Модификатор"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
- `&` в условии автоматически экранируется в `&` в XML
|
||||
- Ссылка на шаблон в `rls`: `"#ИмяШаблона(\"параметры\")"` — начинается с `#`
|
||||
- Параметры шаблона можно передавать пустыми: `#ДляОбъекта("")`
|
||||
|
||||
## Примеры
|
||||
|
||||
### 1. Простая роль (только пресеты)
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ЧтениеНоменклатуры",
|
||||
"synonym": "Чтение номенклатуры",
|
||||
"objects": [
|
||||
"Catalog.Номенклатура: @view",
|
||||
"Catalog.Контрагенты: @view",
|
||||
"DataProcessor.Загрузка: @view"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Роль для регламентного задания
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ОбновлениеЦен",
|
||||
"synonym": "Обновление цен номенклатуры",
|
||||
"objects": [
|
||||
"Catalog.Номенклатура: Read",
|
||||
"Catalog.Валюты: Read",
|
||||
"InformationRegister.ЦеныНоменклатуры: Read, Update",
|
||||
"Constant.ОсновнаяВалюта: Read"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Роль с RLS
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ЧтениеДокументовПоОрганизации",
|
||||
"synonym": "Чтение документов (ограничение по организации)",
|
||||
"objects": [
|
||||
"Catalog.Организации: @view",
|
||||
{
|
||||
"name": "Document.РеализацияТоваровУслуг",
|
||||
"preset": "view",
|
||||
"rls": {
|
||||
"Read": "#ДляОбъекта(\"\")"
|
||||
}
|
||||
}
|
||||
],
|
||||
"templates": [
|
||||
{
|
||||
"name": "ДляОбъекта(Модификатор)",
|
||||
"condition": "ГДЕ Организация = &ТекущаяОрганизация"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Роль с русскими синонимами
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ПросмотрДанных",
|
||||
"synonym": "Просмотр данных",
|
||||
"objects": [
|
||||
"Справочник.Контрагенты: @view",
|
||||
"Документ.Реализация: Чтение, Просмотр",
|
||||
"РегистрСведений.Цены: @edit",
|
||||
"Обработка.ЗагрузкаДанных: @view"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Роль с переопределением прав из пресета
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "ОграниченноеРедактирование",
|
||||
"synonym": "Редактирование без удаления",
|
||||
"objects": [
|
||||
{
|
||||
"name": "Catalog.Контрагенты",
|
||||
"preset": "edit",
|
||||
"rights": { "Delete": false }
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -1,886 +0,0 @@
|
||||
# role-compile v1.10 — Compile 1C role from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$JsonPath,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
[string]$OutputDir
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Support guard (Ext/ParentConfigurations.bin) ---
|
||||
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
|
||||
# read-only configs unless allowed. Trigger = bin present; reaction from
|
||||
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
|
||||
# throws — guard errors degrade to allow.
|
||||
function Get-RootUuid([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $null }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
|
||||
} catch {}
|
||||
return $null
|
||||
}
|
||||
function Test-ExternalObjectRoot([string]$xmlPath) {
|
||||
if (-not (Test-Path $xmlPath)) { return $false }
|
||||
try {
|
||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
||||
$el = $mx.DocumentElement.FirstChild
|
||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
||||
} catch {}
|
||||
return $false
|
||||
}
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Get-EditMode([string]$cfgDir) {
|
||||
try {
|
||||
$pj = Find-V8Project (Get-Location).Path
|
||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
||||
if (-not $pj) { return 'deny' }
|
||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
||||
if ($proj.databases) {
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($db.configSrc) {
|
||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
||||
return 'deny'
|
||||
} catch { return 'deny' }
|
||||
}
|
||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
||||
try {
|
||||
$rp = $targetPath
|
||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if (Test-ExternalObjectRoot $rp) { return }
|
||||
$elemUuid = Get-RootUuid $rp
|
||||
$cfgDir = $null; $binPath = $null
|
||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
||||
if (-not $cfgDir) {
|
||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
||||
}
|
||||
if ($elemUuid -and $cfgDir) { break }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
# New object (no element file): fall back to config root uuid.
|
||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
||||
if ($bytes.Length -le 32) { return }
|
||||
$start = 0
|
||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
||||
if (-not $hm.Success) { return }
|
||||
$G = [int]$hm.Groups[1].Value
|
||||
$K = [int]$hm.Groups[2].Value
|
||||
if ($K -eq 0) { return }
|
||||
$best = $null
|
||||
if ($elemUuid) {
|
||||
$u = [regex]::Escape($elemUuid.ToLower())
|
||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
||||
$f1 = [int]$m.Groups[1].Value
|
||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
||||
}
|
||||
}
|
||||
$blocked = $false; $code = ""; $reason = ""
|
||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
||||
elseif ($require -eq 'removed') {
|
||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
||||
}
|
||||
else {
|
||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
||||
}
|
||||
if (-not $blocked) { return }
|
||||
$mode = Get-EditMode $cfgDir
|
||||
if ($mode -eq 'off') { return }
|
||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
||||
# latter throws and would be swallowed by this function's own catch.
|
||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if ($code -eq "capability-off") {
|
||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
} elseif ($code -eq "not-removed") {
|
||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
||||
} else {
|
||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
||||
}
|
||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
||||
exit 1
|
||||
} catch { return }
|
||||
}
|
||||
|
||||
# --- 1. Load and validate JSON ---
|
||||
|
||||
if (-not (Test-Path $JsonPath)) {
|
||||
Write-Error "File not found: $JsonPath"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$json = Get-Content -Raw -Encoding UTF8 $JsonPath
|
||||
$def = $json | ConvertFrom-Json
|
||||
|
||||
if (-not $def.name) {
|
||||
Write-Error "JSON must have 'name' field (role programmatic name)"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$roleName = "$($def.name)"
|
||||
$synonym = if ($def.synonym) { "$($def.synonym)" } else { $roleName }
|
||||
$comment = if ($def.comment) { "$($def.comment)" } else { "" }
|
||||
|
||||
# --- 2. XML helpers ---
|
||||
|
||||
$script:xmlBuf = $null
|
||||
|
||||
function X {
|
||||
param([string]$text)
|
||||
$script:xmlBuf.AppendLine($text) | Out-Null
|
||||
}
|
||||
|
||||
function Esc-Xml {
|
||||
# Экранирование ТЕКСТА элемента: только & < > . Кавычки в тексте платформа НЕ экранирует —
|
||||
# пишет литерально (проверено: 92142 сырых кавычки на корпус, ни одной "). " платформа
|
||||
# принимает, но при выгрузке нормализует обратно в кавычку → лишний шум в роундтрипе.
|
||||
param([string]$s)
|
||||
return $s.Replace('&','&').Replace('<','<').Replace('>','>')
|
||||
}
|
||||
|
||||
# --- 3. Russian synonyms → canonical English names ---
|
||||
|
||||
$script:typeAliases = @{
|
||||
"Справочник" = "Catalog"
|
||||
"Документ" = "Document"
|
||||
"РегистрСведений" = "InformationRegister"
|
||||
"РегистрНакопления" = "AccumulationRegister"
|
||||
"РегистрБухгалтерии" = "AccountingRegister"
|
||||
"РегистрРасчета" = "CalculationRegister"
|
||||
"Константа" = "Constant"
|
||||
"ПланСчетов" = "ChartOfAccounts"
|
||||
"ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
|
||||
"ПланВидовРасчета" = "ChartOfCalculationTypes"
|
||||
"ПланОбмена" = "ExchangePlan"
|
||||
"БизнесПроцесс" = "BusinessProcess"
|
||||
"Задача" = "Task"
|
||||
"Обработка" = "DataProcessor"
|
||||
"Отчет" = "Report"
|
||||
"ОбщаяФорма" = "CommonForm"
|
||||
"ОбщаяКоманда" = "CommonCommand"
|
||||
"Подсистема" = "Subsystem"
|
||||
"КритерийОтбора" = "FilterCriterion"
|
||||
"ЖурналДокументов" = "DocumentJournal"
|
||||
"Последовательность" = "Sequence"
|
||||
"ВебСервис" = "WebService"
|
||||
"HTTPСервис" = "HTTPService"
|
||||
"СервисИнтеграции" = "IntegrationService"
|
||||
"ПараметрСеанса" = "SessionParameter"
|
||||
"ОбщийРеквизит" = "CommonAttribute"
|
||||
"Конфигурация" = "Configuration"
|
||||
"Перечисление" = "Enum"
|
||||
# Nested
|
||||
"Реквизит" = "Attribute"
|
||||
"СтандартныйРеквизит" = "StandardAttribute"
|
||||
"ТабличнаяЧасть" = "TabularSection"
|
||||
"Измерение" = "Dimension"
|
||||
"Ресурс" = "Resource"
|
||||
"Команда" = "Command"
|
||||
"РеквизитАдресации" = "AddressingAttribute"
|
||||
}
|
||||
|
||||
$script:rightAliases = @{
|
||||
"Чтение" = "Read"
|
||||
"Добавление" = "Insert"
|
||||
"Изменение" = "Update"
|
||||
"Удаление" = "Delete"
|
||||
"Просмотр" = "View"
|
||||
"Редактирование" = "Edit"
|
||||
"ВводПоСтроке" = "InputByString"
|
||||
"Проведение" = "Posting"
|
||||
"ОтменаПроведения" = "UndoPosting"
|
||||
"ИнтерактивноеДобавление" = "InteractiveInsert"
|
||||
"ИнтерактивнаяПометкаУдаления" = "InteractiveSetDeletionMark"
|
||||
"ИнтерактивноеСнятиеПометкиУдаления" = "InteractiveClearDeletionMark"
|
||||
"ИнтерактивноеУдаление" = "InteractiveDelete"
|
||||
"ИнтерактивноеУдалениеПомеченных" = "InteractiveDeleteMarked"
|
||||
"ИнтерактивноеПроведение" = "InteractivePosting"
|
||||
"ИнтерактивноеПроведениеНеоперативное" = "InteractivePostingRegular"
|
||||
"ИнтерактивнаяОтменаПроведения" = "InteractiveUndoPosting"
|
||||
"ИнтерактивноеИзменениеПроведенных" = "InteractiveChangeOfPosted"
|
||||
"Использование" = "Use"
|
||||
"Получение" = "Get"
|
||||
"Установка" = "Set"
|
||||
"Старт" = "Start"
|
||||
"ИнтерактивныйСтарт" = "InteractiveStart"
|
||||
"ИнтерактивнаяАктивация" = "InteractiveActivate"
|
||||
"Выполнение" = "Execute"
|
||||
"ИнтерактивноеВыполнение" = "InteractiveExecute"
|
||||
"УправлениеИтогами" = "TotalsControl"
|
||||
"Администрирование" = "Administration"
|
||||
"АдминистрированиеДанных" = "DataAdministration"
|
||||
"ТонкийКлиент" = "ThinClient"
|
||||
"ВебКлиент" = "WebClient"
|
||||
"ТолстыйКлиент" = "ThickClient"
|
||||
"ВнешнееСоединение" = "ExternalConnection"
|
||||
"Вывод" = "Output"
|
||||
"СохранениеДанныхПользователя" = "SaveUserData"
|
||||
"МобильныйКлиент" = "MobileClient"
|
||||
}
|
||||
|
||||
# Translate Russian object name to English (e.g. "Справочник.Контрагенты" → "Catalog.Контрагенты")
|
||||
function Translate-ObjectName {
|
||||
param([string]$name)
|
||||
$parts = $name.Split(".")
|
||||
$result = @()
|
||||
foreach ($p in $parts) {
|
||||
if ($script:typeAliases.ContainsKey($p)) {
|
||||
$result += $script:typeAliases[$p]
|
||||
} else {
|
||||
$result += $p
|
||||
}
|
||||
}
|
||||
return $result -join "."
|
||||
}
|
||||
|
||||
# Translate Russian right name to English (e.g. "Чтение" → "Read")
|
||||
function Translate-RightName {
|
||||
param([string]$name)
|
||||
if ($script:rightAliases.ContainsKey($name)) {
|
||||
return $script:rightAliases[$name]
|
||||
}
|
||||
return $name
|
||||
}
|
||||
|
||||
# --- 4. Known rights per object type (source: docs/1c-role-spec.md) ---
|
||||
|
||||
$script:knownRights = @{
|
||||
"Configuration" = @(
|
||||
"Administration","DataAdministration","UpdateDataBaseConfiguration",
|
||||
"ConfigurationExtensionsAdministration","ActiveUsers","EventLog","ExclusiveMode",
|
||||
"ThinClient","ThickClient","WebClient","MobileClient","ExternalConnection",
|
||||
"Automation","Output","SaveUserData","TechnicalSpecialistMode",
|
||||
"InteractiveOpenExtDataProcessors","InteractiveOpenExtReports",
|
||||
"AnalyticsSystemClient","CollaborationSystemInfoBaseRegistration",
|
||||
"MainWindowModeNormal","MainWindowModeWorkplace",
|
||||
"MainWindowModeEmbeddedWorkplace","MainWindowModeFullscreenWorkplace","MainWindowModeKiosk"
|
||||
)
|
||||
"Catalog" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveDeleteMarked",
|
||||
"InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"Document" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"Posting","UndoPosting",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveDeleteMarked",
|
||||
"InteractivePosting","InteractivePostingRegular","InteractiveUndoPosting",
|
||||
"InteractiveChangeOfPosted",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"InformationRegister" = @(
|
||||
"Read","Update","View","Edit","TotalsControl",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"AccumulationRegister" = @("Read","Update","View","Edit","TotalsControl")
|
||||
"AccountingRegister" = @("Read","Update","View","Edit","TotalsControl")
|
||||
"CalculationRegister" = @("Read","View")
|
||||
"Constant" = @(
|
||||
"Read","Update","View","Edit",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"ChartOfAccounts" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete",
|
||||
"InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory","ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistory","UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment"
|
||||
)
|
||||
"ChartOfCharacteristicTypes" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveDeleteMarked",
|
||||
"InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"ReadDataHistoryOfMissingData","UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"ChartOfCalculationTypes" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete",
|
||||
"InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData"
|
||||
)
|
||||
"ExchangePlan" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveDeleteMarked",
|
||||
"ReadDataHistory","ViewDataHistory","UpdateDataHistory",
|
||||
"ReadDataHistoryOfMissingData","UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
|
||||
)
|
||||
"BusinessProcess" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"Start","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveActivate","InteractiveStart"
|
||||
)
|
||||
"Task" = @(
|
||||
"Read","Insert","Update","Delete","View","Edit","InputByString",
|
||||
"Execute","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
|
||||
"InteractiveDelete","InteractiveActivate","InteractiveExecute"
|
||||
)
|
||||
"DataProcessor" = @("Use","View")
|
||||
"Report" = @("Use","View")
|
||||
"CommonForm" = @("View")
|
||||
"CommonCommand" = @("View")
|
||||
"Subsystem" = @("View")
|
||||
"FilterCriterion" = @("View")
|
||||
"DocumentJournal" = @("Read","View")
|
||||
"Sequence" = @("Read","Update")
|
||||
"WebService" = @("Use")
|
||||
"HTTPService" = @("Use")
|
||||
"IntegrationService" = @("Use")
|
||||
"SessionParameter" = @("Get","Set")
|
||||
"CommonAttribute" = @("View","Edit")
|
||||
}
|
||||
|
||||
# Nested objects: Attribute, StandardAttribute, TabularSection, Dimension, Resource, AddressingAttribute
|
||||
$script:nestedRights = @("View","Edit")
|
||||
$script:commandRights = @("View")
|
||||
|
||||
# --- 4. Presets (@view, @edit) ---
|
||||
|
||||
$script:presets = @{
|
||||
"view" = @{
|
||||
"Catalog" = @("Read","View","InputByString")
|
||||
"ExchangePlan" = @("Read","View","InputByString")
|
||||
"Document" = @("Read","View","InputByString")
|
||||
"ChartOfAccounts" = @("Read","View","InputByString")
|
||||
"ChartOfCharacteristicTypes" = @("Read","View","InputByString")
|
||||
"ChartOfCalculationTypes" = @("Read","View","InputByString")
|
||||
"BusinessProcess" = @("Read","View","InputByString")
|
||||
"Task" = @("Read","View","InputByString")
|
||||
"InformationRegister" = @("Read","View")
|
||||
"AccumulationRegister" = @("Read","View")
|
||||
"AccountingRegister" = @("Read","View")
|
||||
"CalculationRegister" = @("Read","View")
|
||||
"Constant" = @("Read","View")
|
||||
"DocumentJournal" = @("Read","View")
|
||||
"Sequence" = @("Read")
|
||||
"CommonForm" = @("View")
|
||||
"CommonCommand" = @("View")
|
||||
"Subsystem" = @("View")
|
||||
"FilterCriterion" = @("View")
|
||||
"SessionParameter" = @("Get")
|
||||
"CommonAttribute" = @("View")
|
||||
"DataProcessor" = @("Use","View")
|
||||
"Report" = @("Use","View")
|
||||
"Configuration" = @("ThinClient","WebClient","Output","SaveUserData","MainWindowModeNormal")
|
||||
}
|
||||
"edit" = @{
|
||||
"Catalog" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
|
||||
"ExchangePlan" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
|
||||
"Document" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Posting","UndoPosting","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractivePosting","InteractivePostingRegular","InteractiveUndoPosting","InteractiveChangeOfPosted")
|
||||
"ChartOfAccounts" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
|
||||
"ChartOfCharacteristicTypes" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
|
||||
"ChartOfCalculationTypes" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
|
||||
"BusinessProcess" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Start","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractiveActivate","InteractiveStart")
|
||||
"Task" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Execute","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractiveActivate","InteractiveExecute")
|
||||
"InformationRegister" = @("Read","Update","View","Edit")
|
||||
"AccumulationRegister" = @("Read","Update","View","Edit")
|
||||
"AccountingRegister" = @("Read","Update","View","Edit")
|
||||
"Constant" = @("Read","Update","View","Edit")
|
||||
"DocumentJournal" = @("Read","View")
|
||||
"Sequence" = @("Read","Update")
|
||||
"SessionParameter" = @("Get","Set")
|
||||
"CommonAttribute" = @("View","Edit")
|
||||
}
|
||||
}
|
||||
|
||||
# --- 5. Helpers ---
|
||||
|
||||
function Get-ObjectType {
|
||||
param([string]$objectName)
|
||||
$dotIdx = $objectName.IndexOf(".")
|
||||
if ($dotIdx -lt 0) { return $objectName }
|
||||
return $objectName.Substring(0, $dotIdx)
|
||||
}
|
||||
|
||||
function Is-NestedObject {
|
||||
param([string]$objectName)
|
||||
return ($objectName.Split(".").Count -ge 3)
|
||||
}
|
||||
|
||||
function Resolve-Preset {
|
||||
param([string]$objectType, [string]$presetName)
|
||||
|
||||
$preset = $presetName.TrimStart('@')
|
||||
|
||||
if (-not $script:presets.ContainsKey($preset)) {
|
||||
Write-Warning "Unknown preset '@$preset'. Known: @view, @edit"
|
||||
return @()
|
||||
}
|
||||
|
||||
$typeMap = $script:presets[$preset]
|
||||
if (-not $typeMap.ContainsKey($objectType)) {
|
||||
$available = @()
|
||||
foreach ($k in $script:presets.Keys) {
|
||||
if ($script:presets[$k].ContainsKey($objectType)) {
|
||||
$available += "@$k"
|
||||
}
|
||||
}
|
||||
$availStr = if ($available.Count -gt 0) { $available -join ", " } else { "none" }
|
||||
Write-Warning "Preset '@$preset' not defined for type '$objectType'. Available: $availStr"
|
||||
return @()
|
||||
}
|
||||
|
||||
return @($typeMap[$objectType])
|
||||
}
|
||||
|
||||
function Validate-RightName {
|
||||
param([string]$objectName, [string]$rightName)
|
||||
|
||||
$objectType = Get-ObjectType $objectName
|
||||
|
||||
if (Is-NestedObject $objectName) {
|
||||
if ($objectName -match '\.Command\.') {
|
||||
if ($rightName -notin $script:commandRights) {
|
||||
Write-Warning "${objectName}: '$rightName' not valid for commands (only: View)"
|
||||
return $false
|
||||
}
|
||||
} else {
|
||||
if ($rightName -notin $script:nestedRights) {
|
||||
Write-Warning "${objectName}: '$rightName' not valid for nested objects (only: View, Edit)"
|
||||
return $false
|
||||
}
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
if (-not $script:knownRights.ContainsKey($objectType)) {
|
||||
Write-Warning "${objectName}: unknown object type '$objectType'"
|
||||
return $true
|
||||
}
|
||||
|
||||
$validRights = $script:knownRights[$objectType]
|
||||
if ($rightName -notin $validRights) {
|
||||
$suggestions = @($validRights | Where-Object {
|
||||
$_ -like "*$rightName*" -or $rightName -like "*$_*"
|
||||
})
|
||||
$sugStr = if ($suggestions.Count -gt 0) { " Did you mean: $($suggestions -join ', ')?" } else { "" }
|
||||
Write-Warning "${objectName}: unknown right '$rightName'.$sugStr"
|
||||
return $false
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
# --- 6. Parse object entries ---
|
||||
|
||||
function Parse-ObjectEntry {
|
||||
param($entry)
|
||||
|
||||
# --- String shorthand ---
|
||||
if ($entry -is [string]) {
|
||||
$colonIdx = $entry.IndexOf(':')
|
||||
if ($colonIdx -lt 0) {
|
||||
Write-Warning "Invalid string '$entry' -- expected 'Object.Name: @preset' or 'Object.Name: Right1, Right2'"
|
||||
return $null
|
||||
}
|
||||
$objName = Translate-ObjectName ($entry.Substring(0, $colonIdx).Trim())
|
||||
$rightsStr = $entry.Substring($colonIdx + 1).Trim()
|
||||
$objectType = Get-ObjectType $objName
|
||||
|
||||
if ($rightsStr.StartsWith('@')) {
|
||||
$rightNames = @(Resolve-Preset -objectType $objectType -presetName $rightsStr)
|
||||
} else {
|
||||
$rightNames = @($rightsStr -split ',\s*' | ForEach-Object { Translate-RightName $_.Trim() } | Where-Object { $_ })
|
||||
foreach ($r in $rightNames) {
|
||||
Validate-RightName -objectName $objName -rightName $r | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
$rights = @()
|
||||
foreach ($r in $rightNames) {
|
||||
$rights += ,@{Name=$r; Value="true"; Condition=$null}
|
||||
}
|
||||
return @{ Name = $objName; Rights = $rights }
|
||||
}
|
||||
|
||||
# --- Object form ---
|
||||
$objName = Translate-ObjectName "$($entry.name)"
|
||||
if (-not $objName) {
|
||||
Write-Warning "Object entry missing 'name' field"
|
||||
return $null
|
||||
}
|
||||
|
||||
$objectType = Get-ObjectType $objName
|
||||
$rightsMap = [ordered]@{}
|
||||
|
||||
# 1) Start with preset
|
||||
if ($entry.preset) {
|
||||
$presetRights = @(Resolve-Preset -objectType $objectType -presetName "$($entry.preset)")
|
||||
foreach ($r in $presetRights) {
|
||||
$rightsMap[$r] = @{Value="true"; Condition=$null}
|
||||
}
|
||||
}
|
||||
|
||||
# 2) Apply explicit rights
|
||||
if ($entry.rights) {
|
||||
if ($entry.rights -is [array]) {
|
||||
foreach ($r in $entry.rights) {
|
||||
$rName = Translate-RightName "$r"
|
||||
Validate-RightName -objectName $objName -rightName $rName | Out-Null
|
||||
$rightsMap[$rName] = @{Value="true"; Condition=$null}
|
||||
}
|
||||
} else {
|
||||
foreach ($p in $entry.rights.PSObject.Properties) {
|
||||
$rName = Translate-RightName $p.Name
|
||||
Validate-RightName -objectName $objName -rightName $rName | Out-Null
|
||||
$boolVal = $p.Value
|
||||
if ($boolVal -eq $true -or "$boolVal" -eq "True") {
|
||||
$rightsMap[$rName] = @{Value="true"; Condition=$null}
|
||||
} else {
|
||||
$rightsMap[$rName] = @{Value="false"; Condition=$null}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 3) Apply RLS conditions
|
||||
if ($entry.rls) {
|
||||
foreach ($p in $entry.rls.PSObject.Properties) {
|
||||
$rlsRight = Translate-RightName $p.Name
|
||||
if ($rightsMap.Contains($rlsRight)) {
|
||||
$rightsMap[$rlsRight].Condition = "$($p.Value)"
|
||||
} else {
|
||||
Write-Warning "${objName}: RLS for '$rlsRight' but this right is not in the rights list"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Convert to array
|
||||
$rights = @()
|
||||
foreach ($k in $rightsMap.Keys) {
|
||||
$rights += ,@{
|
||||
Name = $k
|
||||
Value = $rightsMap[$k].Value
|
||||
Condition = $rightsMap[$k].Condition
|
||||
}
|
||||
}
|
||||
|
||||
return @{ Name = $objName; Rights = $rights }
|
||||
}
|
||||
|
||||
# --- 7. Parse all object entries ---
|
||||
|
||||
# Synonym: accept "rights" as alias for "objects"
|
||||
if (-not $def.objects -and $def.rights) { $def | Add-Member -NotePropertyName objects -NotePropertyValue $def.rights }
|
||||
|
||||
$parsedObjects = @()
|
||||
if ($def.objects) {
|
||||
foreach ($entry in $def.objects) {
|
||||
$parsed = Parse-ObjectEntry -entry $entry
|
||||
if ($parsed) {
|
||||
$parsedObjects += ,$parsed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- Detect format version ---
|
||||
|
||||
function Detect-FormatVersion([string]$dir) {
|
||||
$d = $dir
|
||||
while ($d) {
|
||||
$cfgPath = Join-Path $d "Configuration.xml"
|
||||
if (Test-Path $cfgPath) {
|
||||
$cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
|
||||
# Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
|
||||
# СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
|
||||
$head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
|
||||
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
|
||||
}
|
||||
$parent = Split-Path $d -Parent
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return "2.17"
|
||||
}
|
||||
|
||||
$resolvedOutputDir = if ([System.IO.Path]::IsPathRooted($OutputDir)) { $OutputDir } else { Join-Path (Get-Location) $OutputDir }
|
||||
Assert-EditAllowed $resolvedOutputDir 'editable'
|
||||
$formatVersion = Detect-FormatVersion $resolvedOutputDir
|
||||
|
||||
# --- 8. Generate UUID ---
|
||||
|
||||
$uuid = [guid]::NewGuid().ToString()
|
||||
|
||||
# --- 9. Emit metadata XML (Roles/Name.xml) ---
|
||||
|
||||
$script:xmlBuf = New-Object System.Text.StringBuilder 4096
|
||||
|
||||
X '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
X '<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses"'
|
||||
X ' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
|
||||
X ' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
|
||||
X ' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"'
|
||||
X ' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
|
||||
X ' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
|
||||
X ' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
|
||||
X ' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
|
||||
X ' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
|
||||
X ' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
|
||||
X ' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
|
||||
X ' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
|
||||
X ' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"'
|
||||
X ' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"'
|
||||
X ' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
||||
X ' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||
X ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
X " version=`"$formatVersion`">"
|
||||
X " <Role uuid=`"$uuid`">"
|
||||
X ' <Properties>'
|
||||
X " <Name>$roleName</Name>"
|
||||
X ' <Synonym>'
|
||||
X ' <v8:item>'
|
||||
X ' <v8:lang>ru</v8:lang>'
|
||||
X " <v8:content>$(Esc-Xml $synonym)</v8:content>"
|
||||
X ' </v8:item>'
|
||||
X ' </Synonym>'
|
||||
if ($comment) {
|
||||
X " <Comment>$(Esc-Xml $comment)</Comment>"
|
||||
} else {
|
||||
X ' <Comment/>'
|
||||
}
|
||||
X ' </Properties>'
|
||||
X ' </Role>'
|
||||
X '</MetaDataObject>'
|
||||
|
||||
$metadataXml = $script:xmlBuf.ToString()
|
||||
|
||||
# --- 10. Emit Rights XML (Roles/Name/Ext/Rights.xml) ---
|
||||
|
||||
$script:xmlBuf = New-Object System.Text.StringBuilder 8192
|
||||
|
||||
X '<?xml version="1.0" encoding="UTF-8"?>'
|
||||
X '<Rights xmlns="http://v8.1c.ru/8.2/roles"'
|
||||
X ' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||
X ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
X " xsi:type=`"Rights`" version=`"$formatVersion`">"
|
||||
|
||||
# Global flags (defaults match typical 1C roles)
|
||||
$sfno = if ($null -ne $def.setForNewObjects) { "$($def.setForNewObjects)".ToLower() } else { "false" }
|
||||
$sfab = if ($null -ne $def.setForAttributesByDefault) { "$($def.setForAttributesByDefault)".ToLower() } else { "true" }
|
||||
$irco = if ($null -ne $def.independentRightsOfChildObjects) { "$($def.independentRightsOfChildObjects)".ToLower() } else { "false" }
|
||||
|
||||
X " <setForNewObjects>$sfno</setForNewObjects>"
|
||||
X " <setForAttributesByDefault>$sfab</setForAttributesByDefault>"
|
||||
X " <independentRightsOfChildObjects>$irco</independentRightsOfChildObjects>"
|
||||
|
||||
# Object blocks
|
||||
$totalRights = 0
|
||||
foreach ($obj in $parsedObjects) {
|
||||
X ' <object>'
|
||||
X " <name>$($obj.Name)</name>"
|
||||
foreach ($right in $obj.Rights) {
|
||||
X ' <right>'
|
||||
X " <name>$($right.Name)</name>"
|
||||
X " <value>$($right.Value)</value>"
|
||||
if ($right.Condition) {
|
||||
X ' <restrictionByCondition>'
|
||||
X " <condition>$(Esc-Xml $right.Condition)</condition>"
|
||||
X ' </restrictionByCondition>'
|
||||
}
|
||||
X ' </right>'
|
||||
$totalRights++
|
||||
}
|
||||
X ' </object>'
|
||||
}
|
||||
|
||||
# RLS restriction templates
|
||||
$templateCount = 0
|
||||
if ($def.templates) {
|
||||
foreach ($tpl in $def.templates) {
|
||||
X ' <restrictionTemplate>'
|
||||
X " <name>$(Esc-Xml "$($tpl.name)")</name>"
|
||||
X " <condition>$(Esc-Xml "$($tpl.condition)")</condition>"
|
||||
X ' </restrictionTemplate>'
|
||||
$templateCount++
|
||||
}
|
||||
}
|
||||
|
||||
X '</Rights>'
|
||||
|
||||
$rightsXml = $script:xmlBuf.ToString()
|
||||
|
||||
# --- 11. Write output files ---
|
||||
|
||||
$outDir = if ([System.IO.Path]::IsPathRooted($OutputDir)) {
|
||||
$OutputDir
|
||||
} else {
|
||||
Join-Path (Get-Location) $OutputDir
|
||||
}
|
||||
|
||||
# Determine Roles dir and config root
|
||||
# Back-compat: if OutputDir leaf is "Roles", use as-is; otherwise treat as config root
|
||||
$leaf = Split-Path $outDir -Leaf
|
||||
if ($leaf -eq "Roles") {
|
||||
$rolesDir = $outDir
|
||||
$configDir = Split-Path $outDir -Parent
|
||||
} else {
|
||||
$rolesDir = Join-Path $outDir "Roles"
|
||||
$configDir = $outDir
|
||||
}
|
||||
|
||||
# Metadata: Roles/RoleName.xml
|
||||
$metadataPath = Join-Path $rolesDir "$roleName.xml"
|
||||
if (-not (Test-Path $rolesDir)) {
|
||||
New-Item -ItemType Directory -Path $rolesDir -Force | Out-Null
|
||||
}
|
||||
|
||||
# Rights: Roles/RoleName/Ext/Rights.xml
|
||||
$roleSubDir = Join-Path $rolesDir $roleName
|
||||
$extDir = Join-Path $roleSubDir "Ext"
|
||||
$rightsPath = Join-Path $extDir "Rights.xml"
|
||||
if (-not (Test-Path $extDir)) {
|
||||
New-Item -ItemType Directory -Path $extDir -Force | Out-Null
|
||||
}
|
||||
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText($metadataPath, $metadataXml, $enc)
|
||||
[System.IO.File]::WriteAllText($rightsPath, $rightsXml, $enc)
|
||||
|
||||
# --- 12. Register in Configuration.xml ---
|
||||
|
||||
$configXmlPath = Join-Path $configDir "Configuration.xml"
|
||||
$regResult = $null
|
||||
|
||||
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:Role", $nsMgr)
|
||||
$alreadyExists = $false
|
||||
foreach ($r in $existing) {
|
||||
if ($r.InnerText -eq $roleName) {
|
||||
$alreadyExists = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($alreadyExists) {
|
||||
$regResult = "already"
|
||||
} else {
|
||||
$roleElem = $configDoc.CreateElement("Role", "http://v8.1c.ru/8.3/MDClasses")
|
||||
$roleElem.InnerText = $roleName
|
||||
|
||||
if ($existing.Count -gt 0) {
|
||||
# Insert after last existing <Role>
|
||||
$lastRole = $existing[$existing.Count - 1]
|
||||
$newWs = $configDoc.CreateWhitespace("`n`t`t`t")
|
||||
$childObjects.InsertAfter($newWs, $lastRole) | Out-Null
|
||||
$childObjects.InsertAfter($roleElem, $newWs) | Out-Null
|
||||
} else {
|
||||
# No existing roles — 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($roleElem, $lastChild) | Out-Null
|
||||
} else {
|
||||
$childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
|
||||
$childObjects.AppendChild($roleElem) | Out-Null
|
||||
$childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t")) | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
# Save
|
||||
$cfgSettings = New-Object System.Xml.XmlWriterSettings
|
||||
$cfgSettings.Encoding = New-Object System.Text.UTF8Encoding($true)
|
||||
$cfgSettings.Indent = $false
|
||||
$stream = New-Object System.IO.FileStream($configXmlPath, [System.IO.FileMode]::Create)
|
||||
$writer = [System.Xml.XmlWriter]::Create($stream, $cfgSettings)
|
||||
$configDoc.Save($writer)
|
||||
$writer.Close()
|
||||
$stream.Close()
|
||||
|
||||
$regResult = "added"
|
||||
}
|
||||
} else {
|
||||
$regResult = "no-childobj"
|
||||
}
|
||||
} else {
|
||||
$regResult = "no-config"
|
||||
}
|
||||
|
||||
# --- 13. Summary ---
|
||||
|
||||
Write-Host "[OK] Role '$roleName' compiled"
|
||||
Write-Host " UUID: $uuid"
|
||||
Write-Host " Metadata: $metadataPath"
|
||||
Write-Host " Rights: $rightsPath"
|
||||
Write-Host " Objects: $($parsedObjects.Count), Rights: $totalRights, Templates: $templateCount"
|
||||
switch ($regResult) {
|
||||
"added" { Write-Host " Configuration.xml: <Role>$roleName</Role> added to ChildObjects" }
|
||||
"already" { Write-Host " Configuration.xml: <Role>$roleName</Role> already registered" }
|
||||
"no-childobj" { Write-Warning "Configuration.xml found but <ChildObjects> not found" }
|
||||
"no-config" { Write-Warning "Configuration.xml not found at $configXmlPath — register manually" }
|
||||
}
|
||||
@@ -1,837 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# role-compile v1.10 — Compile 1C role from JSON
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from lxml import etree
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
|
||||
# Blocks edits of vendor objects "на замке" / read-only configs. Trigger = bin
|
||||
# present; reaction from .v8-project.json editingAllowedCheck (deny|warn|off,
|
||||
# default deny). Never throws (except sys.exit on deny) — errors degrade to allow.
|
||||
# ============================================================
|
||||
|
||||
def _sg_root_uuid(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return None
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str) and child.get("uuid"):
|
||||
return child.get("uuid")
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _sg_is_external_root(xml_path):
|
||||
if not os.path.isfile(xml_path):
|
||||
return False
|
||||
try:
|
||||
mx = etree.parse(xml_path).getroot()
|
||||
for child in mx:
|
||||
if isinstance(child.tag, str):
|
||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
|
||||
def _sg_get_edit_mode(cfg_dir):
|
||||
try:
|
||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
||||
if not pj:
|
||||
return "deny"
|
||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
||||
for db in proj.get("databases", []):
|
||||
src = db.get("configSrc")
|
||||
if src:
|
||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
||||
if db.get("editingAllowedCheck"):
|
||||
return db["editingAllowedCheck"]
|
||||
if proj.get("editingAllowedCheck"):
|
||||
return proj["editingAllowedCheck"]
|
||||
return "deny"
|
||||
except Exception:
|
||||
return "deny"
|
||||
|
||||
|
||||
def assert_edit_allowed(target_path, require):
|
||||
try:
|
||||
rp = os.path.abspath(target_path)
|
||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
||||
if _sg_is_external_root(rp):
|
||||
return
|
||||
elem_uuid = _sg_root_uuid(rp)
|
||||
cfg_dir = None
|
||||
bin_path = None
|
||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
||||
for _ in range(12):
|
||||
if not d:
|
||||
break
|
||||
if _sg_is_external_root(d + ".xml"):
|
||||
return
|
||||
if not elem_uuid:
|
||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
||||
if not cfg_dir:
|
||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
||||
cfg_dir = d
|
||||
bin_path = cand
|
||||
if elem_uuid and cfg_dir:
|
||||
break
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
if not elem_uuid and cfg_dir:
|
||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
||||
if not bin_path or not os.path.exists(bin_path):
|
||||
return
|
||||
data = open(bin_path, "rb").read()
|
||||
if len(data) <= 32:
|
||||
return
|
||||
if data[:3] == b"\xef\xbb\xbf":
|
||||
data = data[3:]
|
||||
text = data.decode("utf-8", "replace")
|
||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
||||
if not h:
|
||||
return
|
||||
g = int(h.group(1))
|
||||
k = int(h.group(2))
|
||||
if k == 0:
|
||||
return
|
||||
best = None
|
||||
if elem_uuid:
|
||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
||||
f1 = int(m.group(1))
|
||||
if best is None or f1 < best:
|
||||
best = f1
|
||||
blocked = False
|
||||
code = ""
|
||||
reason = ""
|
||||
if g == 1:
|
||||
blocked = True
|
||||
code = "capability-off"
|
||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
||||
elif require == "removed":
|
||||
if best is not None and best != 2:
|
||||
blocked = True
|
||||
code = "not-removed"
|
||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
||||
else:
|
||||
if best is not None and best == 0:
|
||||
blocked = True
|
||||
code = "locked"
|
||||
reason = "объект на замке — редактирование сломает обновления"
|
||||
if not blocked:
|
||||
return
|
||||
mode = _sg_get_edit_mode(cfg_dir)
|
||||
if mode == "off":
|
||||
return
|
||||
if mode == "warn":
|
||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
||||
return
|
||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
||||
if code == "capability-off":
|
||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
||||
fix = (
|
||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
||||
)
|
||||
elif code == "not-removed":
|
||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
||||
fix = (
|
||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
||||
)
|
||||
else:
|
||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
||||
fix = (
|
||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
||||
)
|
||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
||||
sys.exit(1)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception:
|
||||
return
|
||||
|
||||
|
||||
def detect_format_version(d):
|
||||
while d:
|
||||
cfg_path = os.path.join(d, "Configuration.xml")
|
||||
if os.path.isfile(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8-sig") as f:
|
||||
head = f.read(2000)
|
||||
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
|
||||
if m:
|
||||
return m.group(1)
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return "2.17"
|
||||
|
||||
|
||||
def esc_xml(s):
|
||||
"""Экранирование ТЕКСТА элемента: только & < > . Кавычки платформа в тексте не экранирует
|
||||
(92142 сырых кавычки на корпус, ни одной "); " она принимает, но нормализует обратно."""
|
||||
return s.replace('&', '&').replace('<', '<').replace('>', '>')
|
||||
|
||||
|
||||
def emit_mltext(lines, indent, tag, text):
|
||||
if not text:
|
||||
lines.append(f"{indent}<{tag}/>")
|
||||
return
|
||||
lines.append(f"{indent}<{tag}>")
|
||||
lines.append(f"{indent}\t<v8:item>")
|
||||
lines.append(f"{indent}\t\t<v8:lang>ru</v8:lang>")
|
||||
lines.append(f"{indent}\t\t<v8:content>{esc_xml(text)}</v8:content>")
|
||||
lines.append(f"{indent}\t</v8:item>")
|
||||
lines.append(f"{indent}</{tag}>")
|
||||
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
# --- Russian synonyms -> canonical English names ---
|
||||
|
||||
TYPE_ALIASES = {
|
||||
"Справочник": "Catalog",
|
||||
"Документ": "Document",
|
||||
"РегистрСведений": "InformationRegister",
|
||||
"РегистрНакопления": "AccumulationRegister",
|
||||
"РегистрБухгалтерии": "AccountingRegister",
|
||||
"РегистрРасчета": "CalculationRegister",
|
||||
"Константа": "Constant",
|
||||
"ПланСчетов": "ChartOfAccounts",
|
||||
"ПланВидовХарактеристик": "ChartOfCharacteristicTypes",
|
||||
"ПланВидовРасчета": "ChartOfCalculationTypes",
|
||||
"ПланОбмена": "ExchangePlan",
|
||||
"БизнесПроцесс": "BusinessProcess",
|
||||
"Задача": "Task",
|
||||
"Обработка": "DataProcessor",
|
||||
"Отчет": "Report",
|
||||
"ОбщаяФорма": "CommonForm",
|
||||
"ОбщаяКоманда": "CommonCommand",
|
||||
"Подсистема": "Subsystem",
|
||||
"КритерийОтбора": "FilterCriterion",
|
||||
"ЖурналДокументов": "DocumentJournal",
|
||||
"Последовательность": "Sequence",
|
||||
"ВебСервис": "WebService",
|
||||
"HTTPСервис": "HTTPService",
|
||||
"СервисИнтеграции": "IntegrationService",
|
||||
"ПараметрСеанса": "SessionParameter",
|
||||
"ОбщийРеквизит": "CommonAttribute",
|
||||
"Конфигурация": "Configuration",
|
||||
"Перечисление": "Enum",
|
||||
# Nested
|
||||
"Реквизит": "Attribute",
|
||||
"СтандартныйРеквизит": "StandardAttribute",
|
||||
"ТабличнаяЧасть": "TabularSection",
|
||||
"Измерение": "Dimension",
|
||||
"Ресурс": "Resource",
|
||||
"Команда": "Command",
|
||||
"РеквизитАдресации": "AddressingAttribute",
|
||||
}
|
||||
|
||||
RIGHT_ALIASES = {
|
||||
"Чтение": "Read",
|
||||
"Добавление": "Insert",
|
||||
"Изменение": "Update",
|
||||
"Удаление": "Delete",
|
||||
"Просмотр": "View",
|
||||
"Редактирование": "Edit",
|
||||
"ВводПоСтроке": "InputByString",
|
||||
"Проведение": "Posting",
|
||||
"ОтменаПроведения": "UndoPosting",
|
||||
"ИнтерактивноеДобавление": "InteractiveInsert",
|
||||
"ИнтерактивнаяПометкаУдаления": "InteractiveSetDeletionMark",
|
||||
"ИнтерактивноеСнятиеПометкиУдаления": "InteractiveClearDeletionMark",
|
||||
"ИнтерактивноеУдаление": "InteractiveDelete",
|
||||
"ИнтерактивноеУдалениеПомеченных": "InteractiveDeleteMarked",
|
||||
"ИнтерактивноеПроведение": "InteractivePosting",
|
||||
"ИнтерактивноеПроведениеНеоперативное": "InteractivePostingRegular",
|
||||
"ИнтерактивнаяОтменаПроведения": "InteractiveUndoPosting",
|
||||
"ИнтерактивноеИзменениеПроведенных": "InteractiveChangeOfPosted",
|
||||
"Использование": "Use",
|
||||
"Получение": "Get",
|
||||
"Установка": "Set",
|
||||
"Старт": "Start",
|
||||
"ИнтерактивныйСтарт": "InteractiveStart",
|
||||
"ИнтерактивнаяАктивация": "InteractiveActivate",
|
||||
"Выполнение": "Execute",
|
||||
"ИнтерактивноеВыполнение": "InteractiveExecute",
|
||||
"УправлениеИтогами": "TotalsControl",
|
||||
"Администрирование": "Administration",
|
||||
"АдминистрированиеДанных": "DataAdministration",
|
||||
"ТонкийКлиент": "ThinClient",
|
||||
"ВебКлиент": "WebClient",
|
||||
"ТолстыйКлиент": "ThickClient",
|
||||
"ВнешнееСоединение": "ExternalConnection",
|
||||
"Вывод": "Output",
|
||||
"СохранениеДанныхПользователя": "SaveUserData",
|
||||
"МобильныйКлиент": "MobileClient",
|
||||
}
|
||||
|
||||
# --- Known rights per object type ---
|
||||
|
||||
KNOWN_RIGHTS = {
|
||||
"Configuration": [
|
||||
"Administration", "DataAdministration", "UpdateDataBaseConfiguration",
|
||||
"ConfigurationExtensionsAdministration", "ActiveUsers", "EventLog", "ExclusiveMode",
|
||||
"ThinClient", "ThickClient", "WebClient", "MobileClient", "ExternalConnection",
|
||||
"Automation", "Output", "SaveUserData", "TechnicalSpecialistMode",
|
||||
"InteractiveOpenExtDataProcessors", "InteractiveOpenExtReports",
|
||||
"AnalyticsSystemClient", "CollaborationSystemInfoBaseRegistration",
|
||||
"MainWindowModeNormal", "MainWindowModeWorkplace",
|
||||
"MainWindowModeEmbeddedWorkplace", "MainWindowModeFullscreenWorkplace", "MainWindowModeKiosk",
|
||||
],
|
||||
"Catalog": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveDeleteMarked",
|
||||
"InteractiveDeletePredefinedData", "InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData", "InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData", "ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"Document": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"Posting", "UndoPosting",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveDeleteMarked",
|
||||
"InteractivePosting", "InteractivePostingRegular", "InteractiveUndoPosting",
|
||||
"InteractiveChangeOfPosted",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData", "ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"InformationRegister": [
|
||||
"Read", "Update", "View", "Edit", "TotalsControl",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"UpdateDataHistoryOfMissingData", "ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"AccumulationRegister": ["Read", "Update", "View", "Edit", "TotalsControl"],
|
||||
"AccountingRegister": ["Read", "Update", "View", "Edit", "TotalsControl"],
|
||||
"CalculationRegister": ["Read", "View"],
|
||||
"Constant": [
|
||||
"Read", "Update", "View", "Edit",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"ChartOfAccounts": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete",
|
||||
"InteractiveDeletePredefinedData", "InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData", "InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory", "ReadDataHistoryOfMissingData",
|
||||
"UpdateDataHistory", "UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
],
|
||||
"ChartOfCharacteristicTypes": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveDeleteMarked",
|
||||
"InteractiveDeletePredefinedData", "InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData", "InteractiveDeleteMarkedPredefinedData",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"ReadDataHistoryOfMissingData", "UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"ChartOfCalculationTypes": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete",
|
||||
"InteractiveDeletePredefinedData", "InteractiveSetDeletionMarkPredefinedData",
|
||||
"InteractiveClearDeletionMarkPredefinedData", "InteractiveDeleteMarkedPredefinedData",
|
||||
],
|
||||
"ExchangePlan": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveDeleteMarked",
|
||||
"ReadDataHistory", "ViewDataHistory", "UpdateDataHistory",
|
||||
"ReadDataHistoryOfMissingData", "UpdateDataHistoryOfMissingData",
|
||||
"UpdateDataHistorySettings", "UpdateDataHistoryVersionComment",
|
||||
"EditDataHistoryVersionComment", "SwitchToDataHistoryVersion",
|
||||
],
|
||||
"BusinessProcess": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"Start", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveActivate", "InteractiveStart",
|
||||
],
|
||||
"Task": [
|
||||
"Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString",
|
||||
"Execute", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark",
|
||||
"InteractiveDelete", "InteractiveActivate", "InteractiveExecute",
|
||||
],
|
||||
"DataProcessor": ["Use", "View"],
|
||||
"Report": ["Use", "View"],
|
||||
"CommonForm": ["View"],
|
||||
"CommonCommand": ["View"],
|
||||
"Subsystem": ["View"],
|
||||
"FilterCriterion": ["View"],
|
||||
"DocumentJournal": ["Read", "View"],
|
||||
"Sequence": ["Read", "Update"],
|
||||
"WebService": ["Use"],
|
||||
"HTTPService": ["Use"],
|
||||
"IntegrationService": ["Use"],
|
||||
"SessionParameter": ["Get", "Set"],
|
||||
"CommonAttribute": ["View", "Edit"],
|
||||
}
|
||||
|
||||
NESTED_RIGHTS = ["View", "Edit"]
|
||||
COMMAND_RIGHTS = ["View"]
|
||||
|
||||
# --- Presets ---
|
||||
|
||||
PRESETS = {
|
||||
"view": {
|
||||
"Catalog": ["Read", "View", "InputByString"],
|
||||
"ExchangePlan": ["Read", "View", "InputByString"],
|
||||
"Document": ["Read", "View", "InputByString"],
|
||||
"ChartOfAccounts": ["Read", "View", "InputByString"],
|
||||
"ChartOfCharacteristicTypes": ["Read", "View", "InputByString"],
|
||||
"ChartOfCalculationTypes": ["Read", "View", "InputByString"],
|
||||
"BusinessProcess": ["Read", "View", "InputByString"],
|
||||
"Task": ["Read", "View", "InputByString"],
|
||||
"InformationRegister": ["Read", "View"],
|
||||
"AccumulationRegister": ["Read", "View"],
|
||||
"AccountingRegister": ["Read", "View"],
|
||||
"CalculationRegister": ["Read", "View"],
|
||||
"Constant": ["Read", "View"],
|
||||
"DocumentJournal": ["Read", "View"],
|
||||
"Sequence": ["Read"],
|
||||
"CommonForm": ["View"],
|
||||
"CommonCommand": ["View"],
|
||||
"Subsystem": ["View"],
|
||||
"FilterCriterion": ["View"],
|
||||
"SessionParameter": ["Get"],
|
||||
"CommonAttribute": ["View"],
|
||||
"DataProcessor": ["Use", "View"],
|
||||
"Report": ["Use", "View"],
|
||||
"Configuration": ["ThinClient", "WebClient", "Output", "SaveUserData", "MainWindowModeNormal"],
|
||||
},
|
||||
"edit": {
|
||||
"Catalog": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark"],
|
||||
"ExchangePlan": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark"],
|
||||
"Document": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "Posting", "UndoPosting", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark", "InteractivePosting", "InteractivePostingRegular", "InteractiveUndoPosting", "InteractiveChangeOfPosted"],
|
||||
"ChartOfAccounts": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark"],
|
||||
"ChartOfCharacteristicTypes": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark"],
|
||||
"ChartOfCalculationTypes": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark"],
|
||||
"BusinessProcess": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "Start", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark", "InteractiveActivate", "InteractiveStart"],
|
||||
"Task": ["Read", "Insert", "Update", "Delete", "View", "Edit", "InputByString", "Execute", "InteractiveInsert", "InteractiveSetDeletionMark", "InteractiveClearDeletionMark", "InteractiveActivate", "InteractiveExecute"],
|
||||
"InformationRegister": ["Read", "Update", "View", "Edit"],
|
||||
"AccumulationRegister": ["Read", "Update", "View", "Edit"],
|
||||
"AccountingRegister": ["Read", "Update", "View", "Edit"],
|
||||
"Constant": ["Read", "Update", "View", "Edit"],
|
||||
"DocumentJournal": ["Read", "View"],
|
||||
"Sequence": ["Read", "Update"],
|
||||
"SessionParameter": ["Get", "Set"],
|
||||
"CommonAttribute": ["View", "Edit"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def translate_object_name(name):
|
||||
parts = name.split('.')
|
||||
result = []
|
||||
for p in parts:
|
||||
result.append(TYPE_ALIASES.get(p, p))
|
||||
return '.'.join(result)
|
||||
|
||||
|
||||
def translate_right_name(name):
|
||||
return RIGHT_ALIASES.get(name, name)
|
||||
|
||||
|
||||
def get_object_type(object_name):
|
||||
dot_idx = object_name.find('.')
|
||||
if dot_idx < 0:
|
||||
return object_name
|
||||
return object_name[:dot_idx]
|
||||
|
||||
|
||||
def is_nested_object(object_name):
|
||||
return len(object_name.split('.')) >= 3
|
||||
|
||||
|
||||
def resolve_preset(object_type, preset_name):
|
||||
preset = preset_name.lstrip('@')
|
||||
if preset not in PRESETS:
|
||||
print(f"WARNING: Unknown preset '@{preset}'. Known: @view, @edit", file=sys.stderr)
|
||||
return []
|
||||
type_map = PRESETS[preset]
|
||||
if object_type not in type_map:
|
||||
available = []
|
||||
for k in PRESETS:
|
||||
if object_type in PRESETS[k]:
|
||||
available.append(f'@{k}')
|
||||
avail_str = ', '.join(available) if available else 'none'
|
||||
print(f"WARNING: Preset '@{preset}' not defined for type '{object_type}'. Available: {avail_str}", file=sys.stderr)
|
||||
return []
|
||||
return list(type_map[object_type])
|
||||
|
||||
|
||||
def validate_right_name(object_name, right_name):
|
||||
object_type = get_object_type(object_name)
|
||||
|
||||
if is_nested_object(object_name):
|
||||
if '.Command.' in object_name:
|
||||
if right_name not in COMMAND_RIGHTS:
|
||||
print(f"WARNING: {object_name}: '{right_name}' not valid for commands (only: View)", file=sys.stderr)
|
||||
return False
|
||||
else:
|
||||
if right_name not in NESTED_RIGHTS:
|
||||
print(f"WARNING: {object_name}: '{right_name}' not valid for nested objects (only: View, Edit)", file=sys.stderr)
|
||||
return False
|
||||
return True
|
||||
|
||||
if object_type not in KNOWN_RIGHTS:
|
||||
print(f"WARNING: {object_name}: unknown object type '{object_type}'", file=sys.stderr)
|
||||
return True
|
||||
|
||||
valid_rights = KNOWN_RIGHTS[object_type]
|
||||
if right_name not in valid_rights:
|
||||
suggestions = [r for r in valid_rights if right_name in r or r in right_name]
|
||||
sug_str = f" Did you mean: {', '.join(suggestions)}?" if suggestions else ""
|
||||
print(f"WARNING: {object_name}: unknown right '{right_name}'.{sug_str}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def parse_object_entry(entry):
|
||||
# --- String shorthand ---
|
||||
if isinstance(entry, str):
|
||||
colon_idx = entry.find(':')
|
||||
if colon_idx < 0:
|
||||
print(f"WARNING: Invalid string '{entry}' -- expected 'Object.Name: @preset' or 'Object.Name: Right1, Right2'", file=sys.stderr)
|
||||
return None
|
||||
obj_name = translate_object_name(entry[:colon_idx].strip())
|
||||
rights_str = entry[colon_idx + 1:].strip()
|
||||
object_type = get_object_type(obj_name)
|
||||
|
||||
if rights_str.startswith('@'):
|
||||
right_names = resolve_preset(object_type, rights_str)
|
||||
else:
|
||||
right_names = [translate_right_name(r.strip()) for r in rights_str.split(',') if r.strip()]
|
||||
for r in right_names:
|
||||
validate_right_name(obj_name, r)
|
||||
|
||||
rights = []
|
||||
for r in right_names:
|
||||
rights.append({'Name': r, 'Value': 'true', 'Condition': None})
|
||||
return {'Name': obj_name, 'Rights': rights}
|
||||
|
||||
# --- Object form ---
|
||||
obj_name = translate_object_name(str(entry.get('name', '')))
|
||||
if not obj_name:
|
||||
print("WARNING: Object entry missing 'name' field", file=sys.stderr)
|
||||
return None
|
||||
|
||||
object_type = get_object_type(obj_name)
|
||||
# Use a list of tuples to preserve insertion order
|
||||
rights_map = {} # name -> {Value, Condition}
|
||||
rights_order = [] # preserve order
|
||||
|
||||
# 1) Start with preset
|
||||
if entry.get('preset'):
|
||||
preset_rights = resolve_preset(object_type, str(entry['preset']))
|
||||
for r in preset_rights:
|
||||
if r not in rights_map:
|
||||
rights_order.append(r)
|
||||
rights_map[r] = {'Value': 'true', 'Condition': None}
|
||||
|
||||
# 2) Apply explicit rights
|
||||
if entry.get('rights') is not None:
|
||||
if isinstance(entry['rights'], list):
|
||||
for r in entry['rights']:
|
||||
r_name = translate_right_name(str(r))
|
||||
validate_right_name(obj_name, r_name)
|
||||
if r_name not in rights_map:
|
||||
rights_order.append(r_name)
|
||||
rights_map[r_name] = {'Value': 'true', 'Condition': None}
|
||||
elif isinstance(entry['rights'], dict):
|
||||
for p_name, p_value in entry['rights'].items():
|
||||
r_name = translate_right_name(p_name)
|
||||
validate_right_name(obj_name, r_name)
|
||||
bool_val = 'true' if p_value is True or str(p_value) == 'True' else 'false'
|
||||
if r_name not in rights_map:
|
||||
rights_order.append(r_name)
|
||||
rights_map[r_name] = {'Value': bool_val, 'Condition': None}
|
||||
|
||||
# 3) Apply RLS conditions
|
||||
if entry.get('rls'):
|
||||
for p_name, p_value in entry['rls'].items():
|
||||
rls_right = translate_right_name(p_name)
|
||||
if rls_right in rights_map:
|
||||
rights_map[rls_right]['Condition'] = str(p_value)
|
||||
else:
|
||||
print(f"WARNING: {obj_name}: RLS for '{rls_right}' but this right is not in the rights list", file=sys.stderr)
|
||||
|
||||
# Convert to array
|
||||
rights = []
|
||||
for k in rights_order:
|
||||
rights.append({
|
||||
'Name': k,
|
||||
'Value': rights_map[k]['Value'],
|
||||
'Condition': rights_map[k]['Condition'],
|
||||
})
|
||||
|
||||
return {'Name': obj_name, 'Rights': rights}
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Compile 1C role from JSON', allow_abbrev=False)
|
||||
parser.add_argument('-JsonPath', type=str, required=True)
|
||||
parser.add_argument('-OutputDir', type=str, required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
# --- 1. Load and validate JSON ---
|
||||
json_path = args.JsonPath
|
||||
if not os.path.exists(json_path):
|
||||
print(f"File not found: {json_path}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
with open(json_path, 'r', encoding='utf-8-sig') as f:
|
||||
defn = json.load(f)
|
||||
|
||||
if not defn.get('name'):
|
||||
print("JSON must have 'name' field (role programmatic name)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
role_name = str(defn['name'])
|
||||
synonym = str(defn['synonym']) if defn.get('synonym') else role_name
|
||||
comment = str(defn['comment']) if defn.get('comment') else ''
|
||||
|
||||
# Synonym: accept "rights" as alias for "objects"
|
||||
if not defn.get('objects') and defn.get('rights'):
|
||||
defn['objects'] = defn['rights']
|
||||
|
||||
out_dir_resolved = args.OutputDir if os.path.isabs(args.OutputDir) else os.path.join(os.getcwd(), args.OutputDir)
|
||||
assert_edit_allowed(out_dir_resolved, "editable")
|
||||
format_version = detect_format_version(out_dir_resolved)
|
||||
|
||||
# --- 2. Parse all object entries ---
|
||||
parsed_objects = []
|
||||
if defn.get('objects'):
|
||||
for entry in defn['objects']:
|
||||
parsed = parse_object_entry(entry)
|
||||
if parsed:
|
||||
parsed_objects.append(parsed)
|
||||
|
||||
# --- 3. Generate UUID ---
|
||||
uid = new_uuid()
|
||||
|
||||
# --- 4. Emit metadata XML (Roles/Name.xml) ---
|
||||
lines = []
|
||||
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
|
||||
lines.append('<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses"')
|
||||
lines.append(' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"')
|
||||
lines.append(' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"')
|
||||
lines.append(' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"')
|
||||
lines.append(' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"')
|
||||
lines.append(' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"')
|
||||
lines.append(' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"')
|
||||
lines.append(' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"')
|
||||
lines.append(' xmlns:v8="http://v8.1c.ru/8.1/data/core"')
|
||||
lines.append(' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"')
|
||||
lines.append(' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"')
|
||||
lines.append(' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"')
|
||||
lines.append(' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"')
|
||||
lines.append(' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"')
|
||||
lines.append(' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"')
|
||||
lines.append(' xmlns:xs="http://www.w3.org/2001/XMLSchema"')
|
||||
lines.append(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
|
||||
lines.append(f' version="{format_version}">')
|
||||
lines.append(f' <Role uuid="{uid}">')
|
||||
lines.append(' <Properties>')
|
||||
lines.append(f' <Name>{role_name}</Name>')
|
||||
lines.append(' <Synonym>')
|
||||
lines.append(' <v8:item>')
|
||||
lines.append(' <v8:lang>ru</v8:lang>')
|
||||
lines.append(f' <v8:content>{esc_xml(synonym)}</v8:content>')
|
||||
lines.append(' </v8:item>')
|
||||
lines.append(' </Synonym>')
|
||||
if comment:
|
||||
lines.append(f' <Comment>{esc_xml(comment)}</Comment>')
|
||||
else:
|
||||
lines.append(' <Comment/>')
|
||||
lines.append(' </Properties>')
|
||||
lines.append(' </Role>')
|
||||
lines.append('</MetaDataObject>')
|
||||
|
||||
metadata_xml = '\n'.join(lines) + '\n'
|
||||
|
||||
# --- 5. Emit Rights XML (Roles/Name/Ext/Rights.xml) ---
|
||||
lines = []
|
||||
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
|
||||
lines.append('<Rights xmlns="http://v8.1c.ru/8.2/roles"')
|
||||
lines.append(' xmlns:xs="http://www.w3.org/2001/XMLSchema"')
|
||||
lines.append(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
|
||||
lines.append(f' xsi:type="Rights" version="{format_version}">')
|
||||
|
||||
# Global flags
|
||||
sfno = str(defn['setForNewObjects']).lower() if defn.get('setForNewObjects') is not None else 'false'
|
||||
sfab = str(defn['setForAttributesByDefault']).lower() if defn.get('setForAttributesByDefault') is not None else 'true'
|
||||
irco = str(defn['independentRightsOfChildObjects']).lower() if defn.get('independentRightsOfChildObjects') is not None else 'false'
|
||||
|
||||
lines.append(f' <setForNewObjects>{sfno}</setForNewObjects>')
|
||||
lines.append(f' <setForAttributesByDefault>{sfab}</setForAttributesByDefault>')
|
||||
lines.append(f' <independentRightsOfChildObjects>{irco}</independentRightsOfChildObjects>')
|
||||
|
||||
# Object blocks
|
||||
total_rights = 0
|
||||
for obj in parsed_objects:
|
||||
lines.append(' <object>')
|
||||
lines.append(f' <name>{obj["Name"]}</name>')
|
||||
for right in obj['Rights']:
|
||||
lines.append(' <right>')
|
||||
lines.append(f' <name>{right["Name"]}</name>')
|
||||
lines.append(f' <value>{right["Value"]}</value>')
|
||||
if right['Condition']:
|
||||
lines.append(' <restrictionByCondition>')
|
||||
lines.append(f' <condition>{esc_xml(right["Condition"])}</condition>')
|
||||
lines.append(' </restrictionByCondition>')
|
||||
lines.append(' </right>')
|
||||
total_rights += 1
|
||||
lines.append(' </object>')
|
||||
|
||||
# RLS restriction templates
|
||||
template_count = 0
|
||||
if defn.get('templates'):
|
||||
for tpl in defn['templates']:
|
||||
lines.append(' <restrictionTemplate>')
|
||||
lines.append(f' <name>{esc_xml(str(tpl["name"]))}</name>')
|
||||
lines.append(f' <condition>{esc_xml(str(tpl["condition"]))}</condition>')
|
||||
lines.append(' </restrictionTemplate>')
|
||||
template_count += 1
|
||||
|
||||
lines.append('</Rights>')
|
||||
|
||||
rights_xml = '\n'.join(lines) + '\n'
|
||||
|
||||
# --- 6. Write output files ---
|
||||
out_dir = args.OutputDir
|
||||
if not os.path.isabs(out_dir):
|
||||
out_dir = os.path.join(os.getcwd(), out_dir)
|
||||
|
||||
# Determine Roles dir and config root
|
||||
# Back-compat: if OutputDir leaf is "Roles", use as-is; otherwise treat as config root
|
||||
leaf = os.path.basename(out_dir.rstrip(os.sep).rstrip('/'))
|
||||
if leaf == 'Roles':
|
||||
roles_dir = out_dir
|
||||
config_dir = os.path.dirname(out_dir)
|
||||
else:
|
||||
roles_dir = os.path.join(out_dir, 'Roles')
|
||||
config_dir = out_dir
|
||||
|
||||
# Metadata: Roles/RoleName.xml
|
||||
metadata_path = os.path.join(roles_dir, f'{role_name}.xml')
|
||||
os.makedirs(roles_dir, exist_ok=True)
|
||||
|
||||
# Rights: Roles/RoleName/Ext/Rights.xml
|
||||
role_sub_dir = os.path.join(roles_dir, role_name)
|
||||
ext_dir = os.path.join(role_sub_dir, 'Ext')
|
||||
rights_path = os.path.join(ext_dir, 'Rights.xml')
|
||||
os.makedirs(ext_dir, exist_ok=True)
|
||||
|
||||
write_utf8_bom(metadata_path, metadata_xml)
|
||||
write_utf8_bom(rights_path, rights_xml)
|
||||
|
||||
# --- 7. Register in Configuration.xml ---
|
||||
config_xml_path = os.path.join(config_dir, 'Configuration.xml')
|
||||
reg_result = None
|
||||
|
||||
if os.path.exists(config_xml_path):
|
||||
with open(config_xml_path, 'r', encoding='utf-8-sig') as f:
|
||||
raw_text = f.read()
|
||||
|
||||
# Check if already registered
|
||||
if f'<Role>{role_name}</Role>' in raw_text:
|
||||
reg_result = 'already'
|
||||
else:
|
||||
# Find last <Role>...</Role> and insert after it
|
||||
role_pattern = re.compile(r'(<Role>[^<]*</Role>)')
|
||||
matches = list(role_pattern.finditer(raw_text))
|
||||
new_role_tag = f'<Role>{role_name}</Role>'
|
||||
|
||||
if matches:
|
||||
# Insert after last existing <Role>
|
||||
last_match = matches[-1]
|
||||
insert_pos = last_match.end()
|
||||
raw_text = raw_text[:insert_pos] + f'\n\t\t\t{new_role_tag}' + raw_text[insert_pos:]
|
||||
else:
|
||||
# No existing roles — insert before </ChildObjects>
|
||||
raw_text = raw_text.replace('</ChildObjects>', f'\t\t\t{new_role_tag}\n\t\t</ChildObjects>')
|
||||
|
||||
write_utf8_bom(config_xml_path, raw_text)
|
||||
reg_result = 'added'
|
||||
else:
|
||||
reg_result = 'no-config'
|
||||
|
||||
# --- 8. Summary ---
|
||||
print(f"[OK] Role '{role_name}' compiled")
|
||||
print(f" UUID: {uid}")
|
||||
print(f" Metadata: {metadata_path}")
|
||||
print(f" Rights: {rights_path}")
|
||||
print(f" Objects: {len(parsed_objects)}, Rights: {total_rights}, Templates: {template_count}")
|
||||
if reg_result == 'added':
|
||||
print(f" Configuration.xml: <Role>{role_name}</Role> added to ChildObjects")
|
||||
elif reg_result == 'already':
|
||||
print(f" Configuration.xml: <Role>{role_name}</Role> already registered")
|
||||
elif reg_result == 'no-childobj':
|
||||
print(f"WARNING: Configuration.xml found but <ChildObjects> not found", file=sys.stderr)
|
||||
elif reg_result == 'no-config':
|
||||
print(f"WARNING: Configuration.xml not found at {config_xml_path} -- register manually", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,62 +0,0 @@
|
||||
---
|
||||
name: web-info
|
||||
description: Статус Apache и веб-публикаций 1С — запущен ли сервер, какие базы опубликованы, ошибки. Используй когда пользователь спрашивает про статус веб-сервера, опубликованные базы, работает ли Apache
|
||||
argument-hint: ""
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /web-info — Статус Apache и публикаций 1С
|
||||
|
||||
Показывает состояние Apache HTTP Server, список опубликованных баз и последние ошибки.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/web-info
|
||||
```
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Если задан `webPath` — используй как `-ApachePath`.
|
||||
По умолчанию `tools/apache24` от корня проекта.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/web-info.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
|
||||
| Параметр | Обязательный | Описание |
|
||||
|----------|:------------:|----------|
|
||||
| `-ApachePath <путь>` | нет | Корень Apache (по умолчанию `tools/apache24`) |
|
||||
|
||||
## Формат вывода
|
||||
|
||||
```
|
||||
=== Apache Web Server ===
|
||||
Status: Запущен (PID: 12345)
|
||||
Path: C:\...\tools\apache24
|
||||
Port: 8081
|
||||
Module: C:/Program Files/1cv8/8.3.24.1691/bin/wsap24.dll
|
||||
|
||||
=== Опубликованные базы ===
|
||||
mydb http://localhost:8081/mydb File="C:\Bases\MyDB";
|
||||
|
||||
=== Последние ошибки ===
|
||||
(пусто)
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Статус по умолчанию
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/web-info.ps1"
|
||||
|
||||
# Указать путь к Apache
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/web-info.ps1" -ApachePath "C:\tools\apache24"
|
||||
```
|
||||
@@ -1,7 +0,0 @@
|
||||
# Коммиты, которые git blame должен «проскакивать» (механические правки —
|
||||
# не меняют авторство содержимого). Включить локально:
|
||||
# git config blame.ignoreRevsFile .git-blame-ignore-revs
|
||||
# GitHub/GitLab уважают этот файл в blame-UI автоматически.
|
||||
|
||||
# chore(repo): нормализация EOL к LF + .gitattributes
|
||||
26888a07d58351755fb8e487727c00d5b611eb95
|
||||
@@ -1,28 +0,0 @@
|
||||
# EOL policy
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Авторский контент нормализуем к LF: инструмент правки (Edit) всегда пишет LF,
|
||||
# поэтому единый LF убирает EOL-шум в диффах и ловушку «не правь CRLF-файл».
|
||||
# git с eol=lf конвертит ТОЛЬКО CR<->LF и не трогает BOM (BOM — байты контента),
|
||||
# поэтому BOM на .ps1 сохраняется.
|
||||
*.ps1 text eol=lf
|
||||
*.psm1 text eol=lf
|
||||
*.py text eol=lf
|
||||
*.mjs text eol=lf
|
||||
*.md text eol=lf
|
||||
*.json text eol=lf
|
||||
.gitignore text eol=lf
|
||||
|
||||
# .bsl уже целиком LF — пин фиксирует статус-кво от будущего дрейфа.
|
||||
*.bsl text eol=lf
|
||||
|
||||
# Данные 1С НЕ трогаем. *.xml — реальные выгрузки 1С (EOL местами значим,
|
||||
# правим не мы, а навыки): оставляем как есть, под управление не берём.
|
||||
# autocrlf=false и отсутствие text-атрибута => git хранит их байты как есть.
|
||||
|
||||
# Бинарники 1С
|
||||
*.bin binary
|
||||
|
||||
# Package.bin пакетов XDTO — текстовый XML, несмотря на расширение. Оставляем
|
||||
# под правилом *.bin binary (байты не нормализуются), но включаем текстовый diff,
|
||||
# иначе изменение модели пакета в истории выглядит как «Binary files differ».
|
||||
XDTOPackages/**/Package.bin diff
|
||||
@@ -1,26 +0,0 @@
|
||||
# 1C Skills for {{PLATFORM_LABEL}} ({{RUNTIME_LABEL}})
|
||||
|
||||
Автоматическая сборка из [main]({{MAIN_REPO_URL}}) — навыки 1С:Предприятие 8.3 для AI-агента **{{PLATFORM_LABEL}}** с рантаймом **{{RUNTIME_LABEL}}**.
|
||||
|
||||
> Эта ветка генерируется CI на каждый push в main. **Не редактируйте напрямую** — все правки идут в [main]({{MAIN_REPO_URL}}).
|
||||
|
||||
## Установка
|
||||
|
||||
1. Скачайте ZIP этой ветки: **Code → Download ZIP** (или `git archive`).
|
||||
2. Распакуйте в корень своего проекта — должна появиться папка `{{PLATFORM_DIR}}/`.
|
||||
3. Запустите {{PLATFORM_LABEL}} из этого проекта — навыки станут доступны.
|
||||
|
||||
## Требования
|
||||
|
||||
{{RUNTIME_REQUIREMENTS}}
|
||||
- **1С:Предприятие 8.3** — для сборки/разборки EPF/ERF и работы с базами.
|
||||
- **Node.js 18+** — для `/web-test`.
|
||||
|
||||
## Документация
|
||||
|
||||
Полные гайды, спецификации и описание навыков — в [main]({{MAIN_REPO_URL}}).
|
||||
|
||||
---
|
||||
|
||||
Source: {{MAIN_REPO_URL}}
|
||||
Build commit: `{{COMMIT_SHA}}`
|
||||
@@ -1,31 +0,0 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
|
||||
"name": "{{PLUGIN_NAME}}",
|
||||
"description": "[Python] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент. Linux/Mac или когда PowerShell недоступен.",
|
||||
"author": {
|
||||
"name": "Nikolay Shirokov"
|
||||
},
|
||||
"homepage": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"repository": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"1c",
|
||||
"1c-dev",
|
||||
"cf",
|
||||
"cfe",
|
||||
"epf",
|
||||
"erf",
|
||||
"metadata",
|
||||
"configuration",
|
||||
"extension",
|
||||
"form",
|
||||
"report",
|
||||
"skd",
|
||||
"data-processor",
|
||||
"mxl",
|
||||
"web-client",
|
||||
"testing",
|
||||
"test-automation"
|
||||
],
|
||||
"skills": "./.claude/skills/"
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"name": "{{PLUGIN_NAME}}",
|
||||
"version": "{{VERSION}}",
|
||||
"description": "[{{RUNTIME_LABEL}}] Навыки для разработки на 1С:Предприятие 8.3 — абстракции над XML-форматами и CLI конфигуратора, плюс глаза и руки для тестирования через веб-клиент.",
|
||||
"author": {
|
||||
"name": "Nikolay Shirokov"
|
||||
},
|
||||
"homepage": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"repository": "https://github.com/Nikolay-Shirokov/cc-1c-skills",
|
||||
"license": "MIT",
|
||||
"keywords": [
|
||||
"1c",
|
||||
"1c-dev",
|
||||
"cf",
|
||||
"cfe",
|
||||
"epf",
|
||||
"erf",
|
||||
"metadata",
|
||||
"configuration",
|
||||
"extension",
|
||||
"form",
|
||||
"report",
|
||||
"skd",
|
||||
"data-processor",
|
||||
"mxl",
|
||||
"web-client",
|
||||
"testing",
|
||||
"test-automation"
|
||||
],
|
||||
"skills": "./.codex/skills/",
|
||||
"interface": {
|
||||
"displayName": "1C Skills ({{RUNTIME_LABEL}})",
|
||||
"shortDescription": "{{SHORT_DESCRIPTION}}",
|
||||
"category": "Development"
|
||||
}
|
||||
}
|
||||
@@ -1,246 +0,0 @@
|
||||
name: Build port branches
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- '.claude/skills/**'
|
||||
- 'scripts/switch.py'
|
||||
- 'requirements.txt'
|
||||
- '.github/templates/README.port.md.tmpl'
|
||||
- '.github/templates/codex-plugin.json.tmpl'
|
||||
- '.github/templates/claude-plugin.json.tmpl'
|
||||
- '.github/workflows/build-ports.yml'
|
||||
- 'LICENSE'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: claude-code
|
||||
runtime: python
|
||||
branch: port-claude-code-py
|
||||
label: Claude Code
|
||||
target_dir: .claude/skills
|
||||
- platform: cursor
|
||||
runtime: powershell
|
||||
branch: port-cursor
|
||||
label: Cursor
|
||||
target_dir: .cursor/skills
|
||||
- platform: cursor
|
||||
runtime: python
|
||||
branch: port-cursor-py
|
||||
label: Cursor
|
||||
target_dir: .cursor/skills
|
||||
- platform: codex
|
||||
runtime: powershell
|
||||
branch: port-codex
|
||||
label: Codex
|
||||
target_dir: .codex/skills
|
||||
- platform: codex
|
||||
runtime: python
|
||||
branch: port-codex-py
|
||||
label: Codex
|
||||
target_dir: .codex/skills
|
||||
- platform: copilot
|
||||
runtime: powershell
|
||||
branch: port-copilot
|
||||
label: GitHub Copilot
|
||||
target_dir: .github/skills
|
||||
- platform: copilot
|
||||
runtime: python
|
||||
branch: port-copilot-py
|
||||
label: GitHub Copilot
|
||||
target_dir: .github/skills
|
||||
- platform: augment
|
||||
runtime: powershell
|
||||
branch: port-augment
|
||||
label: Augment
|
||||
target_dir: .augment/skills
|
||||
- platform: augment
|
||||
runtime: python
|
||||
branch: port-augment-py
|
||||
label: Augment
|
||||
target_dir: .augment/skills
|
||||
- platform: cline
|
||||
runtime: powershell
|
||||
branch: port-cline
|
||||
label: Cline
|
||||
target_dir: .cline/skills
|
||||
- platform: cline
|
||||
runtime: python
|
||||
branch: port-cline-py
|
||||
label: Cline
|
||||
target_dir: .cline/skills
|
||||
- platform: kilo
|
||||
runtime: powershell
|
||||
branch: port-kilo
|
||||
label: Kilo Code
|
||||
target_dir: .kilocode/skills
|
||||
- platform: kilo
|
||||
runtime: python
|
||||
branch: port-kilo-py
|
||||
label: Kilo Code
|
||||
target_dir: .kilocode/skills
|
||||
- platform: kiro
|
||||
runtime: powershell
|
||||
branch: port-kiro
|
||||
label: Kiro
|
||||
target_dir: .kiro/skills
|
||||
- platform: kiro
|
||||
runtime: python
|
||||
branch: port-kiro-py
|
||||
label: Kiro
|
||||
target_dir: .kiro/skills
|
||||
- platform: gemini
|
||||
runtime: powershell
|
||||
branch: port-gemini
|
||||
label: Gemini CLI
|
||||
target_dir: .gemini/skills
|
||||
- platform: gemini
|
||||
runtime: python
|
||||
branch: port-gemini-py
|
||||
label: Gemini CLI
|
||||
target_dir: .gemini/skills
|
||||
- platform: opencode
|
||||
runtime: powershell
|
||||
branch: port-opencode
|
||||
label: OpenCode
|
||||
target_dir: .opencode/skills
|
||||
- platform: opencode
|
||||
runtime: python
|
||||
branch: port-opencode-py
|
||||
label: OpenCode
|
||||
target_dir: .opencode/skills
|
||||
- platform: roo
|
||||
runtime: powershell
|
||||
branch: port-roo
|
||||
label: Roo Code
|
||||
target_dir: .roo/skills
|
||||
- platform: roo
|
||||
runtime: python
|
||||
branch: port-roo-py
|
||||
label: Roo Code
|
||||
target_dir: .roo/skills
|
||||
- platform: windsurf
|
||||
runtime: powershell
|
||||
branch: port-windsurf
|
||||
label: Windsurf
|
||||
target_dir: .windsurf/skills
|
||||
- platform: windsurf
|
||||
runtime: python
|
||||
branch: port-windsurf-py
|
||||
label: Windsurf
|
||||
target_dir: .windsurf/skills
|
||||
- platform: codeassistant
|
||||
runtime: powershell
|
||||
branch: port-codeassistant
|
||||
label: Yandex Code Assistant
|
||||
target_dir: .codeassistant/skills
|
||||
- platform: codeassistant
|
||||
runtime: python
|
||||
branch: port-codeassistant-py
|
||||
label: Yandex Code Assistant
|
||||
target_dir: .codeassistant/skills
|
||||
- platform: agents
|
||||
runtime: powershell
|
||||
branch: port-agents
|
||||
label: Agent Skills
|
||||
target_dir: .agents/skills
|
||||
- platform: agents
|
||||
runtime: python
|
||||
branch: port-agents-py
|
||||
label: Agent Skills
|
||||
target_dir: .agents/skills
|
||||
|
||||
steps:
|
||||
- name: Checkout main
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.11'
|
||||
|
||||
- name: Build skills tree for ${{ matrix.platform }} (${{ matrix.runtime }})
|
||||
run: |
|
||||
python scripts/switch.py "${{ matrix.platform }}" \
|
||||
--project-dir build \
|
||||
--runtime "${{ matrix.runtime }}"
|
||||
|
||||
- name: Render port README
|
||||
env:
|
||||
PLATFORM_LABEL: ${{ matrix.label }}
|
||||
PLATFORM_DIR: ${{ matrix.target_dir }}
|
||||
RUNTIME: ${{ matrix.runtime }}
|
||||
RUNTIME_LABEL: ${{ matrix.runtime == 'powershell' && 'PowerShell' || 'Python' }}
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
MAIN_REPO_URL: https://github.com/${{ github.repository }}
|
||||
run: |
|
||||
if [ "$RUNTIME" = "powershell" ]; then
|
||||
RUNTIME_REQUIREMENTS='- **Windows** с PowerShell 5.1+ (входит в Windows).'
|
||||
else
|
||||
RUNTIME_REQUIREMENTS='- **Python 3.9+**. Установка зависимостей: `pip install -r requirements.txt` (lxml, Pillow, psutil).'
|
||||
fi
|
||||
sed \
|
||||
-e "s|{{PLATFORM_LABEL}}|${PLATFORM_LABEL}|g" \
|
||||
-e "s|{{PLATFORM_DIR}}|${PLATFORM_DIR}|g" \
|
||||
-e "s|{{RUNTIME_LABEL}}|${RUNTIME_LABEL}|g" \
|
||||
-e "s|{{RUNTIME_REQUIREMENTS}}|${RUNTIME_REQUIREMENTS}|g" \
|
||||
-e "s|{{COMMIT_SHA}}|${COMMIT_SHA}|g" \
|
||||
-e "s|{{MAIN_REPO_URL}}|${MAIN_REPO_URL}|g" \
|
||||
.github/templates/README.port.md.tmpl > build/README.md
|
||||
|
||||
- name: Render Codex plugin manifest
|
||||
if: matrix.platform == 'codex'
|
||||
env:
|
||||
PLUGIN_NAME: ${{ matrix.runtime == 'python' && '1c-skills-py' || '1c-skills' }}
|
||||
RUNTIME_LABEL: ${{ matrix.runtime == 'powershell' && 'PowerShell' || 'Python' }}
|
||||
SHORT_DESCRIPTION: ${{ matrix.runtime == 'python' && 'Python runtime (Linux/Mac/Windows)' || 'PowerShell runtime (Windows-first)' }}
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
run: |
|
||||
VERSION="$(date -u +%Y.%-m.%-d)+${COMMIT_SHA::7}"
|
||||
mkdir -p build/.codex-plugin
|
||||
sed \
|
||||
-e "s|{{PLUGIN_NAME}}|${PLUGIN_NAME}|g" \
|
||||
-e "s|{{VERSION}}|${VERSION}|g" \
|
||||
-e "s|{{RUNTIME_LABEL}}|${RUNTIME_LABEL}|g" \
|
||||
-e "s|{{SHORT_DESCRIPTION}}|${SHORT_DESCRIPTION}|g" \
|
||||
.github/templates/codex-plugin.json.tmpl > build/.codex-plugin/plugin.json
|
||||
|
||||
- name: Render Claude plugin manifest (Py variant)
|
||||
if: matrix.platform == 'claude-code' && matrix.runtime == 'python'
|
||||
env:
|
||||
PLUGIN_NAME: 1c-skills-py
|
||||
run: |
|
||||
mkdir -p build/.claude-plugin
|
||||
sed -e "s|{{PLUGIN_NAME}}|${PLUGIN_NAME}|g" \
|
||||
.github/templates/claude-plugin.json.tmpl > build/.claude-plugin/plugin.json
|
||||
|
||||
- name: Copy LICENSE
|
||||
run: cp LICENSE build/LICENSE
|
||||
|
||||
- name: Copy requirements.txt (Python builds only)
|
||||
if: matrix.runtime == 'python'
|
||||
run: cp requirements.txt build/requirements.txt
|
||||
|
||||
- name: Force-push orphan snapshot to ${{ matrix.branch }}
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
cd build
|
||||
git init -q -b master
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add -A
|
||||
git commit -q -m "Auto-build: ${{ matrix.platform }} (${{ matrix.runtime }}) from ${GITHUB_SHA::7}"
|
||||
git push --force \
|
||||
"https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git" \
|
||||
"master:${{ matrix.branch }}"
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
# Реальные выгрузки обработок (примеры, не для версионирования)
|
||||
upload/
|
||||
|
||||
# Результаты сборки
|
||||
build/
|
||||
base/
|
||||
*.epf
|
||||
*.log
|
||||
|
||||
# Временные файлы тестов
|
||||
test-tmp/
|
||||
|
||||
# Локальные настройки Claude Code
|
||||
.claude/settings.local.json
|
||||
|
||||
# Инструменты (portable Apache и т.д.)
|
||||
tools/
|
||||
|
||||
# Отладка навыков (eval, trigger-test, run_loop результаты)
|
||||
debug/
|
||||
|
||||
# Кэш тестов навыков
|
||||
tests/skills/.cache/
|
||||
|
||||
# Python кэш
|
||||
__pycache__/
|
||||
|
||||
# Локальный реестр баз данных 1С
|
||||
.v8-project.json
|
||||
|
||||
# web-test: Node.js зависимости и runtime-артефакты
|
||||
.claude/skills/web-test/scripts/node_modules/
|
||||
.claude/skills/web-test/.browser-session.json
|
||||
|
||||
# Маркер отработавшего prepare() в фикстуре _suite-root
|
||||
tests/web-test/_suite-root/prepare-ran.txt
|
||||
|
||||
# Скриншоты и видео (артефакты тестирования web-test)
|
||||
*.png
|
||||
*.mp4
|
||||
|
||||
# Навыки, скопированные для других AI-платформ (генерируются scripts/switch.py)
|
||||
.agents/skills/
|
||||
.augment/
|
||||
.cline/
|
||||
.codex/
|
||||
.cursor/
|
||||
.gemini/
|
||||
.github/skills/
|
||||
.kilocode/
|
||||
.kiro/
|
||||
.opencode/
|
||||
.roo/
|
||||
.windsurf/
|
||||
debug-templates.txt
|
||||
@@ -24,7 +24,7 @@ allowed-tools:
|
||||
| `NoValidate` | Пропустить авто-валидацию |
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-edit.ps1" -ConfigPath '<path>' -Operation modify-property -Value 'Version=1.0.0.1'
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cf-edit/scripts/cf-edit.ps1" -ConfigPath '<path>' -Operation modify-property -Value 'Version=1.0.0.1'
|
||||
```
|
||||
|
||||
## Операции
|
||||
@@ -34,6 +34,7 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-edit.ps1" -Confi
|
||||
| `modify-property` | `Ключ=Значение` (batch `;;`) | Изменить свойство |
|
||||
| `add-childObject` | `Type.Name` (batch `;;`) | Зарегистрировать уже существующий файл объекта в ChildObjects. Для создания нового объекта используй `/meta-compile`, `/role-compile`, `/subsystem-compile` — они регистрируют автоматически |
|
||||
| `remove-childObject` | `Type.Name` (batch `;;`) | Удалить объект из ChildObjects |
|
||||
| `sort-childObjects` | вид, напр. `Catalog` (batch `;;`), либо пусто | Упорядочить ChildObjects по имени внутри вида. Без значения — все виды, кроме четырёх (см. reference) |
|
||||
| `add-defaultRole` | `Role.Name` или `Name` | Добавить роль по умолчанию |
|
||||
| `remove-defaultRole` | `Role.Name` или `Name` | Удалить роль по умолчанию |
|
||||
| `set-defaultRoles` | Имена через `;;` | Заменить список ролей по умолчанию |
|
||||
@@ -39,6 +39,20 @@
|
||||
|
||||
Batch: `"Catalog.Товары ;; Document.Заказ ;; Enum.ВидыОплат"`
|
||||
|
||||
## sort-childObjects
|
||||
|
||||
Упорядочивает объекты в `<ChildObjects>` по имени **внутри вида**. Значение — имя вида (`Catalog`, `Role`, …), batch через `;;`. Без значения обрабатываются все виды, какие есть в файле.
|
||||
|
||||
```
|
||||
-Operation sort-childObjects — все виды, кроме перечисленных ниже
|
||||
-Operation sort-childObjects -Value "Catalog" — только справочники
|
||||
-Operation sort-childObjects -Value "Catalog ;; Role"
|
||||
```
|
||||
|
||||
Не сортируются, пока вид не назван явно: `CommonAttribute`, `Subsystem`, `CommandGroup`, `Language`.
|
||||
|
||||
Вызов без значения дополнительно ставит группы видов в канонический порядок; вызов с явным видом трогает только имена внутри него.
|
||||
|
||||
## add-defaultRole / remove-defaultRole / set-defaultRoles
|
||||
|
||||
Имя роли: `ПолныеПрава` или `Role.ПолныеПрава` (префикс `Role.` добавляется автоматически).
|
||||
+374
-37
@@ -1,15 +1,80 @@
|
||||
# cf-edit v1.11 — Edit 1C configuration root (Configuration.xml)
|
||||
# cf-edit v1.29 — Edit 1C configuration root (Configuration.xml)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)][Alias('Path')][string]$ConfigPath,
|
||||
[string]$DefinitionFile,
|
||||
[ValidateSet("modify-property","add-childObject","remove-childObject","add-defaultRole","remove-defaultRole","set-defaultRoles","set-panels","set-home-page")]
|
||||
[ValidateSet("modify-property","add-childObject","remove-childObject","add-defaultRole","remove-defaultRole","set-defaultRoles","set-panels","set-home-page","sort-childObjects")]
|
||||
[string]$Operation,
|
||||
[string]$Value,
|
||||
[switch]$NoValidate
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# --- Разбор пользовательского JSON ---
|
||||
# Одна строка в stderr вместо дампа исключения ConvertFrom-Json (issue #80): агент по стектрейсу
|
||||
# идёт чинить скрипт, а не свой вызов. $source — файл или параметр. $expected заполняем только
|
||||
# для полиморфного входа: у файла подсказка была бы наполнителем. -Inline печатает ещё и то,
|
||||
# что доехало: у файла такого вопроса нет — путь назван, позицию дал парсер, файл на диске.
|
||||
# Возврат через -NoEnumerate: без него одноэлементный
|
||||
# JSON-массив разворачивался бы в скаляр вторым анруллингом.
|
||||
function ConvertFrom-JsonInput([string]$text, [string]$source, [string]$expected, [switch]$Inline) {
|
||||
try {
|
||||
# PS 5.1 на пустой строке отдаёт $null, а не ошибку — навык уходил дальше с $null,
|
||||
# тогда как py-порт падал. Проверяем сами, чтобы порты вели себя одинаково.
|
||||
if ([string]::IsNullOrWhiteSpace($text)) { throw 'input is empty' }
|
||||
$parsed = $text | ConvertFrom-Json
|
||||
} catch {
|
||||
$what = if ($expected) { "$source expects $expected" } else { "Invalid JSON in $source" }
|
||||
if ($Inline) {
|
||||
$got = ($text -replace '\s+', ' ').Trim()
|
||||
$label = 'got'
|
||||
if (-not $got) { $got = '(empty)' }
|
||||
elseif ($got.Length -gt 60) { $label = 'got (first 60 chars)'; $got = $got.Substring(0, 60) }
|
||||
$what = "${what}, ${label}: ${got}"
|
||||
}
|
||||
[Console]::Error.WriteLine("[ERROR] ${what} ($($_.Exception.Message))")
|
||||
exit 1
|
||||
}
|
||||
Write-Output -NoEnumerate $parsed
|
||||
}
|
||||
|
||||
# --- Чтение входного JSON-файла ---
|
||||
# Кодировку берём из BOM — это объявление самого файла, а не догадка. Без BOM ждём строгий UTF-8:
|
||||
# Get-Content -Encoding UTF8 на файле в cp1251 тихо меняет кириллицу на U+FFFD, JSON после этого
|
||||
# разбирается успешно, и в конфигурацию уезжает имя из «замен». Кодовую страницу не подбираем:
|
||||
# угаданное имя уйдёт в метаданные так же молча.
|
||||
function Read-JsonInputFile([string]$path) {
|
||||
# Проверка здесь, а не по навыкам: часть навыков проверяла путь сама, часть — нет, и один и тот
|
||||
# же промах давал то внятную строку, то дамп MethodInvocationException. Навыки со своей
|
||||
# проверкой срабатывают раньше и сохраняют свой текст.
|
||||
if (-not (Test-Path -LiteralPath $path)) {
|
||||
[Console]::Error.WriteLine("[ERROR] File not found: $path")
|
||||
exit 1
|
||||
}
|
||||
if (Test-Path -LiteralPath $path -PathType Container) {
|
||||
[Console]::Error.WriteLine("[ERROR] Expected a JSON file, got a directory: $path")
|
||||
exit 1
|
||||
}
|
||||
$bytes = [System.IO.File]::ReadAllBytes($path)
|
||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
|
||||
return [System.Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3)
|
||||
}
|
||||
if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
|
||||
return [System.Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
|
||||
}
|
||||
if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) {
|
||||
return [System.Text.Encoding]::BigEndianUnicode.GetString($bytes, 2, $bytes.Length - 2)
|
||||
}
|
||||
try {
|
||||
return (New-Object System.Text.UTF8Encoding($false, $true)).GetString($bytes)
|
||||
} catch {
|
||||
$detail = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { $_.Exception.Message }
|
||||
[Console]::Error.WriteLine("[ERROR] ${path} is not valid UTF-8: ${detail} - save the file as UTF-8, or add a BOM if it is UTF-16")
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Mode validation ---
|
||||
@@ -163,6 +228,8 @@ function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
||||
Assert-EditAllowed $resolvedPath 'editable'
|
||||
|
||||
# --- Load XML with PreserveWhitespace ---
|
||||
# NB: парсер XML по спецификации схлопывает CRLF в LF, а вставки ниже собираются с
|
||||
# явным CRLF — поэтому EOL приводится к целевому в точке записи (см. финализацию).
|
||||
$script:xmlDoc = New-Object System.Xml.XmlDocument
|
||||
$script:xmlDoc.PreserveWhitespace = $true
|
||||
$script:xmlDoc.Load($resolvedPath)
|
||||
@@ -210,27 +277,27 @@ foreach ($child in $script:propsEl.ChildNodes) {
|
||||
}
|
||||
Info "Configuration: $($script:objName)"
|
||||
|
||||
# --- Canonical type order for ChildObjects (44 types) ---
|
||||
# --- Canonical type order for ChildObjects (46 types) ---
|
||||
$script:typeOrder = @(
|
||||
"Language","Subsystem","StyleItem","Style",
|
||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
||||
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||
"FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
|
||||
"Constant","CommonForm","Catalog","Document",
|
||||
"DocumentNumerator","Sequence","DocumentJournal","Enum",
|
||||
"Report","DataProcessor","InformationRegister","AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
|
||||
"ChartOfCalculationTypes","CalculationRegister",
|
||||
"BusinessProcess","Task","IntegrationService"
|
||||
"BusinessProcess","Task","ExternalDataSource","IntegrationService"
|
||||
)
|
||||
|
||||
# --- Type → on-disk directory name (plural) ---
|
||||
$script:typeToDir = @{
|
||||
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
||||
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"; "CommonTemplate"="CommonTemplates"
|
||||
"FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"; "Bot"="Bots"; "CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"
|
||||
"FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"; "Bot"="Bots"; "PaletteColor"="PaletteColors"; "CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"
|
||||
"XDTOPackage"="XDTOPackages"; "WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
||||
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"; "SettingsStorage"="SettingsStorages"; "FunctionalOption"="FunctionalOptions"
|
||||
"FunctionalOptionsParameter"="FunctionalOptionsParameters"; "DefinedType"="DefinedTypes"; "CommonCommand"="CommonCommands"; "CommandGroup"="CommandGroups"
|
||||
@@ -239,7 +306,7 @@ $script:typeToDir = @{
|
||||
"Report"="Reports"; "DataProcessor"="DataProcessors"; "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
|
||||
"ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"; "ChartOfAccounts"="ChartsOfAccounts"; "AccountingRegister"="AccountingRegisters"
|
||||
"ChartOfCalculationTypes"="ChartsOfCalculationTypes"; "CalculationRegister"="CalculationRegisters"
|
||||
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"; "IntegrationService"="IntegrationServices"
|
||||
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"; "ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
|
||||
}
|
||||
|
||||
# --- XML manipulation helpers (from subsystem-edit pattern) ---
|
||||
@@ -309,6 +376,21 @@ function Import-Fragment([string]$xmlString) {
|
||||
}
|
||||
|
||||
# --- Parse batch value (split by ;;) ---
|
||||
|
||||
# Имя вида из пользовательского ввода → каноническое имя или $null.
|
||||
# Ввод прощающий: регистр не важен, принимается имя каталога выгрузки (Catalogs → Catalog)
|
||||
# и русское имя вида в единственном и множественном числе.
|
||||
function Resolve-TypeName([string]$token) {
|
||||
$key = "$token".Trim()
|
||||
if (-not $key) { return $null }
|
||||
foreach ($canon in $script:typeOrder) { if ($canon -eq $key) { return $canon } }
|
||||
$byDir = $script:dirToType[$key.ToLowerInvariant()]
|
||||
if ($byDir) { return $byDir }
|
||||
$ru = $script:ruTypeMap[$key.ToLowerInvariant()]
|
||||
if ($ru) { return $ru }
|
||||
return $null
|
||||
}
|
||||
|
||||
function Parse-BatchValue([string]$val) {
|
||||
$items = @()
|
||||
foreach ($part in $val.Split(";;")) {
|
||||
@@ -374,6 +456,220 @@ function Do-ModifyProperty([string]$batchVal) {
|
||||
}
|
||||
|
||||
# --- Operation: add-childObject ---
|
||||
# Куда навык ставит новую запись в <ChildObjects> — настройка newObjectPosition.
|
||||
# databases[].newObjectPosition базы, чей configSrc охватывает каталог родительского XML,
|
||||
# иначе корневое поле, иначе end. Значения: end — после последнего объекта того же вида
|
||||
# (так дописывает Конфигуратор); byName — по имени среди объектов того же вида.
|
||||
# Файл ищем от рабочего каталога вверх, каталог конфигурации — запасной путь: так же
|
||||
# его ищут support-guard и группа db-*, а скрипт навыка зовут по абсолютному пути, и cwd
|
||||
# остаётся рабочим каталогом проекта.
|
||||
# configSrc считается от каталога .v8-project.json, как задокументировано в
|
||||
# docs/v8-project-guide.md. Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
function Get-NewObjectPosition([string]$cfgDir) {
|
||||
try {
|
||||
if (-not $cfgDir) { $cfgDir = "." }
|
||||
$pj = Find-V8Project (Get-Location).Path
|
||||
if (-not $pj) { $pj = Find-V8Project ([System.IO.Path]::GetFullPath($cfgDir)) }
|
||||
if (-not $pj) { return "end" }
|
||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
||||
$projDir = [System.IO.Path]::GetDirectoryName($pj)
|
||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
||||
if ($proj.databases) {
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($db.configSrc -and $db.newObjectPosition) {
|
||||
$src = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($projDir, $db.configSrc)).TrimEnd('\', '/')
|
||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
||||
if ("$($db.newObjectPosition)" -eq "byName") { return "byName" }
|
||||
return "end"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ("$($proj.newObjectPosition)" -eq "byName") { return "byName" }
|
||||
return "end"
|
||||
} catch { return "end" }
|
||||
}
|
||||
|
||||
# Виды, у которых порядок в дереве несёт смысл: автоматически их не упорядочиваем.
|
||||
# CommonAttribute — исключение самого стандарта (#std467): у общих реквизитов-разделителей
|
||||
# порядок в дереве задаёт порядок установки параметров сеанса. Subsystem и CommandGroup:
|
||||
# пока они не перечислены в <SubsystemsOrder> / <GroupsOrder> файла Ext/CommandInterface.xml,
|
||||
# порядок дерева задаёт порядок в интерфейсе, а платформа эти списки сама не заводит
|
||||
# (в выгрузке ACC вне GroupsOrder 15 живых групп из 39). Language исключён из осторожности,
|
||||
# без замера: языков обычно один-два, и в типовых их порядок не алфавитный.
|
||||
# Явно названный вид сортируется в любом случае.
|
||||
# Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
function Test-OrderSensitiveType([string]$typeName) {
|
||||
return @("CommonAttribute", "Subsystem", "CommandGroup", "Language") -ccontains $typeName
|
||||
}
|
||||
|
||||
# Порядок имён объектов метаданных, как в дереве Конфигуратора.
|
||||
# Ключ — пары «ранг+символ»: регистр не учитывается, подчёркивание раньше цифр, цифры раньше
|
||||
# букв, буквы по кодам (латиница раньше кириллицы), ё на месте е. Культурные таблицы не
|
||||
# используются — они разные на разных ОС и в разных рантаймах, а так оба порта сравнивают
|
||||
# одинаково везде. Равные ключи разводит ordinal-сравнение исходных строк.
|
||||
# Возвращает -1 | 0 | 1. Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
function Compare-MetadataNames([string]$a, [string]$b) {
|
||||
$keys = @("", "")
|
||||
$names = @($a, $b)
|
||||
for ($i = 0; $i -lt 2; $i++) {
|
||||
$sb = New-Object System.Text.StringBuilder
|
||||
foreach ($ch in $names[$i].ToLowerInvariant().ToCharArray()) {
|
||||
if ($ch -eq [char]0x0451) { $ch = [char]0x0435 }
|
||||
if ([char]::IsDigit($ch)) { [void]$sb.Append('1') }
|
||||
elseif ([char]::IsLetter($ch)) { [void]$sb.Append('2') }
|
||||
else { [void]$sb.Append('0') }
|
||||
[void]$sb.Append($ch)
|
||||
}
|
||||
$keys[$i] = $sb.ToString()
|
||||
}
|
||||
$r = [string]::CompareOrdinal($keys[0], $keys[1])
|
||||
if ($r -eq 0) { $r = [string]::CompareOrdinal($a, $b) }
|
||||
if ($r -lt 0) { return -1 }
|
||||
if ($r -gt 0) { return 1 }
|
||||
return 0
|
||||
}
|
||||
|
||||
# Сортировка имён компаратором Compare-MetadataNames. В py-порту ту же роль играет
|
||||
# functools.cmp_to_key — штатный способ отсортировать компаратором; в PS 5.1 его нет,
|
||||
# поэтому слияние вручную. Порядок обоих портов задаёт один и тот же компаратор.
|
||||
function Sort-MetadataNames([string[]]$names) {
|
||||
# Возврат без запятой-обёртки: приёмная сторона всегда пишет @(...), и одноэлементный
|
||||
# результат остаётся массивом. С `return ,@(...)` @() собрал бы ОДИН объект-массив.
|
||||
if ($names.Count -le 1) { return $names }
|
||||
$mid = [int]($names.Count / 2)
|
||||
$left = @(Sort-MetadataNames $names[0..($mid - 1)])
|
||||
$right = @(Sort-MetadataNames $names[$mid..($names.Count - 1)])
|
||||
$out = New-Object System.Collections.ArrayList
|
||||
$i = 0; $j = 0
|
||||
while ($i -lt $left.Count -and $j -lt $right.Count) {
|
||||
if ((Compare-MetadataNames $left[$i] $right[$j]) -le 0) { [void]$out.Add($left[$i]); $i++ }
|
||||
else { [void]$out.Add($right[$j]); $j++ }
|
||||
}
|
||||
while ($i -lt $left.Count) { [void]$out.Add($left[$i]); $i++ }
|
||||
while ($j -lt $right.Count) { [void]$out.Add($right[$j]); $j++ }
|
||||
return $out.ToArray()
|
||||
}
|
||||
|
||||
# Упорядочить <ChildObjects>: имена внутри вида, а без аргумента — и группы видов.
|
||||
# Виды из Test-OrderSensitiveType по имени не сортируются, пока не названы явно.
|
||||
# Вызов без значения дополнительно ставит группы видов в канонический порядок: платформа
|
||||
# починила бы его только при загрузке-выгрузке, то есть неканоничный файл даёт диф на
|
||||
# ровном месте. Переставляем ЗНАЧЕНИЯ узлов, а не сами узлы — отступы и структура файла
|
||||
# остаются как были, в дифе только перестановка строк.
|
||||
function Do-SortChildObjects([string]$batchVal) {
|
||||
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
|
||||
|
||||
# Ввод прощающий: регистр не важен, принимается и имя каталога (Catalogs → Catalog) —
|
||||
# в дереве выгрузки виды видны именно во множественном числе.
|
||||
# Без @(...) на приёме: Parse-BatchValue возвращает ,$items — обёртка, которую @()
|
||||
# собрал бы как ОДИН объект-массив, и вид не нашёлся бы в $script:typeOrder.
|
||||
$tokens = @()
|
||||
if ("$batchVal".Trim()) { $tokens = Parse-BatchValue $batchVal }
|
||||
$requested = @()
|
||||
foreach ($token in $tokens) {
|
||||
$canon = Resolve-TypeName $token
|
||||
if (-not $canon) { Write-Error "Unknown type '$token'. Valid: $($script:typeOrder -join ', ')"; exit 1 }
|
||||
$requested += $canon
|
||||
}
|
||||
|
||||
$groups = New-Object System.Collections.Specialized.OrderedDictionary
|
||||
foreach ($child in $script:childObjsEl.ChildNodes) {
|
||||
if ($child.NodeType -ne 'Element') { continue }
|
||||
$ln = $child.get_LocalName()
|
||||
if (-not $groups.Contains($ln)) { $groups[$ln] = New-Object System.Collections.ArrayList }
|
||||
[void]$groups[$ln].Add($child)
|
||||
}
|
||||
|
||||
$targets = if ($requested.Count -gt 0) { $requested } else { @($groups.Keys | Where-Object { -not (Test-OrderSensitiveType $_) }) }
|
||||
foreach ($typeName in $targets) {
|
||||
if (-not $groups.Contains($typeName)) { continue }
|
||||
$els = $groups[$typeName]
|
||||
if ($els.Count -lt 2) { continue }
|
||||
$names = @(foreach ($e in $els) { $e.InnerText })
|
||||
$ordered = @(Sort-MetadataNames $names)
|
||||
$same = $true
|
||||
for ($i = 0; $i -lt $names.Count; $i++) { if ($names[$i] -cne $ordered[$i]) { $same = $false; break } }
|
||||
if ($same) { continue }
|
||||
for ($i = 0; $i -lt $els.Count; $i++) { $els[$i].InnerText = $ordered[$i] }
|
||||
$script:modifyCount++
|
||||
Info "Sorted: $typeName ($($els.Count))"
|
||||
}
|
||||
|
||||
if ($requested.Count -gt 0) { return }
|
||||
|
||||
# Без аргумента приводим в порядок и сами группы видов: собранная навыками конфигурация
|
||||
# может держать их не в каноне, и первая же выгрузка платформы даст диф. Переставляем
|
||||
# содержимое существующих узлов, а не узлы, поэтому отступы и структура файла не меняются —
|
||||
# в дифе только перестановка строк. Имя тега у XmlElement неизменяемо, поэтому там, где вид
|
||||
# меняется, узел заменяется через ReplaceChild: он сохраняет окружающие пробельные узлы.
|
||||
$elems = @()
|
||||
foreach ($child in $script:childObjsEl.ChildNodes) {
|
||||
if ($child.NodeType -eq 'Element') { $elems += $child }
|
||||
}
|
||||
$tags = @(); $texts = @()
|
||||
foreach ($e in $elems) { $tags += $e.get_LocalName(); $texts += $e.InnerText }
|
||||
$rank = @()
|
||||
for ($i = 0; $i -lt $tags.Count; $i++) {
|
||||
$r = $script:typeOrder.IndexOf($tags[$i])
|
||||
if ($r -lt 0) { $r = $script:typeOrder.Count }
|
||||
$rank += $r
|
||||
}
|
||||
# Порядок стабильный: вторым ключом идёт исходная позиция
|
||||
$order = @(0..($tags.Count - 1) | Sort-Object @{e={$rank[$_]}}, @{e={$_}})
|
||||
$same = $true
|
||||
for ($i = 0; $i -lt $order.Count; $i++) { if ($order[$i] -ne $i) { $same = $false; break } }
|
||||
if ($same) { return }
|
||||
|
||||
for ($i = 0; $i -lt $elems.Count; $i++) {
|
||||
$srcIdx = $order[$i]
|
||||
if ($tags[$i] -ceq $tags[$srcIdx]) {
|
||||
$elems[$i].InnerText = $texts[$srcIdx]
|
||||
continue
|
||||
}
|
||||
$newEl = $script:xmlDoc.CreateElement($tags[$srcIdx], $script:mdNs)
|
||||
$newEl.InnerText = $texts[$srcIdx]
|
||||
[void]$script:childObjsEl.ReplaceChild($newEl, $elems[$i])
|
||||
}
|
||||
$script:modifyCount++
|
||||
Info "Reordered type groups: $($elems.Count) entries"
|
||||
}
|
||||
|
||||
# Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
||||
# финальный перенос. $null → файл новый (сохранить текущее поведение).
|
||||
# Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
function Detect-XmlStyle([string]$path) {
|
||||
if (-not (Test-Path -LiteralPath $path)) { return $null }
|
||||
$raw = [System.IO.File]::ReadAllBytes($path)
|
||||
$bom = ($raw.Length -ge 3 -and $raw[0] -eq 0xEF -and $raw[1] -eq 0xBB -and $raw[2] -eq 0xBF)
|
||||
$body = if ($bom) { [System.Text.Encoding]::UTF8.GetString($raw, 3, $raw.Length - 3) } else { [System.Text.Encoding]::UTF8.GetString($raw) }
|
||||
$head = if ($body.Length -gt 200) { $body.Substring(0, 200) } else { $body }
|
||||
$m = [regex]::Match($head, 'encoding="([^"]+)"')
|
||||
return @{
|
||||
bom = $bom
|
||||
crlf = $body.Contains("`r`n")
|
||||
enc = $(if ($m.Success) { $m.Groups[1].Value } else { "utf-8" })
|
||||
finalNl = $body.EndsWith("`n")
|
||||
}
|
||||
}
|
||||
|
||||
# Привести текст XmlWriter к стилю оригинала; для НОВОГО файла ($null) — к канону выгрузки
|
||||
# Конфигуратора: encoding="UTF-8", CRLF, без перевода строки в конце.
|
||||
# Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
function Finalize-XmlText([string]$text, $style) {
|
||||
if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
|
||||
$encDecl = $(if ($style) { $style.enc } else { "UTF-8" })
|
||||
$text = $text.Replace('encoding="utf-8"', 'encoding="' + $encDecl + '"')
|
||||
# Пустой элемент: XmlWriter отдаёт `<a />`, Конфигуратор пишет `<a/>`. Внутри
|
||||
# CDATA/комментария ` />` может быть содержимым (там `>` не экранируется),
|
||||
# поэтому они идут первыми ветками альтернации и возвращаются как есть.
|
||||
$text = [regex]::Replace($text, '(?s)<!\[CDATA\[.*?\]\]>|<!--.*?-->|(?<=\S) />', { param($m) if ($m.Value -eq ' />') { '/>' } else { $m.Value } })
|
||||
$text = ($text -replace "`r`n", "`n").TrimEnd("`n")
|
||||
if ($style -and $style.finalNl) { $text += "`n" }
|
||||
if (-not $style -or $style.crlf) { $text = $text -replace "`n", "`r`n" }
|
||||
return $text
|
||||
}
|
||||
|
||||
function Do-AddChildObject([string]$batchVal) {
|
||||
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
|
||||
|
||||
@@ -393,6 +689,8 @@ function Do-AddChildObject([string]$batchVal) {
|
||||
exit 1
|
||||
}
|
||||
$typeName = $item.Substring(0, $dotIdx)
|
||||
$canonType = Resolve-TypeName $typeName
|
||||
if ($canonType) { $typeName = $canonType }
|
||||
$objNameVal = $item.Substring($dotIdx + 1)
|
||||
|
||||
# Check type is valid
|
||||
@@ -437,11 +735,11 @@ To create a new $typeName, use $hintSkill (auto-registers in Configuration.xml):
|
||||
continue
|
||||
}
|
||||
|
||||
# Find insertion point: after last element of same type, or after last element of preceding type
|
||||
# Место вставки. Вид — по $script:typeOrder; внутри вида — по newObjectPosition.
|
||||
$byName = (-not (Test-OrderSensitiveType $typeName) -and (Get-NewObjectPosition $script:configDir) -eq "byName")
|
||||
$insertBefore = $null
|
||||
$lastSameType = $null
|
||||
$lastPrecedingType = $null
|
||||
$currentTypeIdx = -1
|
||||
$firstLaterType = $null
|
||||
|
||||
foreach ($child in $script:childObjsEl.ChildNodes) {
|
||||
if ($child.NodeType -ne 'Element') { continue }
|
||||
@@ -449,17 +747,29 @@ To create a new $typeName, use $hintSkill (auto-registers in Configuration.xml):
|
||||
if ($childTypeIdx -lt 0) { continue }
|
||||
|
||||
if ($child.LocalName -eq $typeName) {
|
||||
# Same type — check alphabetical order
|
||||
if ($child.InnerText -gt $objNameVal -and -not $insertBefore) {
|
||||
# Insert before this element (alphabetical)
|
||||
# Внутри вида — по newObjectPosition: end (по умолчанию) кладёт после последнего
|
||||
# объекта того же вида, byName — по имени. Subsystem по имени не упорядочиваем
|
||||
# никогда: порядок подсистем в дереве задаёт порядок разделов в панели.
|
||||
$lastSameType = $child
|
||||
if ($byName -and -not $insertBefore -and (Compare-MetadataNames $child.InnerText $objNameVal) -gt 0) {
|
||||
$insertBefore = $child
|
||||
}
|
||||
$lastSameType = $child
|
||||
} elseif ($childTypeIdx -lt $typeIdx) {
|
||||
$lastPrecedingType = $child
|
||||
} elseif ($childTypeIdx -gt $typeIdx -and -not $insertBefore) {
|
||||
# First element of a later type — insert before it
|
||||
$insertBefore = $child
|
||||
} elseif ($childTypeIdx -gt $typeIdx -and -not $firstLaterType) {
|
||||
$firstLaterType = $child
|
||||
}
|
||||
}
|
||||
|
||||
if (-not $insertBefore) {
|
||||
# Место не выбрано именем — ставим сразу за последним объектом того же вида,
|
||||
# то есть перед его следующим соседом. Через $firstLaterType этого не сделать:
|
||||
# если видов старше в файле нет, запись уехала бы в самый конец блока,
|
||||
# за пределы своей группы.
|
||||
if ($lastSameType) {
|
||||
$next = $lastSameType.NextSibling
|
||||
while ($next -and $next.NodeType -ne 'Element') { $next = $next.NextSibling }
|
||||
$insertBefore = $next
|
||||
} else {
|
||||
$insertBefore = $firstLaterType
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,6 +801,8 @@ function Do-RemoveChildObject([string]$batchVal) {
|
||||
exit 1
|
||||
}
|
||||
$typeName = $item.Substring(0, $dotIdx)
|
||||
$canonType = Resolve-TypeName $typeName
|
||||
if ($canonType) { $typeName = $canonType }
|
||||
$objNameVal = $item.Substring($dotIdx + 1)
|
||||
|
||||
$found = $false
|
||||
@@ -637,10 +949,7 @@ function Do-SetPanels($valArg) {
|
||||
# Accept string (JSON), PSCustomObject, or hashtable
|
||||
$layout = $valArg
|
||||
if ($layout -is [string]) {
|
||||
try { $layout = $layout | ConvertFrom-Json } catch {
|
||||
Write-Error "set-panels value must be valid JSON object, got: $valArg"
|
||||
exit 1
|
||||
}
|
||||
$layout = ConvertFrom-JsonInput $layout "-Value for operation 'set-panels'" "a JSON object with panel layout" -Inline
|
||||
}
|
||||
if (-not $layout) {
|
||||
Write-Error "set-panels value is empty"
|
||||
@@ -691,7 +1000,9 @@ $bodyBlock$declarations
|
||||
if (-not (Test-Path $extDir)) { New-Item -ItemType Directory -Path $extDir -Force | Out-Null }
|
||||
$caiPath = Join-Path $extDir "ClientApplicationInterface.xml"
|
||||
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText($caiPath, $caiXml, $utf8Bom)
|
||||
# Файл создаём мы — канон: CRLF в разделителях, без перевода строки в конце.
|
||||
$caiXml = ($caiXml -replace "`r`n", "`n") -replace "`n", "`r`n"
|
||||
[System.IO.File]::WriteAllText($caiPath, $caiXml.TrimEnd("`r", "`n"), $utf8Bom)
|
||||
$script:modifyCount++
|
||||
Info "Wrote panel layout: $caiPath"
|
||||
}
|
||||
@@ -721,6 +1032,29 @@ $script:ruTypeMap = @{
|
||||
"бот" = "Bot"
|
||||
"планобмена" = "ExchangePlan"
|
||||
"хранилищенастроек" = "SettingsStorage"
|
||||
# Множественное число: в дереве конфигурации виды подписаны именно так.
|
||||
"справочники" = "Catalog"
|
||||
"документы" = "Document"
|
||||
"перечисления" = "Enum"
|
||||
"отчёты" = "Report"
|
||||
"отчеты" = "Report"
|
||||
"обработки" = "DataProcessor"
|
||||
"общиеформы" = "CommonForm"
|
||||
"журналыдокументов" = "DocumentJournal"
|
||||
"планывидовхарактеристик" = "ChartOfCharacteristicTypes"
|
||||
"планысчетов" = "ChartOfAccounts"
|
||||
"планывидоврасчета" = "ChartOfCalculationTypes"
|
||||
"планывидоврасчёта" = "ChartOfCalculationTypes"
|
||||
"регистрысведений" = "InformationRegister"
|
||||
"регистрынакопления" = "AccumulationRegister"
|
||||
"регистрыбухгалтерии" = "AccountingRegister"
|
||||
"регистрырасчета" = "CalculationRegister"
|
||||
"регистрырасчёта" = "CalculationRegister"
|
||||
"бизнеспроцессы" = "BusinessProcess"
|
||||
"задачи" = "Task"
|
||||
"боты" = "Bot"
|
||||
"планыобмена" = "ExchangePlan"
|
||||
"хранилищанастроек" = "SettingsStorage"
|
||||
}
|
||||
# plural folder → singular type
|
||||
$script:dirToType = @{}
|
||||
@@ -822,9 +1156,7 @@ $indent</Item>
|
||||
function Do-SetHomePage($valArg) {
|
||||
$layout = $valArg
|
||||
if ($layout -is [string]) {
|
||||
try { $layout = $layout | ConvertFrom-Json } catch {
|
||||
Write-Error "set-home-page value must be valid JSON object"; exit 1
|
||||
}
|
||||
$layout = ConvertFrom-JsonInput $layout "-Value for operation 'set-home-page'" "a JSON object with home page layout" -Inline
|
||||
}
|
||||
if (-not $layout) { Write-Error "set-home-page value is empty"; exit 1 }
|
||||
|
||||
@@ -880,7 +1212,9 @@ $rightXml
|
||||
if (-not (Test-Path $extDir)) { New-Item -ItemType Directory -Path $extDir -Force | Out-Null }
|
||||
$hpPath = Join-Path $extDir "HomePageWorkArea.xml"
|
||||
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText($hpPath, $hpXml, $utf8Bom)
|
||||
# Файл создаём мы — канон: CRLF в разделителях, без перевода строки в конце.
|
||||
$hpXml = ($hpXml -replace "`r`n", "`n") -replace "`n", "`r`n"
|
||||
[System.IO.File]::WriteAllText($hpPath, $hpXml.TrimEnd("`r", "`n"), $utf8Bom)
|
||||
$script:modifyCount++
|
||||
Info "Wrote home page layout: $hpPath"
|
||||
}
|
||||
@@ -936,8 +1270,8 @@ if ($DefinitionFile) {
|
||||
if (-not [System.IO.Path]::IsPathRooted($DefinitionFile)) {
|
||||
$DefinitionFile = Join-Path (Get-Location).Path $DefinitionFile
|
||||
}
|
||||
$jsonText = Get-Content -Raw -Encoding UTF8 $DefinitionFile
|
||||
$ops = $jsonText | ConvertFrom-Json
|
||||
$jsonText = Read-JsonInputFile $DefinitionFile
|
||||
$ops = ConvertFrom-JsonInput $jsonText $DefinitionFile
|
||||
if ($ops -is [System.Array]) {
|
||||
foreach ($op in $ops) { $operations += $op }
|
||||
} else {
|
||||
@@ -962,11 +1296,16 @@ foreach ($op in $operations) {
|
||||
"set-defaultRoles" { Do-SetDefaultRoles $opValueStr }
|
||||
"set-panels" { Do-SetPanels $opValue }
|
||||
"set-home-page" { Do-SetHomePage $opValue }
|
||||
"sort-childObjects" { Do-SortChildObjects $opValueStr }
|
||||
default { Write-Error "Unknown operation: $opName"; exit 1 }
|
||||
}
|
||||
}
|
||||
|
||||
# --- Save ---
|
||||
# Стиль исходника снимаем ДО записи: правка чужого файла наследует его BOM/EOL/заголовок
|
||||
# (#44/#46/#47), новый файл получает канон выгрузки. Зеркало _detect_xml_style в py-порту.
|
||||
$xmlStyle = Detect-XmlStyle $resolvedPath
|
||||
|
||||
$settings = New-Object System.Xml.XmlWriterSettings
|
||||
$settings.Encoding = New-Object System.Text.UTF8Encoding($true)
|
||||
$settings.Indent = $false
|
||||
@@ -977,14 +1316,12 @@ $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
|
||||
$script:xmlDoc.Save($writer)
|
||||
$writer.Flush(); $writer.Close()
|
||||
|
||||
$bytes = $memStream.ToArray()
|
||||
$text = [System.Text.Encoding]::UTF8.GetString($memStream.ToArray())
|
||||
$memStream.Close()
|
||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes)
|
||||
if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
|
||||
$text = $text.Replace('encoding="utf-8"', 'encoding="UTF-8"')
|
||||
$text = Finalize-XmlText $text $xmlStyle
|
||||
|
||||
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||
[System.IO.File]::WriteAllText($resolvedPath, $text, $utf8Bom)
|
||||
$writeBom = ($null -eq $xmlStyle) -or $xmlStyle.bom
|
||||
[System.IO.File]::WriteAllText($resolvedPath, $text, (New-Object System.Text.UTF8Encoding($writeBom)))
|
||||
Info "Saved: $resolvedPath"
|
||||
|
||||
# --- Auto-validate ---
|
||||
+376
-59
@@ -1,8 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
# cf-edit v1.11 — Edit 1C configuration root (Configuration.xml)
|
||||
# cf-edit v1.29 — Edit 1C configuration root (Configuration.xml)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -12,6 +13,127 @@ import uuid as _uuid
|
||||
from html import escape as html_escape
|
||||
from lxml import etree
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
|
||||
def parse_json_input(text, source, expected=None, inline=False):
|
||||
"""Разбор пользовательского JSON: одна строка в stderr вместо traceback (issue #80).
|
||||
|
||||
expected заполняем только для полиморфного входа: у файла подсказка
|
||||
была бы наполнителем — имя файла и текст парсера самодостаточны. inline печатает ещё и то,
|
||||
что доехало: у файла такого вопроса нет, он лежит на диске и его видно целиком.
|
||||
|
||||
Импорты внутри тела: копия функции живёт в навыках с разными именами модулей
|
||||
(skd-decompile импортирует json локально как _json), а тело обязано быть одинаковым.
|
||||
"""
|
||||
import json as _pj
|
||||
import sys as _psys
|
||||
try:
|
||||
if not str(text).strip():
|
||||
raise ValueError("input is empty")
|
||||
return _pj.loads(text)
|
||||
except ValueError as exc:
|
||||
what = "%s expects %s" % (source, expected) if expected else "Invalid JSON in %s" % source
|
||||
if inline:
|
||||
got = " ".join(str(text).split())
|
||||
label = "got"
|
||||
if not got:
|
||||
got = "(empty)"
|
||||
elif len(got) > 60:
|
||||
label = "got (first 60 chars)"
|
||||
got = got[:60]
|
||||
what = "%s, %s: %s" % (what, label, got)
|
||||
print("[ERROR] %s (%s)" % (what, exc), file=_psys.stderr)
|
||||
_psys.exit(1)
|
||||
|
||||
|
||||
def read_json_file(path):
|
||||
"""Чтение входного JSON-файла с кодировкой из BOM (issue #80).
|
||||
|
||||
BOM — объявление самого файла, поэтому ему верим; без BOM ждём строгий UTF-8. Кодовую
|
||||
страницу не подбираем: угаданное имя уехало бы в метаданные молча.
|
||||
"""
|
||||
import os as _pos
|
||||
import sys as _psys
|
||||
if not _pos.path.exists(path):
|
||||
print("[ERROR] File not found: %s" % path, file=_psys.stderr)
|
||||
_psys.exit(1)
|
||||
if _pos.path.isdir(path):
|
||||
print("[ERROR] Expected a JSON file, got a directory: %s" % path, file=_psys.stderr)
|
||||
_psys.exit(1)
|
||||
with open(path, "rb") as _fh:
|
||||
data = _fh.read()
|
||||
if data[:3] == b"\xef\xbb\xbf":
|
||||
return data[3:].decode("utf-8")
|
||||
if data[:2] == b"\xff\xfe":
|
||||
return data[2:].decode("utf-16-le")
|
||||
if data[:2] == b"\xfe\xff":
|
||||
return data[2:].decode("utf-16-be")
|
||||
try:
|
||||
return data.decode("utf-8")
|
||||
except UnicodeDecodeError as exc:
|
||||
print("[ERROR] %s is not valid UTF-8: %s - save the file as UTF-8, or add a BOM if it is UTF-16"
|
||||
% (path, exc), file=_psys.stderr)
|
||||
_psys.exit(1)
|
||||
|
||||
|
||||
class CIDict(dict):
|
||||
# Ключи храним КАК ЕСТЬ: часть из них — имена объектов (табличные части, стандартные
|
||||
# реквизиты), они попадают в XML. Регистронезависим только поиск. Порядок вставки
|
||||
# сохраняется — от него зависит порядок эмиссии.
|
||||
def _actual(self, key):
|
||||
if not isinstance(key, str) or dict.__contains__(self, key):
|
||||
return key
|
||||
ci = self.__dict__.get('_ci')
|
||||
if ci is None or len(ci) != len(self):
|
||||
ci = {k.lower(): k for k in self if isinstance(k, str)}
|
||||
self.__dict__['_ci'] = ci
|
||||
return ci.get(key.lower(), key)
|
||||
|
||||
def __getitem__(self, key):
|
||||
return dict.__getitem__(self, self._actual(key))
|
||||
|
||||
def __contains__(self, key):
|
||||
return dict.__contains__(self, self._actual(key))
|
||||
|
||||
def get(self, key, default=None):
|
||||
return dict.get(self, self._actual(key), default)
|
||||
|
||||
def pop(self, key, *default):
|
||||
return dict.pop(self, self._actual(key), *default)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
# запись по ключу, отличающемуся регистром, обновляет существующий, а не плодит дубль
|
||||
dict.__setitem__(self, self._actual(key), value)
|
||||
|
||||
def ci_json(obj):
|
||||
"""Рекурсивно оборачивает разобранный JSON: словари → CIDict, списки обходятся."""
|
||||
if isinstance(obj, dict):
|
||||
return CIDict((k, ci_json(v)) for k, v in obj.items())
|
||||
if isinstance(obj, list):
|
||||
return [ci_json(v) for v in obj]
|
||||
return obj
|
||||
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Support guard (Ext/ParentConfigurations.bin) — see docs/1c-support-state-spec.md
|
||||
@@ -195,27 +317,27 @@ XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
|
||||
V8_NS = "http://v8.1c.ru/8.1/data/core"
|
||||
XS_NS = "http://www.w3.org/2001/XMLSchema"
|
||||
|
||||
# Canonical type order for ChildObjects (44 types)
|
||||
# Canonical type order for ChildObjects (46 types)
|
||||
TYPE_ORDER = [
|
||||
"Language", "Subsystem", "StyleItem", "Style",
|
||||
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
||||
"FilterCriterion", "CommonModule", "Bot", "CommonAttribute", "ExchangePlan",
|
||||
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
|
||||
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
||||
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
||||
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
||||
"FunctionalOptionsParameter", "DefinedType", "Bot", "PaletteColor", "CommonCommand", "CommandGroup",
|
||||
"Constant", "CommonForm", "Catalog", "Document",
|
||||
"DocumentNumerator", "Sequence", "DocumentJournal", "Enum",
|
||||
"Report", "DataProcessor", "InformationRegister", "AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes", "ChartOfAccounts", "AccountingRegister",
|
||||
"ChartOfCalculationTypes", "CalculationRegister",
|
||||
"BusinessProcess", "Task", "IntegrationService",
|
||||
"BusinessProcess", "Task", "ExternalDataSource", "IntegrationService",
|
||||
]
|
||||
|
||||
# Type → on-disk directory name (plural)
|
||||
TYPE_TO_DIR = {
|
||||
"Language": "Languages", "Subsystem": "Subsystems", "StyleItem": "StyleItems", "Style": "Styles",
|
||||
"CommonPicture": "CommonPictures", "SessionParameter": "SessionParameters", "Role": "Roles", "CommonTemplate": "CommonTemplates",
|
||||
"FilterCriterion": "FilterCriteria", "CommonModule": "CommonModules", "Bot": "Bots", "CommonAttribute": "CommonAttributes", "ExchangePlan": "ExchangePlans",
|
||||
"FilterCriterion": "FilterCriteria", "CommonModule": "CommonModules", "Bot": "Bots", "PaletteColor": "PaletteColors", "PaletteColor": "PaletteColors", "CommonAttribute": "CommonAttributes", "ExchangePlan": "ExchangePlans",
|
||||
"XDTOPackage": "XDTOPackages", "WebService": "WebServices", "HTTPService": "HTTPServices", "WSReference": "WSReferences",
|
||||
"EventSubscription": "EventSubscriptions", "ScheduledJob": "ScheduledJobs", "SettingsStorage": "SettingsStorages", "FunctionalOption": "FunctionalOptions",
|
||||
"FunctionalOptionsParameter": "FunctionalOptionsParameters", "DefinedType": "DefinedTypes", "CommonCommand": "CommonCommands", "CommandGroup": "CommandGroups",
|
||||
@@ -224,7 +346,7 @@ TYPE_TO_DIR = {
|
||||
"Report": "Reports", "DataProcessor": "DataProcessors", "InformationRegister": "InformationRegisters", "AccumulationRegister": "AccumulationRegisters",
|
||||
"ChartOfCharacteristicTypes": "ChartsOfCharacteristicTypes", "ChartOfAccounts": "ChartsOfAccounts", "AccountingRegister": "AccountingRegisters",
|
||||
"ChartOfCalculationTypes": "ChartsOfCalculationTypes", "CalculationRegister": "CalculationRegisters",
|
||||
"BusinessProcess": "BusinessProcesses", "Task": "Tasks", "IntegrationService": "IntegrationServices",
|
||||
"BusinessProcess": "BusinessProcesses", "Task": "Tasks", "ExternalDataSource": "ExternalDataSources", "IntegrationService": "IntegrationServices",
|
||||
}
|
||||
|
||||
ML_PROPS = ["Synonym", "BriefInformation", "DetailedInformation", "Copyright", "VendorInformationAddress", "ConfigurationInformationAddress"]
|
||||
@@ -232,6 +354,137 @@ SCALAR_PROPS = ["Name", "Version", "Vendor", "Comment", "NamePrefix", "UpdateCat
|
||||
REF_PROPS = ["DefaultLanguage"]
|
||||
|
||||
|
||||
def get_new_object_position(cfg_dir):
|
||||
"""Куда навык ставит новую запись в <ChildObjects> — настройка newObjectPosition.
|
||||
|
||||
databases[].newObjectPosition базы, чей configSrc охватывает каталог родительского XML,
|
||||
иначе корневое поле, иначе end. Значения: end — после последнего объекта того же вида
|
||||
(так дописывает Конфигуратор); byName — по имени среди объектов того же вида.
|
||||
Файл ищем от рабочего каталога вверх, каталог конфигурации — запасной путь: так же
|
||||
его ищут support-guard и группа db-*, а скрипт навыка зовут по абсолютному пути, и cwd
|
||||
остаётся рабочим каталогом проекта.
|
||||
configSrc считается от каталога .v8-project.json, как задокументировано в
|
||||
docs/v8-project-guide.md. Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
"""
|
||||
try:
|
||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(os.path.abspath(cfg_dir or "."))
|
||||
if not pj:
|
||||
return "end"
|
||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
||||
proj_dir = os.path.dirname(pj)
|
||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir or ".")).rstrip("\\/")
|
||||
for db in proj.get("databases", []):
|
||||
src = db.get("configSrc")
|
||||
if src and db.get("newObjectPosition"):
|
||||
src_full = os.path.normcase(os.path.abspath(os.path.join(proj_dir, src))).rstrip("\\/")
|
||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
||||
return "byName" if str(db["newObjectPosition"]).lower() == "byname" else "end"
|
||||
if str(proj.get("newObjectPosition") or "").lower() == "byname":
|
||||
return "byName"
|
||||
return "end"
|
||||
except Exception:
|
||||
return "end"
|
||||
|
||||
|
||||
def is_order_sensitive_type(type_name):
|
||||
"""Виды, у которых порядок в дереве несёт смысл: автоматически их не упорядочиваем.
|
||||
|
||||
CommonAttribute — исключение самого стандарта (#std467): у общих реквизитов-разделителей
|
||||
порядок в дереве задаёт порядок установки параметров сеанса. Subsystem и CommandGroup:
|
||||
пока они не перечислены в <SubsystemsOrder> / <GroupsOrder> файла Ext/CommandInterface.xml,
|
||||
порядок дерева задаёт порядок в интерфейсе, а платформа эти списки сама не заводит
|
||||
(в выгрузке ACC вне GroupsOrder 15 живых групп из 39). Language исключён из осторожности,
|
||||
без замера: языков обычно один-два, и в типовых их порядок не алфавитный.
|
||||
Явно названный вид сортируется в любом случае.
|
||||
Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
"""
|
||||
return type_name in ("CommonAttribute", "Subsystem", "CommandGroup", "Language")
|
||||
|
||||
|
||||
def compare_metadata_names(a, b):
|
||||
"""Порядок имён объектов метаданных, как в дереве Конфигуратора.
|
||||
|
||||
Ключ — пары «ранг+символ»: регистр не учитывается, подчёркивание раньше цифр, цифры раньше
|
||||
букв, буквы по кодам (латиница раньше кириллицы), ё на месте е. Культурные таблицы не
|
||||
используются — они разные на разных ОС и в разных рантаймах, а так оба порта сравнивают
|
||||
одинаково везде. Равные ключи разводит ordinal-сравнение исходных строк.
|
||||
Возвращает -1 | 0 | 1. Реестр семьи: tests/skills/check-inline-drift.mjs.
|
||||
"""
|
||||
keys = []
|
||||
for name in (a, b):
|
||||
parts = []
|
||||
for ch in name.lower():
|
||||
if ch == "ё":
|
||||
ch = "е"
|
||||
if ch.isdigit():
|
||||
parts.append("1" + ch)
|
||||
elif ch.isalpha():
|
||||
parts.append("2" + ch)
|
||||
else:
|
||||
parts.append("0" + ch)
|
||||
keys.append("".join(parts))
|
||||
if keys[0] != keys[1]:
|
||||
return -1 if keys[0] < keys[1] else 1
|
||||
if a != b:
|
||||
return -1 if a < b else 1
|
||||
return 0
|
||||
|
||||
|
||||
RU_TYPE_MAP = {
|
||||
"справочник": "Catalog", "документ": "Document", "перечисление": "Enum",
|
||||
"отчёт": "Report", "отчет": "Report", "обработка": "DataProcessor",
|
||||
"общаяформа": "CommonForm", "журналдокументов": "DocumentJournal",
|
||||
"планвидовхарактеристик": "ChartOfCharacteristicTypes",
|
||||
"плансчетов": "ChartOfAccounts",
|
||||
"планвидоврасчета": "ChartOfCalculationTypes",
|
||||
"планвидоврасчёта": "ChartOfCalculationTypes",
|
||||
"регистрсведений": "InformationRegister",
|
||||
"регистрнакопления": "AccumulationRegister",
|
||||
"регистрбухгалтерии": "AccountingRegister",
|
||||
"регистррасчета": "CalculationRegister",
|
||||
"регистррасчёта": "CalculationRegister",
|
||||
"бизнеспроцесс": "BusinessProcess",
|
||||
"бот": "Bot",
|
||||
"задача": "Task", "планобмена": "ExchangePlan",
|
||||
"хранилищенастроек": "SettingsStorage",
|
||||
# Множественное число: в дереве конфигурации виды подписаны именно так.
|
||||
"справочники": "Catalog", "документы": "Document", "перечисления": "Enum",
|
||||
"отчёты": "Report", "отчеты": "Report", "обработки": "DataProcessor",
|
||||
"общиеформы": "CommonForm", "журналыдокументов": "DocumentJournal",
|
||||
"планывидовхарактеристик": "ChartOfCharacteristicTypes",
|
||||
"планысчетов": "ChartOfAccounts",
|
||||
"планывидоврасчета": "ChartOfCalculationTypes",
|
||||
"планывидоврасчёта": "ChartOfCalculationTypes",
|
||||
"регистрысведений": "InformationRegister",
|
||||
"регистрынакопления": "AccumulationRegister",
|
||||
"регистрыбухгалтерии": "AccountingRegister",
|
||||
"регистррасчета": "CalculationRegister", "регистрырасчета": "CalculationRegister",
|
||||
"регистрырасчёта": "CalculationRegister",
|
||||
"бизнеспроцессы": "BusinessProcess",
|
||||
"боты": "Bot",
|
||||
"задачи": "Task", "планыобмена": "ExchangePlan",
|
||||
"хранилищанастроек": "SettingsStorage",
|
||||
}
|
||||
|
||||
|
||||
def resolve_type_name(token):
|
||||
"""Имя вида из пользовательского ввода → каноническое имя или None.
|
||||
|
||||
Ввод прощающий: регистр не важен, принимается имя каталога выгрузки
|
||||
(Catalogs → Catalog) и русское имя вида в единственном и множественном числе.
|
||||
"""
|
||||
key = (token or "").strip().lower()
|
||||
if not key:
|
||||
return None
|
||||
for canon in TYPE_ORDER:
|
||||
if canon.lower() == key:
|
||||
return canon
|
||||
for canon, dir_name in TYPE_TO_DIR.items():
|
||||
if dir_name.lower() == key:
|
||||
return canon
|
||||
return RU_TYPE_MAP.get(key)
|
||||
|
||||
|
||||
def localname(el):
|
||||
return etree.QName(el.tag).localname
|
||||
|
||||
@@ -341,21 +594,22 @@ def _detect_xml_style(path):
|
||||
|
||||
|
||||
def _finalize_xml_bytes(xml_bytes, style):
|
||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
||||
enc_decl = style["enc"] if style else "utf-8"
|
||||
"""Привести байты к стилю оригинала; для НОВОГО файла (style is None) — к канону
|
||||
выгрузки Конфигуратора: encoding="UTF-8", CRLF в разделителях, без перевода в конце."""
|
||||
enc_decl = style["enc"] if style else "UTF-8"
|
||||
xml_bytes = xml_bytes.replace(
|
||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
||||
want_final_nl = style["final_nl"] if style else True
|
||||
# Финальный перенос — как в оригинале (новый файл → нет, канон #57)
|
||||
want_final_nl = style["final_nl"] if style else False
|
||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
||||
if want_final_nl:
|
||||
xml_bytes += b"\n"
|
||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
||||
if style and style["crlf"]:
|
||||
# EOL — как в оригинале (новый файл → CRLF, канон #57)
|
||||
if (style["crlf"] if style else True):
|
||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
||||
return xml_bytes
|
||||
|
||||
@@ -376,10 +630,10 @@ def main():
|
||||
parser = argparse.ArgumentParser(description="Edit 1C configuration root (Configuration.xml)", allow_abbrev=False)
|
||||
parser.add_argument("-ConfigPath", "-Path", required=True)
|
||||
parser.add_argument("-DefinitionFile", default=None)
|
||||
parser.add_argument("-Operation", default=None, choices=["modify-property", "add-childObject", "remove-childObject", "add-defaultRole", "remove-defaultRole", "set-defaultRoles", "set-panels", "set-home-page"])
|
||||
parser.add_argument("-Operation", default=None, choices=["modify-property", "add-childObject", "remove-childObject", "add-defaultRole", "remove-defaultRole", "set-defaultRoles", "set-panels", "set-home-page", "sort-childObjects"])
|
||||
parser.add_argument("-Value", default=None)
|
||||
parser.add_argument("-NoValidate", action="store_true")
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
if args.DefinitionFile and args.Operation:
|
||||
print("Cannot use both -DefinitionFile and -Operation", file=sys.stderr)
|
||||
@@ -515,7 +769,7 @@ def main():
|
||||
if dot_idx < 1:
|
||||
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
type_name = item[:dot_idx]
|
||||
type_name = resolve_type_name(item[:dot_idx]) or item[:dot_idx]
|
||||
obj_name_val = item[dot_idx + 1:]
|
||||
|
||||
if type_name not in TYPE_ORDER:
|
||||
@@ -552,8 +806,15 @@ def main():
|
||||
warn(f"Already exists: {type_name}.{obj_name_val}")
|
||||
continue
|
||||
|
||||
# Find insertion point
|
||||
# Место вставки. Вид — по TYPE_ORDER; внутри вида — по newObjectPosition:
|
||||
# end (по умолчанию) кладёт после последнего объекта того же вида, byName — по имени.
|
||||
# Subsystem по имени не упорядочиваем никогда: порядок подсистем в дереве задаёт
|
||||
# порядок разделов в панели, пока их не перечислили в <SubsystemsOrder>.
|
||||
by_name = (not is_order_sensitive_type(type_name)
|
||||
and get_new_object_position(config_dir) == "byName")
|
||||
insert_before = None
|
||||
last_same = None
|
||||
first_later = None
|
||||
for child in child_objs_el:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
@@ -563,10 +824,24 @@ def main():
|
||||
child_type_idx = TYPE_ORDER.index(child_type_name)
|
||||
|
||||
if child_type_name == type_name:
|
||||
if (child.text or "") > obj_name_val and insert_before is None:
|
||||
last_same = child
|
||||
if (by_name and insert_before is None
|
||||
and compare_metadata_names(child.text or "", obj_name_val) > 0):
|
||||
insert_before = child
|
||||
elif child_type_idx > type_idx and insert_before is None:
|
||||
insert_before = child
|
||||
elif child_type_idx > type_idx and first_later is None:
|
||||
first_later = child
|
||||
|
||||
if insert_before is None:
|
||||
# Место не выбрано именем — ставим сразу за последним объектом того же вида,
|
||||
# то есть перед его следующим соседом. Через first_later этого не сделать:
|
||||
# если видов старше в файле нет, запись уехала бы в самый конец блока,
|
||||
# за пределы своей группы.
|
||||
if last_same is not None:
|
||||
siblings = [c for c in child_objs_el if isinstance(c.tag, str)]
|
||||
pos = siblings.index(last_same)
|
||||
insert_before = siblings[pos + 1] if pos + 1 < len(siblings) else None
|
||||
else:
|
||||
insert_before = first_later
|
||||
|
||||
new_el = etree.Element(f"{{{MD_NS}}}{type_name}")
|
||||
new_el.text = obj_name_val
|
||||
@@ -579,6 +854,69 @@ def main():
|
||||
add_count += 1
|
||||
info(f"Added: {type_name}.{obj_name_val}")
|
||||
|
||||
def do_sort_child_objects(batch_val):
|
||||
"""Упорядочить <ChildObjects>: имена внутри вида, а без аргумента — и группы видов.
|
||||
|
||||
Виды из is_order_sensitive_type по имени не сортируются, пока не названы явно.
|
||||
Вызов без значения дополнительно ставит группы видов в канонический порядок: платформа
|
||||
починила бы его только при загрузке-выгрузке, то есть неканоничный файл даёт диф на
|
||||
ровном месте. Переставляем ЗНАЧЕНИЯ узлов, а не сами узлы — отступы и структура файла
|
||||
остаются как были, в дифе только перестановка строк.
|
||||
"""
|
||||
nonlocal modify_count
|
||||
if child_objs_el is None:
|
||||
print("No <ChildObjects> element found", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
requested = []
|
||||
for token in (parse_batch_value(batch_val) if str(batch_val or "").strip() else []):
|
||||
canon = resolve_type_name(token)
|
||||
if canon is None:
|
||||
print(f"Unknown type '{token}'. Valid: {', '.join(TYPE_ORDER)}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
requested.append(canon)
|
||||
|
||||
groups = {}
|
||||
for child in child_objs_el:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
groups.setdefault(localname(child), []).append(child)
|
||||
|
||||
targets = requested or [t for t in groups if not is_order_sensitive_type(t)]
|
||||
for type_name in targets:
|
||||
els = groups.get(type_name, [])
|
||||
if len(els) < 2:
|
||||
continue
|
||||
names = [e.text or "" for e in els]
|
||||
ordered = sorted(names, key=functools.cmp_to_key(compare_metadata_names))
|
||||
if names == ordered:
|
||||
continue
|
||||
for el, name in zip(els, ordered):
|
||||
el.text = name
|
||||
modify_count += 1
|
||||
info(f"Sorted: {type_name} ({len(els)})")
|
||||
|
||||
if requested:
|
||||
# Вид назван явно — точечная операция: взаимный порядок групп не трогаем.
|
||||
return
|
||||
|
||||
# Без аргумента приводим в порядок и сами группы видов: собранная навыками
|
||||
# конфигурация может держать их не в каноне, и первая же выгрузка платформы даст
|
||||
# диф. Переставляем содержимое существующих узлов, а не узлы, поэтому отступы и
|
||||
# структура файла не меняются — в дифе только перестановка строк.
|
||||
elems = [c for c in child_objs_el if isinstance(c.tag, str)]
|
||||
pairs = [(localname(c), c.text or "") for c in elems]
|
||||
ranked = sorted(range(len(pairs)),
|
||||
key=lambda i: (TYPE_ORDER.index(pairs[i][0]) if pairs[i][0] in TYPE_ORDER else len(TYPE_ORDER), i))
|
||||
wanted = [pairs[i] for i in ranked]
|
||||
if wanted == pairs:
|
||||
return
|
||||
for el, (tag, text) in zip(elems, wanted):
|
||||
el.tag = f'{{{MD_NS}}}{tag}'
|
||||
el.text = text
|
||||
modify_count += 1
|
||||
info(f"Reordered type groups: {len(elems)} entries")
|
||||
|
||||
def do_remove_child_object(batch_val):
|
||||
nonlocal remove_count
|
||||
if child_objs_el is None:
|
||||
@@ -591,7 +929,7 @@ def main():
|
||||
if dot_idx < 1:
|
||||
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
type_name = item[:dot_idx]
|
||||
type_name = resolve_type_name(item[:dot_idx]) or item[:dot_idx]
|
||||
obj_name_val = item[dot_idx + 1:]
|
||||
|
||||
found = False
|
||||
@@ -761,11 +1099,8 @@ def main():
|
||||
nonlocal modify_count
|
||||
layout = value
|
||||
if isinstance(layout, str):
|
||||
try:
|
||||
layout = json.loads(layout)
|
||||
except json.JSONDecodeError:
|
||||
print(f"set-panels value must be valid JSON object", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
layout = ci_json(parse_json_input(
|
||||
layout, "-Value for operation 'set-panels'", "a JSON object with panel layout", inline=True))
|
||||
if not isinstance(layout, dict) or not layout:
|
||||
print("set-panels value must be non-empty object", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -814,24 +1149,6 @@ def main():
|
||||
info(f"Wrote panel layout: {cai_path}")
|
||||
|
||||
# --- set-home-page (writes Ext/HomePageWorkArea.xml from scratch) ---
|
||||
RU_TYPE_MAP = {
|
||||
"справочник": "Catalog", "документ": "Document", "перечисление": "Enum",
|
||||
"отчёт": "Report", "отчет": "Report", "обработка": "DataProcessor",
|
||||
"общаяформа": "CommonForm", "журналдокументов": "DocumentJournal",
|
||||
"планвидовхарактеристик": "ChartOfCharacteristicTypes",
|
||||
"плансчетов": "ChartOfAccounts",
|
||||
"планвидоврасчета": "ChartOfCalculationTypes",
|
||||
"планвидоврасчёта": "ChartOfCalculationTypes",
|
||||
"регистрсведений": "InformationRegister",
|
||||
"регистрнакопления": "AccumulationRegister",
|
||||
"регистрбухгалтерии": "AccountingRegister",
|
||||
"регистррасчета": "CalculationRegister",
|
||||
"регистррасчёта": "CalculationRegister",
|
||||
"бизнеспроцесс": "BusinessProcess",
|
||||
"бот": "Bot",
|
||||
"задача": "Task", "планобмена": "ExchangePlan",
|
||||
"хранилищенастроек": "SettingsStorage",
|
||||
}
|
||||
DIR_TO_TYPE = {v.lower(): k for k, v in TYPE_TO_DIR.items()}
|
||||
UUID_RE = __import__("re").compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
|
||||
@@ -916,11 +1233,8 @@ def main():
|
||||
nonlocal modify_count
|
||||
layout = value
|
||||
if isinstance(layout, str):
|
||||
try:
|
||||
layout = json.loads(layout)
|
||||
except json.JSONDecodeError:
|
||||
print("set-home-page value must be valid JSON object", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
layout = ci_json(parse_json_input(
|
||||
layout, "-Value for operation 'set-home-page'", "a JSON object with home page layout", inline=True))
|
||||
if not isinstance(layout, dict) or not layout:
|
||||
print("set-home-page value must be non-empty object", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -984,8 +1298,7 @@ def main():
|
||||
def_file = args.DefinitionFile
|
||||
if not os.path.isabs(def_file):
|
||||
def_file = os.path.join(os.getcwd(), def_file)
|
||||
with open(def_file, "r", encoding="utf-8-sig") as fh:
|
||||
ops = json.loads(fh.read())
|
||||
ops = ci_json(parse_json_input(read_json_file(def_file), def_file))
|
||||
if isinstance(ops, list):
|
||||
operations = ops
|
||||
else:
|
||||
@@ -995,24 +1308,28 @@ def main():
|
||||
|
||||
for op in operations:
|
||||
op_name = op.get("operation", args.Operation or "")
|
||||
# PS сравнивает имя операции через switch, а он регистронезависим.
|
||||
op_key = str(op_name).lower()
|
||||
op_value = op.get("value", args.Value or "")
|
||||
|
||||
if op_name == "modify-property":
|
||||
if op_key == "modify-property":
|
||||
do_modify_property(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "add-childObject":
|
||||
elif op_key == "add-childobject":
|
||||
do_add_child_object(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "remove-childObject":
|
||||
elif op_key == "remove-childobject":
|
||||
do_remove_child_object(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "add-defaultRole":
|
||||
elif op_key == "add-defaultrole":
|
||||
do_add_default_role(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "remove-defaultRole":
|
||||
elif op_key == "remove-defaultrole":
|
||||
do_remove_default_role(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "set-defaultRoles":
|
||||
elif op_key == "set-defaultroles":
|
||||
do_set_default_roles(op_value if isinstance(op_value, str) else str(op_value))
|
||||
elif op_name == "set-panels":
|
||||
elif op_key == "set-panels":
|
||||
do_set_panels(op_value)
|
||||
elif op_name == "set-home-page":
|
||||
elif op_key == "set-home-page":
|
||||
do_set_home_page(op_value)
|
||||
elif op_key == "sort-childobjects":
|
||||
do_sort_child_objects(op_value if isinstance(op_value, str) else str(op_value))
|
||||
else:
|
||||
print(f"Unknown operation: {op_name}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -23,7 +23,7 @@ allowed-tools:
|
||||
| `OutFile` | Записать результат в файл (UTF-8 BOM) |
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-info.ps1" -ConfigPath "<путь>"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cf-info/scripts/cf-info.ps1" -ConfigPath "<путь>"
|
||||
```
|
||||
|
||||
## Три режима
|
||||
+8
-7
@@ -1,7 +1,8 @@
|
||||
# cf-info v1.4 — Compact summary of 1C configuration root
|
||||
# cf-info v1.9 — Compact summary of 1C configuration root
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][Alias('Path')][string]$ConfigPath,
|
||||
[Parameter(Mandatory=$true, Position=0)][Alias('Path')][string]$ConfigPath,
|
||||
[ValidateSet("overview","brief","full")]
|
||||
[string]$Mode = "overview",
|
||||
[Alias('Name')]
|
||||
@@ -85,20 +86,20 @@ function Get-PropML([string]$propName) {
|
||||
return (Get-MLText $n)
|
||||
}
|
||||
|
||||
# --- Type name maps (canonical order, 44 types) ---
|
||||
# --- Type name maps (canonical order, 46 types) ---
|
||||
$typeOrder = @(
|
||||
"Language","Subsystem","StyleItem","Style",
|
||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
||||
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||
"FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
|
||||
"Constant","CommonForm","Catalog","Document",
|
||||
"DocumentNumerator","Sequence","DocumentJournal","Enum",
|
||||
"Report","DataProcessor","InformationRegister","AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
|
||||
"ChartOfCalculationTypes","CalculationRegister",
|
||||
"BusinessProcess","Task","IntegrationService"
|
||||
"BusinessProcess","Task","ExternalDataSource","IntegrationService"
|
||||
)
|
||||
|
||||
$typeRuNames = @{
|
||||
@@ -119,7 +120,7 @@ $typeRuNames = @{
|
||||
"ChartOfCharacteristicTypes"="ПВХ"; "ChartOfAccounts"="Планы счетов"
|
||||
"AccountingRegister"="Регистры бухгалтерии"; "ChartOfCalculationTypes"="ПВР"
|
||||
"CalculationRegister"="Регистры расчёта"; "BusinessProcess"="Бизнес-процессы"
|
||||
"Task"="Задачи"; "IntegrationService"="Сервисы интеграции"
|
||||
"Task"="Задачи"; "ExternalDataSource"="Внешние источники данных"; "IntegrationService"="Сервисы интеграции"
|
||||
}
|
||||
|
||||
# --- Read panel layout (Ext/ClientApplicationInterface.xml) ---
|
||||
+33
-11
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# cf-info v1.4 — Compact summary of 1C configuration root
|
||||
# cf-info v1.9 — Compact summary of 1C configuration root
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -12,6 +12,28 @@ from lxml import etree
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
# --- Argument parsing ---
|
||||
parser = argparse.ArgumentParser(description="Analyze 1C configuration structure", allow_abbrev=False)
|
||||
parser.add_argument("-ConfigPath", "-Path", required=True, help="Path to Configuration.xml or directory")
|
||||
@@ -20,7 +42,7 @@ parser.add_argument("-Section", "-Name", choices=["home-page"], default=None, he
|
||||
parser.add_argument("-Limit", type=int, default=150, help="Max lines to show")
|
||||
parser.add_argument("-Offset", type=int, default=0, help="Lines to skip")
|
||||
parser.add_argument("-OutFile", default="", help="Write output to file")
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
# --- Output helper (collect all, paginate at the end) ---
|
||||
lines_buf = []
|
||||
@@ -39,11 +61,11 @@ if os.path.isdir(config_path):
|
||||
if os.path.isfile(candidate):
|
||||
config_path = candidate
|
||||
else:
|
||||
print(f"[ERROR] No Configuration.xml found in directory: {config_path}", file=sys.stderr)
|
||||
print(f"[ERROR] No Configuration.xml found in directory: {config_path}")
|
||||
sys.exit(1)
|
||||
|
||||
if not os.path.isfile(config_path):
|
||||
print(f"[ERROR] File not found: {config_path}", file=sys.stderr)
|
||||
print(f"[ERROR] File not found: {config_path}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Load XML ---
|
||||
@@ -60,12 +82,12 @@ NS = {
|
||||
|
||||
md_root = xml_root # root is MetaDataObject itself
|
||||
if etree.QName(md_root.tag).localname != "MetaDataObject":
|
||||
print("[ERROR] Not a valid 1C metadata XML file (no MetaDataObject root)", file=sys.stderr)
|
||||
print("[ERROR] Not a valid 1C metadata XML file (no MetaDataObject root)")
|
||||
sys.exit(1)
|
||||
|
||||
cfg_node = md_root.find("md:Configuration", NS)
|
||||
if cfg_node is None:
|
||||
print("[ERROR] No <Configuration> element found", file=sys.stderr)
|
||||
print("[ERROR] No <Configuration> element found")
|
||||
sys.exit(1)
|
||||
|
||||
version = md_root.get("version", "")
|
||||
@@ -91,20 +113,20 @@ def get_prop_ml(prop_name):
|
||||
n = props_node.find(f"md:{prop_name}", NS)
|
||||
return get_ml_text(n)
|
||||
|
||||
# --- Type name maps (canonical order, 44 types) ---
|
||||
# --- Type name maps (canonical order, 46 types) ---
|
||||
type_order = [
|
||||
"Language", "Subsystem", "StyleItem", "Style",
|
||||
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
||||
"FilterCriterion", "CommonModule", "Bot", "CommonAttribute", "ExchangePlan",
|
||||
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
|
||||
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
||||
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
||||
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
||||
"FunctionalOptionsParameter", "DefinedType", "Bot", "PaletteColor", "CommonCommand", "CommandGroup",
|
||||
"Constant", "CommonForm", "Catalog", "Document",
|
||||
"DocumentNumerator", "Sequence", "DocumentJournal", "Enum",
|
||||
"Report", "DataProcessor", "InformationRegister", "AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes", "ChartOfAccounts", "AccountingRegister",
|
||||
"ChartOfCalculationTypes", "CalculationRegister",
|
||||
"BusinessProcess", "Task", "IntegrationService",
|
||||
"BusinessProcess", "Task", "ExternalDataSource", "IntegrationService",
|
||||
]
|
||||
|
||||
type_ru_names = {
|
||||
@@ -125,7 +147,7 @@ type_ru_names = {
|
||||
"ChartOfCharacteristicTypes": "ПВХ", "ChartOfAccounts": "Планы счетов",
|
||||
"AccountingRegister": "Регистры бухгалтерии", "ChartOfCalculationTypes": "ПВР",
|
||||
"CalculationRegister": "Регистры расчёта", "BusinessProcess": "Бизнес-процессы",
|
||||
"Task": "Задачи", "IntegrationService": "Сервисы интеграции",
|
||||
"Task": "Задачи", "ExternalDataSource": "Внешние источники данных", "IntegrationService": "Сервисы интеграции",
|
||||
}
|
||||
|
||||
# --- Read panel layout (Ext/ClientApplicationInterface.xml) ---
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
name: cf-init
|
||||
description: Создать пустую конфигурацию 1С (scaffold XML-исходников). Используй когда нужно начать новую конфигурацию с нуля
|
||||
argument-hint: <Name> [-Synonym <name>] [-OutputDir src]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /cf-init — Создание пустой конфигурации 1С
|
||||
|
||||
Создаёт scaffold исходников пустой конфигурации 1С: `Configuration.xml`, `Languages/Русский.xml`.
|
||||
|
||||
## Параметры и команда
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `Name` | Имя конфигурации (обязат.) |
|
||||
| `Synonym` | Синоним (= Name если не указан) |
|
||||
| `OutputDir` | Каталог для создания (default: `src`) |
|
||||
| `Version` | Версия конфигурации |
|
||||
| `Vendor` | Поставщик |
|
||||
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
||||
| `FormatVersion` | Версия формата выгрузки (default: `2.17`) |
|
||||
|
||||
Оба параметра задаются от **целевой платформы** — той, на которой конфигурация будет работать, — но по
|
||||
разным правилам.
|
||||
|
||||
`FormatVersion` — **не выше** версии формата целевой платформы: 8.3.24 — `2.17`, 8.3.25 — `2.18`,
|
||||
8.3.26 — `2.19`, 8.3.27 — `2.20`, 8.5 — `2.21`. Ниже брать можно: платформа читает свой формат и любой
|
||||
более старый, поэтому дефолт `2.17` подходит для всей линейки 8.3.24 и выше.
|
||||
|
||||
`CompatibilityMode` влияет на доступную функциональность. Если в задаче не оговорено иное — **равен
|
||||
целевой платформе** (`Version8_3_27` для 8.3.27); это то же самое, что «Не использовать» в
|
||||
Конфигураторе, и именно такое значение платформа проставляет новой базе. Более низкий режим берут
|
||||
осознанно — когда конфигурация должна работать и на старых платформах; он отключает возможности,
|
||||
появившиеся позже. Выше целевой платформы — нельзя: такая конфигурация загрузится, но работать на ней
|
||||
не будет.
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cf-init/scripts/cf-init.ps1" -Name "МояКонфигурация"
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Базовая конфигурация
|
||||
... -Name МояКонфигурация -Synonym "Моя конфигурация" -OutputDir test-tmp/cf
|
||||
|
||||
# С версией и поставщиком
|
||||
... -Name TestCfg -Synonym "Тестовая" -Version "1.0.0.1" -Vendor "Фирма 1С" -OutputDir test-tmp/cf2
|
||||
|
||||
# Под платформу 8.3.27 — версия формата и режим совместимости вместе
|
||||
... -Name TestCfg -FormatVersion 2.20 -CompatibilityMode Version8_3_27 -OutputDir test-tmp/cf3
|
||||
```
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/cf-init TestConfig -OutputDir test-tmp/cf
|
||||
/cf-info test-tmp/cf — проверить созданное
|
||||
/cf-validate test-tmp/cf — валидировать
|
||||
```
|
||||
+106
-20
@@ -1,5 +1,6 @@
|
||||
# cf-init v1.4 — Create empty 1C configuration scaffold
|
||||
# cf-init v1.15 — Create empty 1C configuration scaffold (+write_xml_file/write_utf8_bom: общий эталон записи)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
@@ -9,15 +10,54 @@ param(
|
||||
[string]$Vendor,
|
||||
[string]$CompatibilityMode = "Version8_3_24",
|
||||
# Версия формата выгрузки (MDClasses). Её задаёт ПЛАТФОРМА, которой выгружают, и от режима
|
||||
# совместимости она не зависит: 8.3.20-8.3.24 пишут 2.17, 8.3.25 — 2.18, 8.3.26 — 2.19,
|
||||
# 8.3.27 — 2.20. Дефолт консервативный: 2.17 читается всеми поддерживаемыми платформами.
|
||||
[ValidateSet("2.17", "2.18", "2.19", "2.20", "2.21")]
|
||||
# совместимости она не зависит. Дефолт 2.17 — нижняя граница проверенного диапазона.
|
||||
[string]$FormatVersion = "2.17"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
# --- Format version ---
|
||||
# Проверенный диапазон: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница — docs/1c-configuration-spec.md,
|
||||
# «Лестница версий». Версии ниже 2.17 (платформы 8.3.23 и старше) реальны, поэтому запретом их не
|
||||
# закрываем: за пределами диапазона — ПРЕДУПРЕЖДЕНИЕ, скаффолд всё равно выпускается. Ошибка — только
|
||||
# на нечисловое значение: это опечатка, а не версия.
|
||||
$formatVerifiedMin = "2.17"
|
||||
$formatVerifiedMax = "2.21"
|
||||
# Версия формата как число: "2.20" → 220. Строковое сравнение неверно ("2.9" > "2.17").
|
||||
function Get-FormatRank([string]$ver) {
|
||||
if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
|
||||
return 0
|
||||
}
|
||||
$formatRank = Get-FormatRank $FormatVersion
|
||||
|
||||
function Esc-XmlText {
|
||||
param([string]$s)
|
||||
# Эскейп ТЕКСТА элемента: только & < > — кавычку и апостроф платформа держит сырыми.
|
||||
return $s.Replace('&','&').Replace('<','<').Replace('>','>')
|
||||
}
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# Проверка версии — ПОСЛЕ настройки кодировки консоли: иначе em-dash в сообщении уедет в вопросы.
|
||||
# Пишем прямо в stderr, а не Write-Warning: в PS 5.1 предупреждение уходит в stdout, получает
|
||||
# локализованный префикс и переносится по 80 символов — подстрока в тесте перестаёт находиться.
|
||||
if ($formatRank -eq 0) {
|
||||
[Console]::Error.WriteLine("Malformed -FormatVersion '$FormatVersion' (expected N.N, e.g. 2.17)")
|
||||
exit 1
|
||||
}
|
||||
if ($formatRank -lt (Get-FormatRank $formatVerifiedMin) -or $formatRank -gt (Get-FormatRank $formatVerifiedMax)) {
|
||||
[Console]::Error.WriteLine("WARNING: Format version '$FormatVersion' is outside the tested range $formatVerifiedMin-$formatVerifiedMax — the scaffold is emitted as requested but was not verified on that platform")
|
||||
}
|
||||
|
||||
# «Не использовать» в Конфигураторе хранится как версия ТЕКУЩЕЙ платформы, а не как DontUse:
|
||||
# свежая база получает Version8_3_<своя>, и ни одна типовая в корпусе DontUse не содержит.
|
||||
# Само значение легально — платформа принимает его без ошибок, — но не выживает: замерено на
|
||||
# 8.3.25 и 8.3.27, выгрузка обоих возвращает Version8_3_8. Поэтому предупреждение, а не запрет.
|
||||
# Сравнение регистронезависимо ЯВНО: в PS -eq таков по умолчанию, в py — нет, и молчаливое
|
||||
# расхождение портов началось бы прямо здесь.
|
||||
if ($CompatibilityMode -and $CompatibilityMode.ToLowerInvariant() -eq 'dontuse') {
|
||||
[Console]::Error.WriteLine("WARNING: CompatibilityMode 'DontUse' is not `"no restrictions`" — the platform stores it as Version8_3_8. For no compatibility restrictions use the target platform version (e.g. Version8_3_27 for 8.3.27).")
|
||||
}
|
||||
|
||||
# --- Resolve output dir ---
|
||||
if (-not [System.IO.Path]::IsPathRooted($OutputDir)) {
|
||||
$OutputDir = Join-Path (Get-Location).Path $OutputDir
|
||||
@@ -43,6 +83,11 @@ $co6 = [guid]::NewGuid().ToString()
|
||||
$co7 = [guid]::NewGuid().ToString()
|
||||
|
||||
# --- Mobile functionalities ---
|
||||
# Версия формата как число — по ней ниже включаются вставки 2.21.
|
||||
$is221 = ($formatRank -ge 221)
|
||||
# TextToSpeech приехал раньше остальных вставок 8.5 — своей ступенью, поэтому гейт отдельный.
|
||||
$is218 = ($formatRank -ge 218)
|
||||
|
||||
$mobileFuncs = @(
|
||||
@("Biometrics","true"), @("Location","false"), @("BackgroundLocation","false"),
|
||||
@("BluetoothPrinters","false"), @("WiFiPrinters","false"), @("Contacts","false"),
|
||||
@@ -59,6 +104,12 @@ $mobileFuncs = @(
|
||||
@("DocumentScanning","false"), @("SpeechToText","false"), @("Geofences","false"),
|
||||
@("IncomingShareRequests","false"), @("AllIncomingShareRequestsTypesProcessing","false")
|
||||
)
|
||||
# TextToSpeech — возможность мобильного приложения, добавленная форматом 2.18 (8.3.25),
|
||||
# последней в списке; в 2.21 список не менялся. Замерено выгрузками пустой ИБ шести платформ:
|
||||
# 2.13/2.17 — 37 записей без неё, 2.18-2.21 — 38 с ней. Гейт обязателен и в обе стороны:
|
||||
# на 2.17 тег ломает загрузку XDTO-ошибкой (проверено на 8.3.24), без тега на 2.18+ платформа
|
||||
# подставит дефолт false и допишет его при выгрузке — то есть разойдётся роундтрип.
|
||||
if ($is218) { $mobileFuncs += ,@("TextToSpeech","false") }
|
||||
|
||||
$mobileXml = ""
|
||||
foreach ($mf in $mobileFuncs) {
|
||||
@@ -68,17 +119,43 @@ foreach ($mf in $mobileFuncs) {
|
||||
# --- Synonym XML ---
|
||||
$synonymXml = ""
|
||||
if ($Synonym) {
|
||||
$synonymXml = "`r`n`t`t`t`t<v8:item>`r`n`t`t`t`t`t<v8:lang>ru</v8:lang>`r`n`t`t`t`t`t<v8:content>$([System.Security.SecurityElement]::Escape($Synonym))</v8:content>`r`n`t`t`t`t</v8:item>`r`n`t`t`t"
|
||||
$synonymXml = "`r`n`t`t`t`t<v8:item>`r`n`t`t`t`t`t<v8:lang>ru</v8:lang>`r`n`t`t`t`t`t<v8:content>$(Esc-XmlText ($Synonym))</v8:content>`r`n`t`t`t`t</v8:item>`r`n`t`t`t"
|
||||
}
|
||||
|
||||
# --- Optional properties ---
|
||||
$vendorXml = if ($Vendor) { [System.Security.SecurityElement]::Escape($Vendor) } else { "" }
|
||||
$versionXml = if ($Version) { [System.Security.SecurityElement]::Escape($Version) } else { "" }
|
||||
# Элемент целиком, а не значение внутри пары: при пустом значении Конфигуратор
|
||||
# пишет <Vendor/>, а не <Vendor></Vendor>.
|
||||
$vendorEl = if ($Vendor) { "<Vendor>$(Esc-XmlText ($Vendor))</Vendor>" } else { "<Vendor/>" }
|
||||
$versionEl = if ($Version) { "<Version>$(Esc-XmlText ($Version))</Version>" } else { "<Version/>" }
|
||||
|
||||
# --- Свойства и пространство имён формата 2.21 (платформа 8.5) ---
|
||||
# Значения и ПОЗИЦИИ сняты с выгрузки 8.5.1 (debug/fmt221/dump_v851): те же исходники,
|
||||
# выгруженные с 8.3.27 и с 8.5.1, различаются ровно этим. Порядок важен — вставки идут
|
||||
# на своё место, а не в конец.
|
||||
$nl = "`r`n"
|
||||
$f221AuxForms = ""; $f221WindowVariant = ""; $f221OpenVariant = ""; $f221Captions = ""; $f221Migration = ""
|
||||
$palNs = ""
|
||||
if ($is221) {
|
||||
$palNs = ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette"'
|
||||
# Скобки вокруг -join обязательны: без них `$nl + (массив) -join $nl` разбирается как
|
||||
# `($nl + массив) -join $nl`, массив склеивается пробелами и все теги уезжают в одну строку.
|
||||
$f221AuxForms = $nl + ((@(
|
||||
"<AuxiliaryReportForm/>", "<AuxiliaryReportVariantForm/>", "<AuxiliaryReportSettingsForm/>",
|
||||
"<AuxiliaryDynamicListSettingsForm/>", "<AuxiliaryDataHistoryChangeHistoryForm/>",
|
||||
"<AuxiliaryDataHistoryVersionDataForm/>", "<AuxiliaryDataHistoryVersionDifferencesForm/>",
|
||||
"<AuxiliaryCollaborationSystemUsersChoiceForm/>"
|
||||
) | ForEach-Object { "`t`t`t$_" }) -join $nl)
|
||||
$f221WindowVariant = $nl + "`t`t`t<MainClientApplicationWindowInterfaceVariant>NavigationLeft</MainClientApplicationWindowInterfaceVariant>" +
|
||||
$nl + "`t`t`t<ClientApplicationTheme>Auto</ClientApplicationTheme>"
|
||||
$f221OpenVariant = $nl + "`t`t`t<ClientApplicationWindowsOpenVariant>OpenDataInDialogs</ClientApplicationWindowsOpenVariant>"
|
||||
$f221Captions = $nl + "`t`t`t<Caption/>" + $nl + "`t`t`t<ShortCaption/>"
|
||||
$f221Migration = $nl + "`t`t`t<Version85InterfaceMigrationMode>DontUse</Version85InterfaceMigrationMode>"
|
||||
}
|
||||
|
||||
# --- Configuration.xml ---
|
||||
$cfgXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$FormatVersion">
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"$palNs xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$FormatVersion">
|
||||
<Configuration uuid="$uuidCfg">
|
||||
<InternalInfo>
|
||||
<xr:ContainedObject>
|
||||
@@ -111,7 +188,7 @@ $cfgXml = @"
|
||||
</xr:ContainedObject>
|
||||
</InternalInfo>
|
||||
<Properties>
|
||||
<Name>$([System.Security.SecurityElement]::Escape($Name))</Name>
|
||||
<Name>$(Esc-XmlText ($Name))</Name>
|
||||
<Synonym>$synonymXml</Synonym>
|
||||
<Comment/>
|
||||
<NamePrefix/>
|
||||
@@ -122,8 +199,8 @@ $cfgXml = @"
|
||||
</UsePurposes>
|
||||
<ScriptVariant>Russian</ScriptVariant>
|
||||
<DefaultRoles/>
|
||||
<Vendor>$vendorXml</Vendor>
|
||||
<Version>$versionXml</Version>
|
||||
$vendorEl
|
||||
$versionEl
|
||||
<UpdateCatalogAddress/>
|
||||
<IncludeHelpInContents>false</IncludeHelpInContents>
|
||||
<UseManagedFormInOrdinaryApplication>false</UseManagedFormInOrdinaryApplication>
|
||||
@@ -145,15 +222,15 @@ $cfgXml = @"
|
||||
<DefaultDataHistoryChangeHistoryForm/>
|
||||
<DefaultDataHistoryVersionDataForm/>
|
||||
<DefaultDataHistoryVersionDifferencesForm/>
|
||||
<DefaultCollaborationSystemUsersChoiceForm/>
|
||||
<DefaultCollaborationSystemUsersChoiceForm/>$f221AuxForms
|
||||
<RequiredMobileApplicationPermissions/>
|
||||
<UsedMobileApplicationFunctionalities>$mobileXml
|
||||
</UsedMobileApplicationFunctionalities>
|
||||
<StandaloneConfigurationRestrictionRoles/>
|
||||
<MobileApplicationURLs/>
|
||||
<AllowedIncomingShareRequestTypes/>
|
||||
<MainClientApplicationWindowMode>Normal</MainClientApplicationWindowMode>
|
||||
<DefaultInterface/>
|
||||
<AllowedIncomingShareRequestTypes/>$f221WindowVariant
|
||||
<MainClientApplicationWindowMode>Normal</MainClientApplicationWindowMode>$f221OpenVariant
|
||||
<DefaultInterface/>$f221Captions
|
||||
<DefaultStyle/>
|
||||
<DefaultLanguage>Language.Русский</DefaultLanguage>
|
||||
<BriefInformation/>
|
||||
@@ -165,7 +242,7 @@ $cfgXml = @"
|
||||
<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
||||
<ModalityUseMode>DontUse</ModalityUseMode>
|
||||
<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
||||
<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
||||
<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>$f221Migration
|
||||
<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
||||
<CompatibilityMode>$CompatibilityMode</CompatibilityMode>
|
||||
<DefaultConstantsForm/>
|
||||
@@ -180,7 +257,7 @@ $cfgXml = @"
|
||||
# --- Languages/Русский.xml ---
|
||||
$langXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$FormatVersion">
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"$palNs xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$FormatVersion">
|
||||
<Language uuid="$uuidLang">
|
||||
<Properties>
|
||||
<Name>Русский</Name>
|
||||
@@ -240,11 +317,20 @@ if (-not (Test-Path $extDir)) {
|
||||
# --- Write files with UTF-8 BOM ---
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
|
||||
[System.IO.File]::WriteAllText($cfgFile, $cfgXml, $enc)
|
||||
# XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
|
||||
#
|
||||
# Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
|
||||
# копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
function Write-XmlFile([string]$path, [string]$text, $encoding) {
|
||||
$t = ($text -replace "`r`n", "`n") -replace "`n", "`r`n"
|
||||
[System.IO.File]::WriteAllText($path, $t.TrimEnd("`r", "`n"), $encoding)
|
||||
}
|
||||
|
||||
Write-XmlFile $cfgFile $cfgXml $enc
|
||||
$langFile = Join-Path $langDir "Русский.xml"
|
||||
[System.IO.File]::WriteAllText($langFile, $langXml, $enc)
|
||||
Write-XmlFile $langFile $langXml $enc
|
||||
$caiFile = Join-Path $extDir "ClientApplicationInterface.xml"
|
||||
[System.IO.File]::WriteAllText($caiFile, $caiXml, $enc)
|
||||
Write-XmlFile $caiFile $caiXml $enc
|
||||
|
||||
# --- Output ---
|
||||
Write-Host "[OK] Создана конфигурация: $Name"
|
||||
@@ -0,0 +1,340 @@
|
||||
#!/usr/bin/env python3
|
||||
# cf-init v1.15 — Create empty 1C configuration scaffold (+write_xml_file/write_utf8_bom: общий эталон записи)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Generates minimal XML source files for a 1C configuration."""
|
||||
import sys, os, argparse, re, uuid
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def esc_xml_text(s):
|
||||
# Эскейп ТЕКСТА элемента: только & < > — кавычку и апостроф платформа держит сырыми.
|
||||
return s.replace('&', '&').replace('<', '<').replace('>', '>')
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
# newline='' — без трансляции: иначе текстовый режим Python дал бы CRLF на Windows
|
||||
# и LF на macOS, то есть вывод навыка зависел бы от ОС.
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
def write_xml_file(path, content):
|
||||
"""XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
|
||||
|
||||
Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
|
||||
копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
"""
|
||||
text = content.replace('\r\n', '\n').replace('\n', '\r\n').rstrip('\r\n')
|
||||
write_utf8_bom(path, text)
|
||||
|
||||
|
||||
def format_rank(ver):
|
||||
""""2.20" → 220, "2.9" → 209. Строковое сравнение неверно ("2.9" > "2.17")."""
|
||||
m = re.match(r'^(\d+)\.(\d+)$', ver or '')
|
||||
return int(m.group(1)) * 100 + int(m.group(2)) if m else 0
|
||||
|
||||
|
||||
FORMAT_VERIFIED_MIN = "2.17"
|
||||
FORMAT_VERIFIED_MAX = "2.21"
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
parser = argparse.ArgumentParser(description='Create empty 1C configuration scaffold', allow_abbrev=False)
|
||||
parser.add_argument('-Name', dest='Name', required=True)
|
||||
parser.add_argument('-Synonym', dest='Synonym', default=None)
|
||||
parser.add_argument('-OutputDir', dest='OutputDir', default='src')
|
||||
parser.add_argument('-Version', dest='Version', default='')
|
||||
parser.add_argument('-Vendor', dest='Vendor', default='')
|
||||
parser.add_argument('-CompatibilityMode', dest='CompatibilityMode', default='Version8_3_24')
|
||||
# Версия формата выгрузки (MDClasses) — её задаёт ПЛАТФОРМА, а не режим совместимости.
|
||||
# Дефолт 2.17 — нижняя граница проверенного диапазона.
|
||||
parser.add_argument('-FormatVersion', dest='FormatVersion', default='2.17')
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
# Проверенный диапазон: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница —
|
||||
# docs/1c-configuration-spec.md, «Лестница версий». Версии ниже 2.17 (платформы 8.3.23 и
|
||||
# старше) реальны, поэтому запретом их не закрываем: за пределами диапазона —
|
||||
# ПРЕДУПРЕЖДЕНИЕ, скаффолд всё равно выпускается. Ошибка — только на нечисловое значение.
|
||||
format_rank_value = format_rank(args.FormatVersion)
|
||||
if format_rank_value == 0:
|
||||
print(f"Malformed -FormatVersion '{args.FormatVersion}' (expected N.N, e.g. 2.17)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
if not (format_rank(FORMAT_VERIFIED_MIN) <= format_rank_value <= format_rank(FORMAT_VERIFIED_MAX)):
|
||||
print(f"WARNING: Format version '{args.FormatVersion}' is outside the tested range "
|
||||
f"{FORMAT_VERIFIED_MIN}-{FORMAT_VERIFIED_MAX} — the scaffold is emitted as requested "
|
||||
f"but was not verified on that platform", file=sys.stderr)
|
||||
|
||||
# «Не использовать» в Конфигураторе хранится как версия ТЕКУЩЕЙ платформы, а не как DontUse:
|
||||
# свежая база получает Version8_3_<своя>, и ни одна типовая в корпусе DontUse не содержит.
|
||||
# Само значение легально — платформа принимает его без ошибок, — но не выживает: замерено на
|
||||
# 8.3.25 и 8.3.27, выгрузка обоих возвращает Version8_3_8. Поэтому предупреждение, а не запрет.
|
||||
# Сравнение регистронезависимо ЯВНО: в PS -eq таков по умолчанию, в py — нет, и молчаливое
|
||||
# расхождение портов началось бы прямо здесь.
|
||||
if (args.CompatibilityMode or "").lower() == "dontuse":
|
||||
print("WARNING: CompatibilityMode 'DontUse' is not \"no restrictions\" — the platform stores it as Version8_3_8. For no compatibility restrictions use the target platform version (e.g. Version8_3_27 for 8.3.27).", file=sys.stderr)
|
||||
|
||||
name = args.Name
|
||||
synonym = args.Synonym if args.Synonym else name
|
||||
output_dir = args.OutputDir
|
||||
version = args.Version
|
||||
vendor = args.Vendor
|
||||
compat = args.CompatibilityMode
|
||||
|
||||
# --- Resolve output dir ---
|
||||
if not os.path.isabs(output_dir):
|
||||
output_dir = os.path.join(os.getcwd(), output_dir)
|
||||
|
||||
# --- Check existing ---
|
||||
cfg_file = os.path.join(output_dir, "Configuration.xml")
|
||||
if os.path.exists(cfg_file):
|
||||
print(f"Configuration.xml already exists: {cfg_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# --- Generate UUIDs ---
|
||||
uuid_cfg = new_uuid()
|
||||
uuid_lang = new_uuid()
|
||||
co = [new_uuid() for _ in range(7)]
|
||||
|
||||
# --- Mobile functionalities ---
|
||||
# Версия формата как число — по ней ниже включаются вставки 2.21.
|
||||
is_221 = format_rank_value >= 221
|
||||
# TextToSpeech приехал раньше остальных вставок 8.5 — своей ступенью, поэтому гейт отдельный.
|
||||
is_218 = format_rank_value >= 218
|
||||
|
||||
mobile_funcs = [
|
||||
("Biometrics","true"), ("Location","false"), ("BackgroundLocation","false"),
|
||||
("BluetoothPrinters","false"), ("WiFiPrinters","false"), ("Contacts","false"),
|
||||
("Calendars","false"), ("PushNotifications","false"), ("LocalNotifications","false"),
|
||||
("InAppPurchases","false"), ("PersonalComputerFileExchange","false"), ("Ads","false"),
|
||||
("NumberDialing","false"), ("CallProcessing","false"), ("CallLog","false"),
|
||||
("AutoSendSMS","false"), ("ReceiveSMS","false"), ("SMSLog","false"),
|
||||
("Camera","false"), ("Microphone","false"), ("MusicLibrary","false"),
|
||||
("PictureAndVideoLibraries","false"), ("AudioPlaybackAndVibration","false"),
|
||||
("BackgroundAudioPlaybackAndVibration","false"), ("InstallPackages","false"),
|
||||
("OSBackup","true"), ("ApplicationUsageStatistics","false"),
|
||||
("BarcodeScanning","false"), ("BackgroundAudioRecording","false"),
|
||||
("AllFilesAccess","false"), ("Videoconferences","false"), ("NFC","false"),
|
||||
("DocumentScanning","false"), ("SpeechToText","false"), ("Geofences","false"),
|
||||
("IncomingShareRequests","false"), ("AllIncomingShareRequestsTypesProcessing","false"),
|
||||
]
|
||||
# TextToSpeech — возможность мобильного приложения, добавленная форматом 2.18 (8.3.25),
|
||||
# последней в списке; в 2.21 список не менялся. Замерено выгрузками пустой ИБ шести платформ:
|
||||
# 2.13/2.17 — 37 записей без неё, 2.18-2.21 — 38 с ней. Гейт обязателен и в обе стороны:
|
||||
# на 2.17 тег ломает загрузку XDTO-ошибкой (проверено на 8.3.24), без тега на 2.18+ платформа
|
||||
# подставит дефолт false и допишет его при выгрузке — то есть разойдётся роундтрип.
|
||||
if is_218:
|
||||
mobile_funcs.append(("TextToSpeech", "false"))
|
||||
|
||||
mobile_xml = ""
|
||||
for func_name, func_use in mobile_funcs:
|
||||
mobile_xml += f"\r\n\t\t\t\t<app:functionality>\r\n\t\t\t\t\t<app:functionality>{func_name}</app:functionality>\r\n\t\t\t\t\t<app:use>{func_use}</app:use>\r\n\t\t\t\t</app:functionality>"
|
||||
|
||||
# --- Synonym XML ---
|
||||
synonym_xml = ""
|
||||
if synonym:
|
||||
synonym_xml = f"\r\n\t\t\t\t<v8:item>\r\n\t\t\t\t\t<v8:lang>ru</v8:lang>\r\n\t\t\t\t\t<v8:content>{esc_xml_text(synonym)}</v8:content>\r\n\t\t\t\t</v8:item>\r\n\t\t\t"
|
||||
|
||||
# Элемент целиком, а не значение внутри пары: при пустом значении Конфигуратор
|
||||
# пишет <Vendor/>, а не <Vendor></Vendor>.
|
||||
vendor_el = f"<Vendor>{esc_xml_text(vendor)}</Vendor>" if vendor else "<Vendor/>"
|
||||
version_el = f"<Version>{esc_xml_text(version)}</Version>" if version else "<Version/>"
|
||||
|
||||
class_ids = [
|
||||
"9cd510cd-abfc-11d4-9434-004095e12fc7",
|
||||
"9fcd25a0-4822-11d4-9414-008048da11f9",
|
||||
"e3687481-0a87-462c-a166-9f34594f9bba",
|
||||
"9de14907-ec23-4a07-96f0-85521cb6b53b",
|
||||
"51f2d5d8-ea4d-4064-8892-82951750031e",
|
||||
"e68182ea-4237-4383-967f-90c1e3370bc7",
|
||||
"fb282519-d103-4dd3-bc12-cb271d631dfc",
|
||||
]
|
||||
|
||||
# Свойства и пространство имён формата 2.21 (платформа 8.5). Значения и ПОЗИЦИИ сняты
|
||||
# с выгрузки 8.5.1 (debug/fmt221/dump_v851): те же исходники, выгруженные с 8.3.27 и
|
||||
# с 8.5.1, различаются ровно этим. Порядок важен — вставки идут на своё место.
|
||||
pal_ns = ""
|
||||
f221_aux_forms = f221_window_variant = f221_open_variant = f221_captions = f221_migration = ""
|
||||
if is_221:
|
||||
pal_ns = ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette"'
|
||||
f221_aux_forms = "\r\n" + "\r\n".join(
|
||||
f"\t\t\t{t}" for t in (
|
||||
"<AuxiliaryReportForm/>", "<AuxiliaryReportVariantForm/>", "<AuxiliaryReportSettingsForm/>",
|
||||
"<AuxiliaryDynamicListSettingsForm/>", "<AuxiliaryDataHistoryChangeHistoryForm/>",
|
||||
"<AuxiliaryDataHistoryVersionDataForm/>", "<AuxiliaryDataHistoryVersionDifferencesForm/>",
|
||||
"<AuxiliaryCollaborationSystemUsersChoiceForm/>"))
|
||||
f221_window_variant = ("\r\n\t\t\t<MainClientApplicationWindowInterfaceVariant>NavigationLeft"
|
||||
"</MainClientApplicationWindowInterfaceVariant>"
|
||||
"\r\n\t\t\t<ClientApplicationTheme>Auto</ClientApplicationTheme>")
|
||||
f221_open_variant = ("\r\n\t\t\t<ClientApplicationWindowsOpenVariant>OpenDataInDialogs"
|
||||
"</ClientApplicationWindowsOpenVariant>")
|
||||
f221_captions = "\r\n\t\t\t<Caption/>\r\n\t\t\t<ShortCaption/>"
|
||||
f221_migration = ("\r\n\t\t\t<Version85InterfaceMigrationMode>DontUse"
|
||||
"</Version85InterfaceMigrationMode>")
|
||||
|
||||
contained_objects = ""
|
||||
for i in range(7):
|
||||
contained_objects += f"""\t\t\t<xr:ContainedObject>
|
||||
\t\t\t\t<xr:ClassId>{class_ids[i]}</xr:ClassId>
|
||||
\t\t\t\t<xr:ObjectId>{co[i]}</xr:ObjectId>
|
||||
\t\t\t</xr:ContainedObject>\n"""
|
||||
|
||||
cfg_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"{pal_ns} xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{args.FormatVersion}">
|
||||
\t<Configuration uuid="{uuid_cfg}">
|
||||
\t\t<InternalInfo>
|
||||
{contained_objects}\t\t</InternalInfo>
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{esc_xml_text(name)}</Name>
|
||||
\t\t\t<Synonym>{synonym_xml}</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<NamePrefix/>
|
||||
\t\t\t<ConfigurationExtensionCompatibilityMode>{compat}</ConfigurationExtensionCompatibilityMode>
|
||||
\t\t\t<DefaultRunMode>ManagedApplication</DefaultRunMode>
|
||||
\t\t\t<UsePurposes>
|
||||
\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||
\t\t\t</UsePurposes>
|
||||
\t\t\t<ScriptVariant>Russian</ScriptVariant>
|
||||
\t\t\t<DefaultRoles/>
|
||||
\t\t\t{vendor_el}
|
||||
\t\t\t{version_el}
|
||||
\t\t\t<UpdateCatalogAddress/>
|
||||
\t\t\t<IncludeHelpInContents>false</IncludeHelpInContents>
|
||||
\t\t\t<UseManagedFormInOrdinaryApplication>false</UseManagedFormInOrdinaryApplication>
|
||||
\t\t\t<UseOrdinaryFormInManagedApplication>false</UseOrdinaryFormInManagedApplication>
|
||||
\t\t\t<AdditionalFullTextSearchDictionaries/>
|
||||
\t\t\t<CommonSettingsStorage/>
|
||||
\t\t\t<ReportsUserSettingsStorage/>
|
||||
\t\t\t<ReportsVariantsStorage/>
|
||||
\t\t\t<FormDataSettingsStorage/>
|
||||
\t\t\t<DynamicListsUserSettingsStorage/>
|
||||
\t\t\t<URLExternalDataStorage/>
|
||||
\t\t\t<Content/>
|
||||
\t\t\t<DefaultReportForm/>
|
||||
\t\t\t<DefaultReportVariantForm/>
|
||||
\t\t\t<DefaultReportSettingsForm/>
|
||||
\t\t\t<DefaultReportAppearanceTemplate/>
|
||||
\t\t\t<DefaultDynamicListSettingsForm/>
|
||||
\t\t\t<DefaultSearchForm/>
|
||||
\t\t\t<DefaultDataHistoryChangeHistoryForm/>
|
||||
\t\t\t<DefaultDataHistoryVersionDataForm/>
|
||||
\t\t\t<DefaultDataHistoryVersionDifferencesForm/>
|
||||
\t\t\t<DefaultCollaborationSystemUsersChoiceForm/>{f221_aux_forms}
|
||||
\t\t\t<RequiredMobileApplicationPermissions/>
|
||||
\t\t\t<UsedMobileApplicationFunctionalities>{mobile_xml}
|
||||
\t\t\t</UsedMobileApplicationFunctionalities>
|
||||
\t\t\t<StandaloneConfigurationRestrictionRoles/>
|
||||
\t\t\t<MobileApplicationURLs/>
|
||||
\t\t\t<AllowedIncomingShareRequestTypes/>{f221_window_variant}
|
||||
\t\t\t<MainClientApplicationWindowMode>Normal</MainClientApplicationWindowMode>{f221_open_variant}
|
||||
\t\t\t<DefaultInterface/>{f221_captions}
|
||||
\t\t\t<DefaultStyle/>
|
||||
\t\t\t<DefaultLanguage>Language.Русский</DefaultLanguage>
|
||||
\t\t\t<BriefInformation/>
|
||||
\t\t\t<DetailedInformation/>
|
||||
\t\t\t<Copyright/>
|
||||
\t\t\t<VendorInformationAddress/>
|
||||
\t\t\t<ConfigurationInformationAddress/>
|
||||
\t\t\t<DataLockControlMode>Managed</DataLockControlMode>
|
||||
\t\t\t<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
||||
\t\t\t<ModalityUseMode>DontUse</ModalityUseMode>
|
||||
\t\t\t<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
||||
\t\t\t<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>{f221_migration}
|
||||
\t\t\t<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
||||
\t\t\t<CompatibilityMode>{compat}</CompatibilityMode>
|
||||
\t\t\t<DefaultConstantsForm/>
|
||||
\t\t</Properties>
|
||||
\t\t<ChildObjects>
|
||||
\t\t\t<Language>Русский</Language>
|
||||
\t\t</ChildObjects>
|
||||
\t</Configuration>
|
||||
</MetaDataObject>'''
|
||||
|
||||
# --- Languages/Русский.xml ---
|
||||
lang_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"{pal_ns} xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{args.FormatVersion}">
|
||||
\t<Language uuid="{uuid_lang}">
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>Русский</Name>
|
||||
\t\t\t<Synonym>
|
||||
\t\t\t\t<v8:item>
|
||||
\t\t\t\t\t<v8:lang>ru</v8:lang>
|
||||
\t\t\t\t\t<v8:content>Русский</v8:content>
|
||||
\t\t\t\t</v8:item>
|
||||
\t\t\t</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<LanguageCode>ru</LanguageCode>
|
||||
\t\t</Properties>
|
||||
\t</Language>
|
||||
</MetaDataObject>'''
|
||||
|
||||
# --- Ext/ClientApplicationInterface.xml (default ERP-style panel layout) ---
|
||||
# Open panel on top, Sections panel on left; Functions/Favorites/History declared
|
||||
# via panelDef but not placed by default. Without this file the web client renders
|
||||
# section icons without labels (icon-only mode).
|
||||
open_panel_inst = new_uuid()
|
||||
sections_panel_inst = new_uuid()
|
||||
cai_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<ClientApplicationInterface xmlns="http://v8.1c.ru/8.2/managed-application/core" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="InterfaceLayouter">
|
||||
\t<top>
|
||||
\t\t<panel id="{open_panel_inst}">
|
||||
\t\t\t<uuid>cbab57f2-a0f3-4f0a-89ea-4cb19570ab75</uuid>
|
||||
\t\t</panel>
|
||||
\t</top>
|
||||
\t<left>
|
||||
\t\t<panel id="{sections_panel_inst}">
|
||||
\t\t\t<uuid>b553047f-c9aa-4157-978d-448ecad24248</uuid>
|
||||
\t\t</panel>
|
||||
\t</left>
|
||||
\t<panelDef id="b553047f-c9aa-4157-978d-448ecad24248"/>
|
||||
\t<panelDef id="13322b22-3960-4d68-93a6-fe2dd7f28ca3"/>
|
||||
\t<panelDef id="c933ac92-92cd-459d-81cc-e0c8a83ced99"/>
|
||||
\t<panelDef id="cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"/>
|
||||
\t<panelDef id="b2735bd3-d822-4430-ba59-c9e869693b24"/>
|
||||
</ClientApplicationInterface>'''
|
||||
|
||||
# --- Create directories ---
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
lang_dir = os.path.join(output_dir, "Languages")
|
||||
os.makedirs(lang_dir, exist_ok=True)
|
||||
ext_dir = os.path.join(output_dir, "Ext")
|
||||
os.makedirs(ext_dir, exist_ok=True)
|
||||
|
||||
# --- Write files ---
|
||||
write_xml_file(cfg_file, cfg_xml)
|
||||
lang_file = os.path.join(lang_dir, "Русский.xml")
|
||||
write_xml_file(lang_file, lang_xml)
|
||||
cai_file = os.path.join(ext_dir, "ClientApplicationInterface.xml")
|
||||
write_xml_file(cai_file, cai_xml)
|
||||
|
||||
print(f"[OK] Создана конфигурация: {name}")
|
||||
print(f" Каталог: {output_dir}")
|
||||
print(f" Configuration.xml: {cfg_file}")
|
||||
print(f" Languages: {lang_file}")
|
||||
print(f" Ext/CAI: {cai_file}")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -24,6 +24,6 @@ allowed-tools:
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty"
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty/Configuration.xml"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cf-validate/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cf-validate/scripts/cf-validate.ps1" -ConfigPath "upload/cfempty/Configuration.xml"
|
||||
```
|
||||
+28
-9
@@ -1,7 +1,8 @@
|
||||
# cf-validate v1.5 — Validate 1C configuration root structure
|
||||
# cf-validate v1.10 — Validate 1C configuration root structure
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Parameter(Mandatory, Position=0)]
|
||||
[Alias('Path')]
|
||||
[string]$ConfigPath,
|
||||
|
||||
@@ -89,6 +90,19 @@ $finalize = {
|
||||
}
|
||||
}
|
||||
|
||||
# --- Format version ---
|
||||
# Проверенный диапазон версий формата выгрузки: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница —
|
||||
# docs/1c-configuration-spec.md, «Лестница версий». Версию задаёт платформа ВЫГРУЗКИ, а не режим
|
||||
# совместимости конфигурации. Версии ниже 2.17 (платформы 8.3.23 и старше) существуют, но навыки
|
||||
# на них не проверялись — это предупреждение о непокрытии, а не о некорректности файла.
|
||||
$formatVerifiedMin = "2.17"
|
||||
$formatVerifiedMax = "2.21"
|
||||
# Версия формата как число: "2.20" → 220. Строковое сравнение неверно ("2.9" > "2.17").
|
||||
function Get-FormatRank([string]$ver) {
|
||||
if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
|
||||
return 0
|
||||
}
|
||||
|
||||
# --- Reference tables ---
|
||||
$guidPattern = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
|
||||
$identPattern = '^[A-Za-z\u0410-\u042F\u0401\u0430-\u044F\u0451_][A-Za-z0-9\u0410-\u042F\u0401\u0430-\u044F\u0451_]*$'
|
||||
@@ -108,16 +122,16 @@ $validClassIds = @(
|
||||
$childObjectTypes = @(
|
||||
"Language","Subsystem","StyleItem","Style",
|
||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
||||
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||
"FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
|
||||
"Constant","CommonForm","Catalog","Document",
|
||||
"DocumentNumerator","Sequence","DocumentJournal","Enum",
|
||||
"Report","DataProcessor","InformationRegister","AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
|
||||
"ChartOfCalculationTypes","CalculationRegister",
|
||||
"BusinessProcess","Task","IntegrationService"
|
||||
"BusinessProcess","Task","ExternalDataSource","IntegrationService"
|
||||
)
|
||||
|
||||
# Type -> directory mapping
|
||||
@@ -126,6 +140,7 @@ $childTypeDirMap = @{
|
||||
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"
|
||||
"CommonTemplate"="CommonTemplates"; "FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"
|
||||
"Bot"="Bots"
|
||||
"PaletteColor"="PaletteColors"
|
||||
"CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"; "XDTOPackage"="XDTOPackages"
|
||||
"WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
||||
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
|
||||
@@ -142,7 +157,7 @@ $childTypeDirMap = @{
|
||||
"ChartOfCalculationTypes"="ChartsOfCalculationTypes"
|
||||
"CalculationRegister"="CalculationRegisters"
|
||||
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
|
||||
"IntegrationService"="IntegrationServices"
|
||||
"ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
|
||||
}
|
||||
|
||||
# Valid enum values for Configuration properties
|
||||
@@ -203,11 +218,15 @@ if ($root.NamespaceURI -ne $expectedNs) {
|
||||
}
|
||||
|
||||
$version = $root.GetAttribute("version")
|
||||
$versionRank = Get-FormatRank $version
|
||||
if (-not $version) {
|
||||
Report-Warn "1. Missing version attribute on MetaDataObject"
|
||||
} elseif ($version -notin @("2.17", "2.18", "2.19", "2.20", "2.21")) {
|
||||
# Лестница версий формата: 2.17 (8.3.20-8.3.24), 2.18 (8.3.25), 2.19 (8.3.26), 2.20 (8.3.27).
|
||||
Report-Warn "1. Unusual version '$version' (expected 2.17-2.20 or 2.21)"
|
||||
} elseif ($versionRank -eq 0) {
|
||||
Report-Error "1. Malformed version '$version' (expected N.N)"
|
||||
} elseif ($versionRank -lt (Get-FormatRank $formatVerifiedMin)) {
|
||||
Report-Warn "1. Format version '$version' is below the tested range $formatVerifiedMin-$formatVerifiedMax — skills were not verified on it"
|
||||
} elseif ($versionRank -gt (Get-FormatRank $formatVerifiedMax)) {
|
||||
Report-Warn "1. Format version '$version' is above the tested range $formatVerifiedMin-$formatVerifiedMax — skills were not verified on it"
|
||||
}
|
||||
|
||||
# Must have Configuration child
|
||||
+52
-9
@@ -1,10 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
# cf-validate v1.5 — Validate 1C configuration XML structure
|
||||
# cf-validate v1.10 — Validate 1C configuration XML structure
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Validates Configuration.xml: root structure, InternalInfo, properties, ChildObjects, languages."""
|
||||
import sys, os, argparse, re
|
||||
from lxml import etree
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
NS = {
|
||||
'md': 'http://v8.1c.ru/8.3/MDClasses',
|
||||
'v8': 'http://v8.1c.ru/8.1/data/core',
|
||||
@@ -37,16 +59,16 @@ VALID_CLASS_IDS = [
|
||||
CHILD_OBJECT_TYPES = [
|
||||
'Language', 'Subsystem', 'StyleItem', 'Style',
|
||||
'CommonPicture', 'SessionParameter', 'Role', 'CommonTemplate',
|
||||
'FilterCriterion', 'CommonModule', 'Bot', 'CommonAttribute', 'ExchangePlan',
|
||||
'FilterCriterion', 'CommonModule', 'CommonAttribute', 'ExchangePlan',
|
||||
'XDTOPackage', 'WebService', 'HTTPService', 'WSReference',
|
||||
'EventSubscription', 'ScheduledJob', 'SettingsStorage', 'FunctionalOption',
|
||||
'FunctionalOptionsParameter', 'DefinedType', 'CommonCommand', 'CommandGroup',
|
||||
'FunctionalOptionsParameter', 'DefinedType', 'Bot', 'PaletteColor', 'CommonCommand', 'CommandGroup',
|
||||
'Constant', 'CommonForm', 'Catalog', 'Document',
|
||||
'DocumentNumerator', 'Sequence', 'DocumentJournal', 'Enum',
|
||||
'Report', 'DataProcessor', 'InformationRegister', 'AccumulationRegister',
|
||||
'ChartOfCharacteristicTypes', 'ChartOfAccounts', 'AccountingRegister',
|
||||
'ChartOfCalculationTypes', 'CalculationRegister',
|
||||
'BusinessProcess', 'Task', 'IntegrationService',
|
||||
'BusinessProcess', 'Task', 'ExternalDataSource', 'IntegrationService',
|
||||
]
|
||||
|
||||
# Type -> directory mapping
|
||||
@@ -54,7 +76,7 @@ CHILD_TYPE_DIR_MAP = {
|
||||
'Language': 'Languages', 'Subsystem': 'Subsystems', 'StyleItem': 'StyleItems', 'Style': 'Styles',
|
||||
'CommonPicture': 'CommonPictures', 'SessionParameter': 'SessionParameters', 'Role': 'Roles',
|
||||
'CommonTemplate': 'CommonTemplates', 'FilterCriterion': 'FilterCriteria', 'CommonModule': 'CommonModules',
|
||||
'Bot': 'Bots',
|
||||
'Bot': 'Bots', 'PaletteColor': 'PaletteColors',
|
||||
'CommonAttribute': 'CommonAttributes', 'ExchangePlan': 'ExchangePlans', 'XDTOPackage': 'XDTOPackages',
|
||||
'WebService': 'WebServices', 'HTTPService': 'HTTPServices', 'WSReference': 'WSReferences',
|
||||
'EventSubscription': 'EventSubscriptions', 'ScheduledJob': 'ScheduledJobs',
|
||||
@@ -71,6 +93,7 @@ CHILD_TYPE_DIR_MAP = {
|
||||
'ChartOfCalculationTypes': 'ChartsOfCalculationTypes',
|
||||
'CalculationRegister': 'CalculationRegisters',
|
||||
'BusinessProcess': 'BusinessProcesses', 'Task': 'Tasks',
|
||||
'ExternalDataSource': 'ExternalDataSources',
|
||||
'IntegrationService': 'IntegrationServices',
|
||||
}
|
||||
|
||||
@@ -110,6 +133,20 @@ VALID_ENUM_VALUES = {
|
||||
|
||||
EXPECTED_NS = 'http://v8.1c.ru/8.3/MDClasses'
|
||||
|
||||
# ── Format version ───────────────────────────────────────────
|
||||
# Проверенный диапазон версий формата выгрузки: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница —
|
||||
# docs/1c-configuration-spec.md, «Лестница версий». Версию задаёт платформа ВЫГРУЗКИ, а не режим
|
||||
# совместимости конфигурации. Версии ниже 2.17 (платформы 8.3.23 и старше) существуют, но навыки
|
||||
# на них не проверялись — это предупреждение о непокрытии, а не о некорректности файла.
|
||||
FORMAT_VERIFIED_MIN = "2.17"
|
||||
FORMAT_VERIFIED_MAX = "2.21"
|
||||
|
||||
|
||||
def format_rank(ver):
|
||||
""""2.20" → 220, "2.9" → 209. Строковое сравнение неверно ("2.9" > "2.17")."""
|
||||
m = re.match(r'^(\d+)\.(\d+)$', ver or '')
|
||||
return int(m.group(1)) * 100 + int(m.group(2)) if m else 0
|
||||
|
||||
|
||||
class Reporter:
|
||||
def __init__(self, max_errors, detailed=False):
|
||||
@@ -170,7 +207,7 @@ def main():
|
||||
parser.add_argument('-Detailed', action='store_true')
|
||||
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
||||
parser.add_argument('-OutFile', dest='OutFile', default='')
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
config_path = args.ConfigPath
|
||||
max_errors = args.MaxErrors
|
||||
@@ -230,11 +267,17 @@ def main():
|
||||
check1_ok = False
|
||||
|
||||
version = root.get('version', '')
|
||||
version_rank = format_rank(version)
|
||||
if not version:
|
||||
r.warn('1. Missing version attribute on MetaDataObject')
|
||||
elif version not in ('2.17', '2.18', '2.19', '2.20', '2.21'):
|
||||
# Лестница версий формата: 2.17 (8.3.20-8.3.24), 2.18 (8.3.25), 2.19 (8.3.26), 2.20 (8.3.27).
|
||||
r.warn(f"1. Unusual version '{version}' (expected 2.17-2.20 or 2.21)")
|
||||
elif version_rank == 0:
|
||||
r.error(f"1. Malformed version '{version}' (expected N.N)")
|
||||
elif version_rank < format_rank(FORMAT_VERIFIED_MIN):
|
||||
r.warn(f"1. Format version '{version}' is below the tested range "
|
||||
f"{FORMAT_VERIFIED_MIN}-{FORMAT_VERIFIED_MAX} — skills were not verified on it")
|
||||
elif version_rank > format_rank(FORMAT_VERIFIED_MAX):
|
||||
r.warn(f"1. Format version '{version}' is above the tested range "
|
||||
f"{FORMAT_VERIFIED_MIN}-{FORMAT_VERIFIED_MAX} — skills were not verified on it")
|
||||
|
||||
# Must have Configuration child
|
||||
cfg_node = None
|
||||
@@ -31,6 +31,7 @@ allowed-tools:
|
||||
| `ExtensionPath` | Путь к каталогу расширения (обязат.) |
|
||||
| `ConfigPath` | Путь к конфигурации-источнику (обязат.) |
|
||||
| `Object` | Что заимствовать (обязат.), batch через `;;` |
|
||||
| `Module` | Создать пустые модули объекта: `ObjectModule`, `ManagerModule`, `RecordSetModule`, `ValueManagerModule` (через запятую) или `None`. У типов с единственным модулем (`CommonModule`, `HTTPService`, `WebService`) он создаётся и без параметра |
|
||||
| `BorrowMainAttribute` | Заимствовать основной реквизит формы. Без параметра — не заимствует. `Form` — реквизиты, используемые на форме. `All` — все реквизиты объекта. Требует форму в -Object |
|
||||
|
||||
## Формат -Object
|
||||
@@ -41,7 +42,6 @@ allowed-tools:
|
||||
- `Enum.ВидыОплат` — перечисление
|
||||
- `Catalog.Контрагенты.Form.ФормаЭлемента` — форма объекта (заимствование формы)
|
||||
- `Catalog.X ;; CommonModule.Y ;; Enum.Z` — несколько объектов
|
||||
Поддерживаются все 44 типа объектов конфигурации.
|
||||
|
||||
### Заимствование форм
|
||||
|
||||
@@ -66,36 +66,44 @@ allowed-tools:
|
||||
2. `/meta-edit` — добавить новый реквизит в объект расширения
|
||||
3. `/form-edit` — вывести реквизит на заимствованную форму
|
||||
|
||||
**Защита существующих данных**: если зависимый объект уже заимствован с содержимым (реквизитами, формами) — скрипт не перезаписывает его, а добавляет только недостающее.
|
||||
**Защита существующих данных**: уже заимствованный объект не перезаписывается — добавляется только недостающее. Повторный вызов безопасен: собственные реквизиты расширения, заимствованные подобъекты и код в модулях сохраняются.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-borrow.ps1" -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-borrow/scripts/cfe-borrow.ps1" -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Контрагенты"
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Заимствовать один объект
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты"
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Контрагенты"
|
||||
|
||||
# Заимствовать справочник вместе с модулями объекта и менеджера
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Контрагенты" -Module ObjectModule,ManagerModule
|
||||
|
||||
# Общий модуль без файла модуля
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "CommonModule.РаботаСФайлами" -Module None
|
||||
|
||||
# Заимствовать форму (автоматически заимствует родительский объект)
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты.Form.ФормаЭлемента"
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Контрагенты.Form.ФормаЭлемента"
|
||||
|
||||
# Несколько объектов за раз
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты ;; CommonModule.ОбщийМодуль ;; Enum.ВидыОплат"
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Контрагенты ;; CommonModule.ОбщийМодуль ;; Enum.ВидыОплат"
|
||||
|
||||
# Заимствовать форму с основным реквизитом (реквизиты по DataPath формы)
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Номенклатура.Form.ФормаЭлемента" -BorrowMainAttribute
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Номенклатура.Form.ФормаЭлемента" -BorrowMainAttribute
|
||||
|
||||
# Заимствовать форму с ВСЕМИ реквизитами объекта
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Номенклатура.Form.ФормаЭлемента" -BorrowMainAttribute All
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Object "Catalog.Номенклатура.Form.ФормаЭлемента" -BorrowMainAttribute All
|
||||
```
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/cfe-validate <ExtensionPath>
|
||||
/cfe-validate <ExtensionPath> -ConfigPath <ConfigPath>
|
||||
```
|
||||
|
||||
Конфигурацию-источник передавай и валидатору: заимствованные формы он проверяет по ней.
|
||||
|
||||
+817
-132
File diff suppressed because it is too large
Load Diff
+821
-122
File diff suppressed because it is too large
Load Diff
@@ -23,7 +23,7 @@ allowed-tools:
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-diff.ps1" -ExtensionPath src -ConfigPath C:\cfsrc\erp -Mode A
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-diff/scripts/cfe-diff.ps1" -ExtensionPath src\cfe\extname -ConfigPath src\cf -Mode A
|
||||
```
|
||||
|
||||
## Mode A — обзор расширения
|
||||
@@ -50,8 +50,8 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-diff.ps1" -Exte
|
||||
|
||||
```powershell
|
||||
# Обзор — что изменено в расширении
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Mode A
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Mode A
|
||||
|
||||
# Проверка переноса — все ли #Вставка перенесены
|
||||
... -ExtensionPath src -ConfigPath C:\cfsrc\erp -Mode B
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Mode B
|
||||
```
|
||||
+95
-22
@@ -1,7 +1,8 @@
|
||||
# cfe-diff v1.0 — Analyze and compare 1C configuration extension (CFE)
|
||||
# cfe-diff v1.6 — Analyze and compare 1C configuration extension (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Parameter(Mandatory, Position=0)]
|
||||
[string]$ExtensionPath,
|
||||
|
||||
[Parameter(Mandatory)]
|
||||
@@ -48,8 +49,11 @@ $childTypeDirMap = @{
|
||||
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
|
||||
"SettingsStorage"="SettingsStorages"; "FilterCriterion"="FilterCriteria"
|
||||
"CommandGroup"="CommandGroups"; "DocumentNumerator"="DocumentNumerators"
|
||||
"Sequence"="Sequences"; "IntegrationService"="IntegrationServices"
|
||||
"CommonAttribute"="CommonAttributes"
|
||||
"Sequence"="Sequences"; "ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
|
||||
"CommonAttribute"="CommonAttributes"; "Style"="Styles"; "XDTOPackage"="XDTOPackages"
|
||||
"WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
||||
"Bot"="Bots"
|
||||
"PaletteColor"="PaletteColors"
|
||||
}
|
||||
|
||||
# --- Parse extension Configuration.xml ---
|
||||
@@ -158,24 +162,92 @@ function Get-BslFiles {
|
||||
return $bslFiles
|
||||
}
|
||||
|
||||
# --- Helper: parse interceptors from .bsl ---
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
function Get-BslKeywords {
|
||||
return @{
|
||||
ru = @{
|
||||
Async="Асинх"; Proc="Процедура"; EndProc="КонецПроцедуры"
|
||||
Func="Функция"; EndFunc="КонецФункции"; Val="Знач"
|
||||
Region="Область"; EndRegion="КонецОбласти"
|
||||
If="Если"; Then="Тогда"; ElsIf="ИначеЕсли"; Else="Иначе"; EndIf="КонецЕсли"
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
And="И"; Or="Или"; Not="НЕ"
|
||||
Insert="Вставка"; EndInsert="КонецВставки"; Delete="Удаление"; EndDelete="КонецУдаления"
|
||||
Before="Перед"; After="После"; Around="Вместо"; Control="ИзменениеИКонтроль"
|
||||
Proceed="ПродолжитьВызов"; Return="Возврат"
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
ResultVar="Результат"
|
||||
Directives=@("НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере")
|
||||
}
|
||||
en = @{
|
||||
Async="Async"; Proc="Procedure"; EndProc="EndProcedure"
|
||||
Func="Function"; EndFunc="EndFunction"; Val="Val"
|
||||
Region="Region"; EndRegion="EndRegion"
|
||||
If="If"; Then="Then"; ElsIf="ElsIf"; Else="Else"; EndIf="EndIf"
|
||||
And="And"; Or="Or"; Not="Not"
|
||||
Insert="Insert"; EndInsert="EndInsert"; Delete="Delete"; EndDelete="EndDelete"
|
||||
Before="Before"; After="After"; Around="Around"; Control="ChangeAndValidate"
|
||||
Proceed="ProceedWithCall"; Return="Return"
|
||||
ResultVar="Result"
|
||||
Directives=@("AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$script:bslKw = Get-BslKeywords
|
||||
|
||||
# Edit marker kind at the start of a line: Insert/Delete/EndInsert/EndDelete, $null if none.
|
||||
# The marker owns the start of the line only — a trailing comment does not bother the platform
|
||||
# and must not bother us either.
|
||||
function Get-BslMarkerKind {
|
||||
param([string]$line)
|
||||
$kw = $script:bslKw
|
||||
foreach ($k in @("EndInsert", "EndDelete", "Insert", "Delete")) {
|
||||
if ($line -match ('^\s*#(?:' + $kw.ru[$k] + '|' + $kw.en[$k] + ')\b')) { return $k }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# Parse interceptor annotations present in a module. Type is normalized to the Russian spelling
|
||||
# so everything downstream stays single-language; Raw keeps what the file actually says.
|
||||
function Get-Interceptors {
|
||||
param($lines)
|
||||
$kw = $script:bslKw
|
||||
$keys = @("Before", "After", "Control", "Around")
|
||||
$alt = @()
|
||||
$norm = @{}
|
||||
foreach ($k in $keys) {
|
||||
$alt += $kw.ru[$k]; $alt += $kw.en[$k]
|
||||
$norm[$kw.ru[$k].ToLower()] = $kw.ru[$k]
|
||||
$norm[$kw.en[$k].ToLower()] = $kw.ru[$k]
|
||||
}
|
||||
$re = '^&(' + ($alt -join '|') + ')\("([^"]+)"\)'
|
||||
$result = @()
|
||||
for ($i = 0; $i -lt $lines.Count; $i++) {
|
||||
$t = $lines[$i].Trim()
|
||||
if ($t -match $re) {
|
||||
$raw = $Matches[1]
|
||||
$result += @{ Type = $norm[$raw.ToLower()]; Raw = $raw; Method = $Matches[2]; Line = $i }
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
# --- Helper: read a .bsl and parse its interceptors ---
|
||||
function Get-FileInterceptors {
|
||||
param([string]$bslPath)
|
||||
|
||||
if (-not (Test-Path $bslPath)) { return @() }
|
||||
$lines = [System.IO.File]::ReadAllLines($bslPath, [System.Text.Encoding]::UTF8)
|
||||
$interceptors = @()
|
||||
$i = 0
|
||||
while ($i -lt $lines.Count) {
|
||||
$line = $lines[$i].Trim()
|
||||
if ($line -match '^&(Перед|После|ИзменениеИКонтроль|Вместо)\("([^"]+)"\)') {
|
||||
$type = $Matches[1]
|
||||
$method = $Matches[2]
|
||||
$interceptors += @{ Type = $type; Method = $method; Line = $i + 1; File = $bslPath }
|
||||
}
|
||||
$i++
|
||||
$result = @()
|
||||
foreach ($ic in (Get-Interceptors $lines)) {
|
||||
$result += @{ Type = $ic.Type; Raw = $ic.Raw; Method = $ic.Method; Line = $ic.Line + 1; File = $bslPath }
|
||||
}
|
||||
return $interceptors
|
||||
return $result
|
||||
}
|
||||
|
||||
# --- Helper: extract #Вставка blocks from .bsl ---
|
||||
@@ -190,12 +262,13 @@ function Get-InsertionBlocks {
|
||||
$startLine = 0
|
||||
|
||||
for ($i = 0; $i -lt $lines.Count; $i++) {
|
||||
$line = $lines[$i].Trim()
|
||||
if ($line -eq "#Вставка") {
|
||||
$line = $lines[$i]
|
||||
$kind = Get-BslMarkerKind $line
|
||||
if ($kind -eq "Insert") {
|
||||
$inBlock = $true
|
||||
$blockLines = @()
|
||||
$startLine = $i + 1
|
||||
} elseif ($line -eq "#КонецВставки" -and $inBlock) {
|
||||
} elseif ($kind -eq "EndInsert" -and $inBlock) {
|
||||
$inBlock = $false
|
||||
$blocks += @{
|
||||
StartLine = $startLine
|
||||
@@ -294,10 +367,10 @@ if ($Mode -eq "A") {
|
||||
$bslFiles = Get-BslFiles $obj.Type $obj.Name
|
||||
foreach ($bsl in $bslFiles) {
|
||||
$relPath = $bsl.Replace($ExtensionPath, "").TrimStart("\", "/")
|
||||
$interceptors = Get-Interceptors $bsl
|
||||
$interceptors = Get-FileInterceptors $bsl
|
||||
if ($interceptors.Count -gt 0) {
|
||||
foreach ($ic in $interceptors) {
|
||||
Write-Host " &$($ic.Type)(`"$($ic.Method)`") — line $($ic.Line) in $relPath"
|
||||
Write-Host " &$($ic.Raw)(`"$($ic.Method)`") — line $($ic.Line) in $relPath"
|
||||
}
|
||||
} else {
|
||||
Write-Host " $relPath (no interceptors)"
|
||||
@@ -408,7 +481,7 @@ if ($Mode -eq "B") {
|
||||
# Find .bsl files with &ИзменениеИКонтроль
|
||||
$bslFiles = Get-BslFiles $obj.Type $obj.Name
|
||||
foreach ($bsl in $bslFiles) {
|
||||
$interceptors = Get-Interceptors $bsl
|
||||
$interceptors = Get-FileInterceptors $bsl
|
||||
$macInterceptors = @($interceptors | Where-Object { $_.Type -eq "ИзменениеИКонтроль" })
|
||||
|
||||
if ($macInterceptors.Count -eq 0) { continue }
|
||||
+120
-29
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# cfe-diff v1.0 — Analyze and compare 1C configuration extension (CFE)
|
||||
# cfe-diff v1.6 — Analyze and compare 1C configuration extension (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -8,6 +8,28 @@ import re
|
||||
import sys
|
||||
from lxml import etree
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
# --- Namespace maps ---
|
||||
|
||||
MD_NSMAP = {
|
||||
@@ -58,8 +80,16 @@ CHILD_TYPE_DIR_MAP = {
|
||||
"CommandGroup": "CommandGroups",
|
||||
"DocumentNumerator": "DocumentNumerators",
|
||||
"Sequence": "Sequences",
|
||||
"ExternalDataSource": "ExternalDataSources",
|
||||
"IntegrationService": "IntegrationServices",
|
||||
"CommonAttribute": "CommonAttributes",
|
||||
"Style": "Styles",
|
||||
"XDTOPackage": "XDTOPackages",
|
||||
"WebService": "WebServices",
|
||||
"HTTPService": "HTTPServices",
|
||||
"WSReference": "WSReferences",
|
||||
"Bot": "Bots",
|
||||
"PaletteColor": "PaletteColors",
|
||||
}
|
||||
|
||||
|
||||
@@ -135,34 +165,97 @@ def get_bsl_files(obj_type, obj_name, extension_path):
|
||||
return bsl_files
|
||||
|
||||
|
||||
# --- Helper: parse interceptors from .bsl ---
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
def bsl_keywords():
|
||||
return {
|
||||
"ru": {
|
||||
"Async": "Асинх", "Proc": "Процедура", "EndProc": "КонецПроцедуры",
|
||||
"Func": "Функция", "EndFunc": "КонецФункции", "Val": "Знач",
|
||||
"Region": "Область", "EndRegion": "КонецОбласти",
|
||||
"If": "Если", "Then": "Тогда", "ElsIf": "ИначеЕсли", "Else": "Иначе", "EndIf": "КонецЕсли",
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
"And": "И", "Or": "Или", "Not": "НЕ",
|
||||
"Insert": "Вставка", "EndInsert": "КонецВставки", "Delete": "Удаление", "EndDelete": "КонецУдаления",
|
||||
"Before": "Перед", "After": "После", "Around": "Вместо", "Control": "ИзменениеИКонтроль",
|
||||
"Proceed": "ПродолжитьВызов", "Return": "Возврат",
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
"ResultVar": "Результат",
|
||||
"Directives": ["НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере"],
|
||||
},
|
||||
"en": {
|
||||
"Async": "Async", "Proc": "Procedure", "EndProc": "EndProcedure",
|
||||
"Func": "Function", "EndFunc": "EndFunction", "Val": "Val",
|
||||
"Region": "Region", "EndRegion": "EndRegion",
|
||||
"If": "If", "Then": "Then", "ElsIf": "ElsIf", "Else": "Else", "EndIf": "EndIf",
|
||||
"And": "And", "Or": "Or", "Not": "Not",
|
||||
"Insert": "Insert", "EndInsert": "EndInsert", "Delete": "Delete", "EndDelete": "EndDelete",
|
||||
"Before": "Before", "After": "After", "Around": "Around", "Control": "ChangeAndValidate",
|
||||
"Proceed": "ProceedWithCall", "Return": "Return",
|
||||
"ResultVar": "Result",
|
||||
"Directives": ["AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer"],
|
||||
},
|
||||
}
|
||||
|
||||
def get_interceptors(bsl_path):
|
||||
|
||||
BSL_KW = bsl_keywords()
|
||||
|
||||
|
||||
# Edit marker kind at the start of a line: Insert/Delete/EndInsert/EndDelete, None if none.
|
||||
# The marker owns the start of the line only — a trailing comment does not bother the platform
|
||||
# and must not bother us either.
|
||||
def bsl_marker_kind(line):
|
||||
kw = BSL_KW
|
||||
for k in ("EndInsert", "EndDelete", "Insert", "Delete"):
|
||||
if re.match(r'^\s*#(?:' + kw["ru"][k] + '|' + kw["en"][k] + r')\b', line, re.IGNORECASE):
|
||||
return k
|
||||
return None
|
||||
|
||||
|
||||
# Parse interceptor annotations present in a module. Type is normalized to the Russian spelling
|
||||
# so everything downstream stays single-language; raw keeps what the file actually says.
|
||||
def get_interceptors(lines):
|
||||
kw = BSL_KW
|
||||
keys = ("Before", "After", "Control", "Around")
|
||||
alt = []
|
||||
norm = {}
|
||||
for k in keys:
|
||||
alt.append(kw["ru"][k])
|
||||
alt.append(kw["en"][k])
|
||||
norm[kw["ru"][k].lower()] = kw["ru"][k]
|
||||
norm[kw["en"][k].lower()] = kw["ru"][k]
|
||||
pat = re.compile(r'^&(' + '|'.join(alt) + r')\("([^"]+)"\)', re.IGNORECASE)
|
||||
result = []
|
||||
for i in range(len(lines)):
|
||||
m = pat.match(lines[i].strip())
|
||||
if m:
|
||||
raw = m.group(1)
|
||||
result.append({"type": norm[raw.lower()], "raw": raw, "method": m.group(2), "line": i})
|
||||
return result
|
||||
|
||||
|
||||
# --- Helper: read a .bsl and parse its interceptors ---
|
||||
|
||||
def get_file_interceptors(bsl_path):
|
||||
if not os.path.isfile(bsl_path):
|
||||
return []
|
||||
|
||||
with open(bsl_path, "r", encoding="utf-8-sig") as fh:
|
||||
lines = fh.readlines()
|
||||
|
||||
interceptors = []
|
||||
pattern = re.compile(r'^&(\u041f\u0435\u0440\u0435\u0434|\u041f\u043e\u0441\u043b\u0435|\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435\u0418\u041a\u043e\u043d\u0442\u0440\u043e\u043b\u044c|\u0412\u043c\u0435\u0441\u0442\u043e)\("([^"]+)"\)')
|
||||
# The above is: ^&(Перед|После|ИзменениеИКонтроль|Вместо)\("([^"]+)"\)
|
||||
|
||||
for i, line in enumerate(lines):
|
||||
stripped = line.strip()
|
||||
m = pattern.match(stripped)
|
||||
if m:
|
||||
interceptors.append({
|
||||
"Type": m.group(1),
|
||||
"Method": m.group(2),
|
||||
"Line": i + 1,
|
||||
"File": bsl_path,
|
||||
})
|
||||
|
||||
return interceptors
|
||||
return [{
|
||||
"Type": ic["type"],
|
||||
"Raw": ic["raw"],
|
||||
"Method": ic["method"],
|
||||
"Line": ic["line"] + 1,
|
||||
"File": bsl_path,
|
||||
} for ic in get_interceptors(lines)]
|
||||
|
||||
|
||||
# --- Helper: extract #Вставка blocks from .bsl ---
|
||||
# --- Helper: extract insert-marker blocks from .bsl ---
|
||||
|
||||
def get_insertion_blocks(bsl_path):
|
||||
if not os.path.isfile(bsl_path):
|
||||
@@ -177,14 +270,12 @@ def get_insertion_blocks(bsl_path):
|
||||
start_line = 0
|
||||
|
||||
for i, line in enumerate(lines):
|
||||
stripped = line.strip()
|
||||
if stripped == "\u0023\u0412\u0441\u0442\u0430\u0432\u043a\u0430":
|
||||
# #Вставка
|
||||
kind = bsl_marker_kind(line)
|
||||
if kind == "Insert":
|
||||
in_block = True
|
||||
block_lines = []
|
||||
start_line = i + 1
|
||||
elif stripped == "\u0023\u041a\u043e\u043d\u0435\u0446\u0412\u0441\u0442\u0430\u0432\u043a\u0438" and in_block:
|
||||
# #КонецВставки
|
||||
elif kind == "EndInsert" and in_block:
|
||||
in_block = False
|
||||
blocks.append({
|
||||
"StartLine": start_line,
|
||||
@@ -289,10 +380,10 @@ def mode_a(objects, extension_path):
|
||||
bsl_files = get_bsl_files(obj["Type"], obj["Name"], extension_path)
|
||||
for bsl in bsl_files:
|
||||
rel_path = bsl.replace(extension_path, "").lstrip("\\/")
|
||||
interceptor_list = get_interceptors(bsl)
|
||||
interceptor_list = get_file_interceptors(bsl)
|
||||
if len(interceptor_list) > 0:
|
||||
for ic in interceptor_list:
|
||||
print(f' &{ic["Type"]}("{ic["Method"]}") \u2014 line {ic["Line"]} in {rel_path}')
|
||||
print(f' &{ic["Raw"]}("{ic["Method"]}") \u2014 line {ic["Line"]} in {rel_path}')
|
||||
else:
|
||||
print(f" {rel_path} (no interceptors)")
|
||||
|
||||
@@ -404,7 +495,7 @@ def mode_b(objects, extension_path, config_path):
|
||||
# Find .bsl files with &ИзменениеИКонтроль
|
||||
bsl_files = get_bsl_files(obj["Type"], obj["Name"], extension_path)
|
||||
for bsl in bsl_files:
|
||||
interceptor_list = get_interceptors(bsl)
|
||||
interceptor_list = get_file_interceptors(bsl)
|
||||
mac_interceptors = [ic for ic in interceptor_list if ic["Type"] == "\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435\u0418\u041a\u043e\u043d\u0442\u0440\u043e\u043b\u044c"]
|
||||
|
||||
if len(mac_interceptors) == 0:
|
||||
@@ -468,7 +559,7 @@ def main():
|
||||
parser.add_argument("-ExtensionPath", required=True, help="Path to extension dump root")
|
||||
parser.add_argument("-ConfigPath", required=True, help="Path to base config dump root")
|
||||
parser.add_argument("-Mode", choices=["A", "B"], default="A", help="A=overview, B=transfer check")
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
extension_path = args.ExtensionPath
|
||||
config_path = args.ConfigPath
|
||||
@@ -33,39 +33,39 @@ allowed-tools:
|
||||
| `Name` | Имя расширения (обязат.) | — |
|
||||
| `Synonym` | Синоним | = Name |
|
||||
| `NamePrefix` | Префикс собственных объектов | = Name + "_" |
|
||||
| `OutputDir` | Каталог для создания | `src` |
|
||||
| `OutputDir` | Каталог для создания; клади расширение в свой подкаталог, названный по имени: `src\cfe\<Name>` | `src` |
|
||||
| `Purpose` | `Patch` (исправление) / `Customization` (доработка) / `AddOn` (дополнение) | `Customization` |
|
||||
| `Version` | Версия расширения | — |
|
||||
| `Vendor` | Поставщик | — |
|
||||
| `CompatibilityMode` | Режим совместимости | `Version8_3_24` |
|
||||
| `CompatibilityMode` | Режим совместимости; при заданном `ConfigPath` определяется по базовой конфигурации и этот параметр не нужен | `Version8_3_24` |
|
||||
| `ConfigPath` | Путь к выгрузке базовой конфигурации (авто-определяет CompatibilityMode и Language UUID) | — |
|
||||
| `NoRole` | Без основной роли | false |
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-init.ps1" -Name "МоёРасширение"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-init/scripts/cfe-init.ps1" -Name "МоёРасширение" -OutputDir "src\cfe\МоёРасширение" -ConfigPath "src\cf"
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Расширение для ERP с авто-определением совместимости из базовой конфигурации
|
||||
... -Name Расш1 -ConfigPath C:\WS\tasks\cfsrc\erp_8.3.24 -OutputDir src
|
||||
... -Name Расш1 -ConfigPath src\cf -OutputDir src\cfe\Расш1
|
||||
|
||||
# Расширение-исправление с явным режимом совместимости
|
||||
... -Name Расш1 -Purpose Patch -CompatibilityMode Version8_3_17 -OutputDir src
|
||||
... -Name Расш1 -Purpose Patch -CompatibilityMode Version8_3_17 -OutputDir src\cfe\Расш1
|
||||
|
||||
# Расширение-доработка с версией
|
||||
... -Name МоёРасширение -Version "1.0.0.1" -Vendor "Компания" -OutputDir src
|
||||
... -Name МоёРасширение -Version "1.0.0.1" -Vendor "Компания" -OutputDir src\cfe\МоёРасширение
|
||||
|
||||
# Без роли, с явным префиксом
|
||||
... -Name ИсправлениеБага -NamePrefix "ИБ_" -Purpose Patch -NoRole -OutputDir src
|
||||
... -Name ИсправлениеБага -NamePrefix "ИБ_" -Purpose Patch -NoRole -OutputDir src\cfe\ИсправлениеБага
|
||||
```
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/cfe-validate <OutputDir>
|
||||
/cfe-validate <OutputDir> -ConfigPath <ConfigPath>
|
||||
```
|
||||
|
||||
+59
-18
@@ -1,5 +1,6 @@
|
||||
# cfe-init v1.2 — Create 1C configuration extension scaffold (CFE)
|
||||
# cfe-init v1.11 — Create 1C configuration extension scaffold (CFE) (+write_xml_file/write_utf8_bom: общий эталон записи)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$Name,
|
||||
@@ -16,6 +17,12 @@ param(
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Esc-XmlText {
|
||||
param([string]$s)
|
||||
# Эскейп ТЕКСТА элемента: только & < > — кавычку и апостроф платформа держит сырыми.
|
||||
return $s.Replace('&','&').Replace('<','<').Replace('>','>')
|
||||
}
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Default NamePrefix ---
|
||||
@@ -121,20 +128,23 @@ $co7 = [guid]::NewGuid().ToString()
|
||||
# --- Synonym XML ---
|
||||
$synonymXml = ""
|
||||
if ($Synonym) {
|
||||
$synonymXml = "`r`n`t`t`t`t<v8:item>`r`n`t`t`t`t`t<v8:lang>ru</v8:lang>`r`n`t`t`t`t`t<v8:content>$([System.Security.SecurityElement]::Escape($Synonym))</v8:content>`r`n`t`t`t`t</v8:item>`r`n`t`t`t"
|
||||
$synonymXml = "`r`n`t`t`t`t<v8:item>`r`n`t`t`t`t`t<v8:lang>ru</v8:lang>`r`n`t`t`t`t`t<v8:content>$(Esc-XmlText ($Synonym))</v8:content>`r`n`t`t`t`t</v8:item>`r`n`t`t`t"
|
||||
}
|
||||
|
||||
# --- Optional properties ---
|
||||
$vendorXml = if ($Vendor) { [System.Security.SecurityElement]::Escape($Vendor) } else { "" }
|
||||
$versionXml = if ($Version) { [System.Security.SecurityElement]::Escape($Version) } else { "" }
|
||||
# Элемент целиком, а не значение внутри пары: при пустом значении Конфигуратор
|
||||
# пишет <Vendor/>, а не <Vendor></Vendor>.
|
||||
$vendorEl = if ($Vendor) { "<Vendor>$(Esc-XmlText ($Vendor))</Vendor>" } else { "<Vendor/>" }
|
||||
$versionEl = if ($Version) { "<Version>$(Esc-XmlText ($Version))</Version>" } else { "<Version/>" }
|
||||
|
||||
# --- Role name ---
|
||||
$roleName = "${NamePrefix}ОсновнаяРоль"
|
||||
|
||||
# --- DefaultRoles XML ---
|
||||
$defaultRolesXml = ""
|
||||
# Элемент целиком: без роли Конфигуратор пишет <DefaultRoles/>, а не пустую пару.
|
||||
$defaultRolesEl = "<DefaultRoles/>"
|
||||
if (-not $NoRole) {
|
||||
$defaultRolesXml = "`r`n`t`t`t`t<xr:Item xsi:type=`"xr:MDObjectRef`">Role.$roleName</xr:Item>`r`n`t`t`t"
|
||||
$defaultRolesEl = "<DefaultRoles>`r`n`t`t`t`t<xr:Item xsi:type=`"xr:MDObjectRef`">Role.$roleName</xr:Item>`r`n`t`t`t</DefaultRoles>"
|
||||
}
|
||||
|
||||
# --- ChildObjects ---
|
||||
@@ -144,10 +154,32 @@ if (-not $NoRole) {
|
||||
}
|
||||
$childObjectsXml += "`r`n`t`t"
|
||||
|
||||
# Объявления пространств имён — одной переменной: места эмиссии её только интерполируют.
|
||||
# Правки шапки (как xmlns:pal в формате 2.21) делаются здесь, в одном месте.
|
||||
$xmlnsDecl = 'xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
|
||||
# Версия формата как число для сравнений: "2.20" → 220, "2.9" → 209.
|
||||
# Строковое сравнение здесь неверно ("2.9" > "2.17" лексикографически) — известная ловушка.
|
||||
function Get-FormatRank([string]$ver) {
|
||||
if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
|
||||
return 0
|
||||
}
|
||||
|
||||
# 2.21 (8.5) добавила в шапку пространство палитры — ради <Color> у значений перечисления.
|
||||
# Вставляем НА МЕСТО (после lf, перед style): платформа держит объявления по алфавиту,
|
||||
# дописать в конец нельзя.
|
||||
# Caption/ShortCaption — свойства корня из того же формата 2.21, между Version и
|
||||
# DefaultLanguage (позиция снята с выгрузки расширения из базы 8.5).
|
||||
$f221Captions = ""
|
||||
if ((Get-FormatRank $formatVersion) -ge 221) {
|
||||
$xmlnsDecl = $xmlnsDecl -replace ' xmlns:style=', ' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style='
|
||||
$f221Captions = "`r`n`t`t`t<Caption/>`r`n`t`t`t<ShortCaption/>"
|
||||
}
|
||||
|
||||
# --- Configuration.xml ---
|
||||
$cfgXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$formatVersion">
|
||||
<MetaDataObject $xmlnsDecl version="$formatVersion">
|
||||
<Configuration uuid="$uuidCfg">
|
||||
<InternalInfo>
|
||||
<xr:ContainedObject>
|
||||
@@ -181,21 +213,21 @@ $cfgXml = @"
|
||||
</InternalInfo>
|
||||
<Properties>
|
||||
<ObjectBelonging>Adopted</ObjectBelonging>
|
||||
<Name>$([System.Security.SecurityElement]::Escape($Name))</Name>
|
||||
<Name>$(Esc-XmlText ($Name))</Name>
|
||||
<Synonym>$synonymXml</Synonym>
|
||||
<Comment/>
|
||||
<ConfigurationExtensionPurpose>$Purpose</ConfigurationExtensionPurpose>
|
||||
<KeepMappingToExtendedConfigurationObjectsByIDs>true</KeepMappingToExtendedConfigurationObjectsByIDs>
|
||||
<NamePrefix>$([System.Security.SecurityElement]::Escape($NamePrefix))</NamePrefix>
|
||||
<NamePrefix>$(Esc-XmlText ($NamePrefix))</NamePrefix>
|
||||
<ConfigurationExtensionCompatibilityMode>$CompatibilityMode</ConfigurationExtensionCompatibilityMode>
|
||||
<DefaultRunMode>ManagedApplication</DefaultRunMode>
|
||||
<UsePurposes>
|
||||
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||
</UsePurposes>
|
||||
<ScriptVariant>Russian</ScriptVariant>
|
||||
<DefaultRoles>$defaultRolesXml</DefaultRoles>
|
||||
<Vendor>$vendorXml</Vendor>
|
||||
<Version>$versionXml</Version>
|
||||
$defaultRolesEl
|
||||
$vendorEl
|
||||
$versionEl$f221Captions
|
||||
<DefaultLanguage>Language.Русский</DefaultLanguage>
|
||||
<BriefInformation/>
|
||||
<DetailedInformation/>
|
||||
@@ -212,7 +244,7 @@ $cfgXml = @"
|
||||
# --- Languages/Русский.xml (adopted format) ---
|
||||
$langXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$formatVersion">
|
||||
<MetaDataObject $xmlnsDecl version="$formatVersion">
|
||||
<Language uuid="$uuidLang">
|
||||
<InternalInfo/>
|
||||
<Properties>
|
||||
@@ -229,10 +261,10 @@ $langXml = @"
|
||||
# --- Role XML ---
|
||||
$roleXml = @"
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="$formatVersion">
|
||||
<MetaDataObject $xmlnsDecl version="$formatVersion">
|
||||
<Role uuid="$uuidRole">
|
||||
<Properties>
|
||||
<Name>$([System.Security.SecurityElement]::Escape($roleName))</Name>
|
||||
<Name>$(Esc-XmlText ($roleName))</Name>
|
||||
<Synonym/>
|
||||
<Comment/>
|
||||
</Properties>
|
||||
@@ -252,9 +284,18 @@ if (-not (Test-Path $langDir)) {
|
||||
# --- Write files with UTF-8 BOM ---
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
|
||||
[System.IO.File]::WriteAllText($cfgFile, $cfgXml, $enc)
|
||||
# XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
|
||||
#
|
||||
# Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
|
||||
# копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
function Write-XmlFile([string]$path, [string]$text, $encoding) {
|
||||
$t = ($text -replace "`r`n", "`n") -replace "`n", "`r`n"
|
||||
[System.IO.File]::WriteAllText($path, $t.TrimEnd("`r", "`n"), $encoding)
|
||||
}
|
||||
|
||||
Write-XmlFile $cfgFile $cfgXml $enc
|
||||
$langFile = Join-Path $langDir "Русский.xml"
|
||||
[System.IO.File]::WriteAllText($langFile, $langXml, $enc)
|
||||
Write-XmlFile $langFile $langXml $enc
|
||||
|
||||
# --- Role ---
|
||||
if (-not $NoRole) {
|
||||
@@ -263,7 +304,7 @@ if (-not $NoRole) {
|
||||
New-Item -ItemType Directory -Path $roleDir -Force | Out-Null
|
||||
}
|
||||
$roleFile = Join-Path $roleDir "$roleName.xml"
|
||||
[System.IO.File]::WriteAllText($roleFile, $roleXml, $enc)
|
||||
Write-XmlFile $roleFile $roleXml $enc
|
||||
}
|
||||
|
||||
# --- Output ---
|
||||
+103
-22
@@ -1,20 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
# cfe-init v1.2 — Create 1C configuration extension scaffold (CFE)
|
||||
# cfe-init v1.11 — Create 1C configuration extension scaffold (CFE) (+write_xml_file/write_utf8_bom: общий эталон записи)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Generates minimal XML source files for a 1C configuration extension."""
|
||||
import sys, os, argparse, uuid
|
||||
import sys, os, re, argparse, uuid
|
||||
from xml.etree import ElementTree as ET
|
||||
|
||||
def esc_xml(s):
|
||||
return s.replace('&','&').replace('<','<').replace('>','>').replace('"','"')
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def esc_xml_text(s):
|
||||
# Эскейп ТЕКСТА элемента: только & < > — кавычку и апостроф платформа держит сырыми.
|
||||
return s.replace('&', '&').replace('<', '<').replace('>', '>')
|
||||
|
||||
def new_uuid():
|
||||
return str(uuid.uuid4())
|
||||
|
||||
def write_utf8_bom(path, content):
|
||||
# newline='' — без трансляции: иначе текстовый режим Python дал бы CRLF на Windows
|
||||
# и LF на macOS, то есть вывод навыка зависел бы от ОС.
|
||||
with open(path, 'w', encoding='utf-8-sig', newline='') as f:
|
||||
f.write(content)
|
||||
|
||||
|
||||
def write_xml_file(path, content):
|
||||
"""XML в каноне выгрузки Конфигуратора: CRLF в разделителях, без перевода в конце.
|
||||
|
||||
Копия этой функции есть в каждом навыке-эмиттере (навыки автономны). Держать
|
||||
копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
"""
|
||||
text = content.replace('\r\n', '\n').replace('\n', '\r\n').rstrip('\r\n')
|
||||
write_utf8_bom(path, text)
|
||||
|
||||
|
||||
def format_rank(ver):
|
||||
""""2.20" → 220, "2.9" → 209. Строковое сравнение неверно ("2.9" > "2.17")."""
|
||||
m = re.match(r'^(\d+)\.(\d+)$', ver or '')
|
||||
return int(m.group(1)) * 100 + int(m.group(2)) if m else 0
|
||||
|
||||
|
||||
def main():
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
@@ -29,7 +71,7 @@ def main():
|
||||
parser.add_argument('-CompatibilityMode', dest='CompatibilityMode', default='Version8_3_24')
|
||||
parser.add_argument('-ConfigPath', dest='ConfigPath', default=None)
|
||||
parser.add_argument('-NoRole', dest='NoRole', action='store_true')
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
name = args.Name
|
||||
synonym = args.Synonym if args.Synonym else name
|
||||
@@ -126,18 +168,23 @@ def main():
|
||||
# --- Synonym XML ---
|
||||
synonym_xml = ""
|
||||
if synonym:
|
||||
synonym_xml = f"\r\n\t\t\t\t<v8:item>\r\n\t\t\t\t\t<v8:lang>ru</v8:lang>\r\n\t\t\t\t\t<v8:content>{esc_xml(synonym)}</v8:content>\r\n\t\t\t\t</v8:item>\r\n\t\t\t"
|
||||
synonym_xml = f"\r\n\t\t\t\t<v8:item>\r\n\t\t\t\t\t<v8:lang>ru</v8:lang>\r\n\t\t\t\t\t<v8:content>{esc_xml_text(synonym)}</v8:content>\r\n\t\t\t\t</v8:item>\r\n\t\t\t"
|
||||
|
||||
vendor_xml = esc_xml(vendor) if vendor else ""
|
||||
version_xml = esc_xml(version) if version else ""
|
||||
# Элемент целиком, а не значение внутри пары: при пустом значении Конфигуратор
|
||||
# пишет <Vendor/>, а не <Vendor></Vendor>.
|
||||
vendor_el = f"<Vendor>{esc_xml_text(vendor)}</Vendor>" if vendor else "<Vendor/>"
|
||||
version_el = f"<Version>{esc_xml_text(version)}</Version>" if version else "<Version/>"
|
||||
|
||||
# --- Role name ---
|
||||
role_name = f"{name_prefix}ОсновнаяРоль"
|
||||
|
||||
# --- DefaultRoles XML ---
|
||||
default_roles_xml = ""
|
||||
# Элемент целиком: без роли Конфигуратор пишет <DefaultRoles/>, а не пустую пару.
|
||||
default_roles_el = "<DefaultRoles/>"
|
||||
if not args.NoRole:
|
||||
default_roles_xml = f'\r\n\t\t\t\t<xr:Item xsi:type="xr:MDObjectRef">Role.{role_name}</xr:Item>\r\n\t\t\t'
|
||||
default_roles_el = ('<DefaultRoles>\r\n\t\t\t\t'
|
||||
f'<xr:Item xsi:type="xr:MDObjectRef">Role.{role_name}</xr:Item>'
|
||||
'\r\n\t\t\t</DefaultRoles>')
|
||||
|
||||
# --- ChildObjects ---
|
||||
child_objects_xml = f"\r\n\t\t\t<Language>Русский</Language>"
|
||||
@@ -156,6 +203,40 @@ def main():
|
||||
]
|
||||
|
||||
contained_objects = ""
|
||||
|
||||
# Объявления пространств имён — одной переменной: места эмиссии её только подставляют.
|
||||
# Правки шапки (как xmlns:pal в формате 2.21) делаются здесь, в одном месте.
|
||||
xmlns_decl = (
|
||||
'xmlns="http://v8.1c.ru/8.3/MDClasses"'
|
||||
' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
|
||||
' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
|
||||
' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"'
|
||||
' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
|
||||
' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
|
||||
' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
|
||||
' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
|
||||
' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
|
||||
' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
|
||||
' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
|
||||
' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
|
||||
' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"'
|
||||
' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"'
|
||||
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
||||
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||
)
|
||||
|
||||
# 2.21 (8.5) добавила в шапку пространство палитры — ради <Color> у значений перечисления.
|
||||
# Вставляем НА МЕСТО (после lf, перед style): платформа держит объявления по алфавиту,
|
||||
# дописать в конец нельзя.
|
||||
# Caption/ShortCaption — свойства корня из того же формата 2.21, между Version и
|
||||
# DefaultLanguage (позиция снята с выгрузки расширения из базы 8.5).
|
||||
f221_captions = ""
|
||||
if format_rank(format_version) >= 221:
|
||||
xmlns_decl = xmlns_decl.replace(
|
||||
' xmlns:style=',
|
||||
' xmlns:pal="http://v8.1c.ru/8.1/data/ui/colors/palette" xmlns:style=')
|
||||
f221_captions = "\r\n\t\t\t<Caption/>\r\n\t\t\t<ShortCaption/>"
|
||||
for i in range(7):
|
||||
contained_objects += f"""\t\t\t<xr:ContainedObject>
|
||||
\t\t\t\t<xr:ClassId>{class_ids[i]}</xr:ClassId>
|
||||
@@ -163,27 +244,27 @@ def main():
|
||||
\t\t\t</xr:ContainedObject>\n"""
|
||||
|
||||
cfg_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{format_version}">
|
||||
<MetaDataObject {xmlns_decl} version="{format_version}">
|
||||
\t<Configuration uuid="{uuid_cfg}">
|
||||
\t\t<InternalInfo>
|
||||
{contained_objects}\t\t</InternalInfo>
|
||||
\t\t<Properties>
|
||||
\t\t\t<ObjectBelonging>Adopted</ObjectBelonging>
|
||||
\t\t\t<Name>{esc_xml(name)}</Name>
|
||||
\t\t\t<Name>{esc_xml_text(name)}</Name>
|
||||
\t\t\t<Synonym>{synonym_xml}</Synonym>
|
||||
\t\t\t<Comment/>
|
||||
\t\t\t<ConfigurationExtensionPurpose>{purpose}</ConfigurationExtensionPurpose>
|
||||
\t\t\t<KeepMappingToExtendedConfigurationObjectsByIDs>true</KeepMappingToExtendedConfigurationObjectsByIDs>
|
||||
\t\t\t<NamePrefix>{esc_xml(name_prefix)}</NamePrefix>
|
||||
\t\t\t<NamePrefix>{esc_xml_text(name_prefix)}</NamePrefix>
|
||||
\t\t\t<ConfigurationExtensionCompatibilityMode>{compat}</ConfigurationExtensionCompatibilityMode>
|
||||
\t\t\t<DefaultRunMode>ManagedApplication</DefaultRunMode>
|
||||
\t\t\t<UsePurposes>
|
||||
\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||
\t\t\t</UsePurposes>
|
||||
\t\t\t<ScriptVariant>Russian</ScriptVariant>
|
||||
\t\t\t<DefaultRoles>{default_roles_xml}</DefaultRoles>
|
||||
\t\t\t<Vendor>{vendor_xml}</Vendor>
|
||||
\t\t\t<Version>{version_xml}</Version>
|
||||
\t\t\t{default_roles_el}
|
||||
\t\t\t{vendor_el}
|
||||
\t\t\t{version_el}{f221_captions}
|
||||
\t\t\t<DefaultLanguage>Language.Русский</DefaultLanguage>
|
||||
\t\t\t<BriefInformation/>
|
||||
\t\t\t<DetailedInformation/>
|
||||
@@ -198,7 +279,7 @@ def main():
|
||||
|
||||
# --- Languages/Русский.xml (adopted format) ---
|
||||
lang_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{format_version}">
|
||||
<MetaDataObject {xmlns_decl} version="{format_version}">
|
||||
\t<Language uuid="{uuid_lang}">
|
||||
\t\t<InternalInfo/>
|
||||
\t\t<Properties>
|
||||
@@ -213,10 +294,10 @@ def main():
|
||||
|
||||
# --- Role XML ---
|
||||
role_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="{format_version}">
|
||||
<MetaDataObject {xmlns_decl} version="{format_version}">
|
||||
\t<Role uuid="{uuid_role}">
|
||||
\t\t<Properties>
|
||||
\t\t\t<Name>{esc_xml(role_name)}</Name>
|
||||
\t\t\t<Name>{esc_xml_text(role_name)}</Name>
|
||||
\t\t\t<Synonym/>
|
||||
\t\t\t<Comment/>
|
||||
\t\t</Properties>
|
||||
@@ -229,9 +310,9 @@ def main():
|
||||
os.makedirs(lang_dir, exist_ok=True)
|
||||
|
||||
# --- Write files ---
|
||||
write_utf8_bom(cfg_file, cfg_xml)
|
||||
write_xml_file(cfg_file, cfg_xml)
|
||||
lang_file = os.path.join(lang_dir, "Русский.xml")
|
||||
write_utf8_bom(lang_file, lang_xml)
|
||||
write_xml_file(lang_file, lang_xml)
|
||||
|
||||
# --- Role ---
|
||||
role_file = None
|
||||
@@ -239,7 +320,7 @@ def main():
|
||||
role_dir = os.path.join(output_dir, "Roles")
|
||||
os.makedirs(role_dir, exist_ok=True)
|
||||
role_file = os.path.join(role_dir, f"{role_name}.xml")
|
||||
write_utf8_bom(role_file, role_xml)
|
||||
write_xml_file(role_file, role_xml)
|
||||
|
||||
# --- Output ---
|
||||
print(f"[OK] Создано расширение: {name}")
|
||||
+12
-10
@@ -88,7 +88,7 @@ allowed-tools:
|
||||
|
||||
Правила:
|
||||
- Маркеры — на **отдельной строке с 0-й колонки** (без отступа), даже внутри отступов и текста запроса (`|…`).
|
||||
- **Незамеченные (unmarked) строки должны совпадать с оригиналом дословно** — это и есть «контроль». Если оригинал в конфигурации-источнике изменится, unmarked-контекст разойдётся → метод потребует актуализации (см. ниже; проверить пачкой — `-Check`).
|
||||
- **Незамеченные (unmarked) строки должны совпадать с оригиналом дословно** — это и есть «контроль». Дословно — включая комментарии, регистр и пробелы внутри строки (`Х = Х + 1` ≠ `Х=Х+1`); свободны только отступ и пустые строки. Если оригинал в конфигурации-источнике изменится, unmarked-контекст разойдётся → метод потребует актуализации (см. ниже; проверить пачкой — `-Check`).
|
||||
- Меняешь только свои `#Вставка`/`#Удаление`; чужой оригинал не трогай.
|
||||
|
||||
## Актуализация
|
||||
@@ -107,39 +107,41 @@ allowed-tools:
|
||||
|
||||
Повторный вызов `Before`/`After`/`Instead` для уже перехваченного метода дубль не создаёт (`[ПРОПУЩЕН]`).
|
||||
|
||||
`-Check` смотрит исходники. Вердикт платформы — уже после загрузки в базу: `/db-cfe-admin check`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/cfe-patch-method.ps1" -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-patch-method/scripts/cfe-patch-method.ps1" -ExtensionPath src\cfe\extname -ConfigPath src\cf -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||
```
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Код перед записью
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||
|
||||
# Перехват После на форме
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -ModulePath "Document.Заказ.Form.ФормаДокумента" -MethodName "ПослеЗаписиНаСервере" -InterceptorType After
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -ModulePath "Document.Заказ.Form.ФормаДокумента" -MethodName "ПослеЗаписиНаСервере" -InterceptorType After
|
||||
|
||||
# Замена функции (ПродолжитьВызов)
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -ModulePath "CommonModule.ОбщийМодуль" -MethodName "ПолучитьДанные" -InterceptorType Instead
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -ModulePath "CommonModule.ОбщийМодуль" -MethodName "ПолучитьДанные" -InterceptorType Instead
|
||||
|
||||
# ИзменениеИКонтроль — копия тела для правки маркерами
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -ModulePath "Document.РеализацияТоваров.ObjectModule" -MethodName "ОбработкаПроведения" -InterceptorType ModificationAndControl
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -ModulePath "Document.РеализацияТоваров.ObjectModule" -MethodName "ОбработкаПроведения" -InterceptorType ModificationAndControl
|
||||
|
||||
# ModulePath как путь к файлу модуля-источника (без -ConfigPath)
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ModulePath "src\cf\CommonModules\ОбщийМодуль\Ext\Module.bsl" -MethodName "ПолучитьДанные" -InterceptorType Instead
|
||||
... -ExtensionPath src\cfe\extname -ModulePath "src\cf\CommonModules\ОбщийМодуль\Ext\Module.bsl" -MethodName "ПолучитьДанные" -InterceptorType Instead
|
||||
|
||||
# Проверить все контролируемые методы расширения на дрейф
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -Check
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Check
|
||||
|
||||
# Актуализировать дрейфнувшие контролируемые методы пачкой
|
||||
... -ExtensionPath src\cfe\ИмяРасширения -ConfigPath src\cf -Actualize
|
||||
... -ExtensionPath src\cfe\extname -ConfigPath src\cf -Actualize
|
||||
```
|
||||
|
||||
## Верификация
|
||||
|
||||
```
|
||||
/cfe-validate <ExtensionPath>
|
||||
/cfe-validate <ExtensionPath> -ConfigPath <ConfigPath>
|
||||
```
|
||||
+329
-88
@@ -1,5 +1,6 @@
|
||||
# cfe-patch-method v2.5 — Source-aware method interceptor for 1C extension (CFE)
|
||||
# cfe-patch-method v2.12 — Source-aware method interceptor for 1C extension (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[string]$ExtensionPath,
|
||||
@@ -51,6 +52,105 @@ $script:decoratorMap = @{
|
||||
"ModificationAndControl"="ИзменениеИКонтроль"
|
||||
}
|
||||
|
||||
# InterceptorType -> keyword table key (emission goes through the table, the map above stays
|
||||
# the normalized value the logic compares against)
|
||||
$script:decoratorKey = @{
|
||||
"Before"="Before"; "After"="After"; "Instead"="Around"
|
||||
"ModificationAndControl"="Control"
|
||||
}
|
||||
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
function Get-BslKeywords {
|
||||
return @{
|
||||
ru = @{
|
||||
Async="Асинх"; Proc="Процедура"; EndProc="КонецПроцедуры"
|
||||
Func="Функция"; EndFunc="КонецФункции"; Val="Знач"
|
||||
Region="Область"; EndRegion="КонецОбласти"
|
||||
If="Если"; Then="Тогда"; ElsIf="ИначеЕсли"; Else="Иначе"; EndIf="КонецЕсли"
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
And="И"; Or="Или"; Not="НЕ"
|
||||
Insert="Вставка"; EndInsert="КонецВставки"; Delete="Удаление"; EndDelete="КонецУдаления"
|
||||
Before="Перед"; After="После"; Around="Вместо"; Control="ИзменениеИКонтроль"
|
||||
Proceed="ПродолжитьВызов"; Return="Возврат"
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
ResultVar="Результат"
|
||||
Directives=@("НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере")
|
||||
}
|
||||
en = @{
|
||||
Async="Async"; Proc="Procedure"; EndProc="EndProcedure"
|
||||
Func="Function"; EndFunc="EndFunction"; Val="Val"
|
||||
Region="Region"; EndRegion="EndRegion"
|
||||
If="If"; Then="Then"; ElsIf="ElsIf"; Else="Else"; EndIf="EndIf"
|
||||
And="And"; Or="Or"; Not="Not"
|
||||
Insert="Insert"; EndInsert="EndInsert"; Delete="Delete"; EndDelete="EndDelete"
|
||||
Before="Before"; After="After"; Around="Around"; Control="ChangeAndValidate"
|
||||
Proceed="ProceedWithCall"; Return="Return"
|
||||
ResultVar="Result"
|
||||
Directives=@("AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$script:bslKw = Get-BslKeywords
|
||||
|
||||
# Regex alternation for a keyword in both spellings
|
||||
function Get-KwAlt {
|
||||
param([string]$key)
|
||||
return '(?:' + $script:bslKw.ru[$key] + '|' + $script:bslKw.en[$key] + ')'
|
||||
}
|
||||
|
||||
# Spelling language of a recognized keyword. English is the discriminator: a Russian keyword
|
||||
# never equals an English one, so anything else is 'ru'.
|
||||
function Get-BslLang {
|
||||
param([string]$word)
|
||||
$w = $word.Trim().ToLower()
|
||||
foreach ($k in @("Async", "Proc", "EndProc", "Func", "EndFunc", "Region", "If", "Insert", "Delete", "Before", "After", "Around", "Control")) {
|
||||
if ($script:bslKw.en[$k].ToLower() -eq $w) { return "en" }
|
||||
}
|
||||
return "ru"
|
||||
}
|
||||
|
||||
# Edit marker kind at the start of a line: Insert/Delete/EndInsert/EndDelete, $null if none.
|
||||
# The marker owns the start of the line only — a trailing comment does not bother the platform
|
||||
# and must not bother us either.
|
||||
function Get-BslMarkerKind {
|
||||
param([string]$line)
|
||||
$kw = $script:bslKw
|
||||
foreach ($k in @("EndInsert", "EndDelete", "Insert", "Delete")) {
|
||||
if ($line -match ('^\s*#(?:' + $kw.ru[$k] + '|' + $kw.en[$k] + ')\b')) { return $k }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# Parse interceptor annotations present in a module. Type is normalized to the Russian spelling
|
||||
# so everything downstream stays single-language; Raw keeps what the file actually says.
|
||||
function Get-Interceptors {
|
||||
param($lines)
|
||||
$kw = $script:bslKw
|
||||
$keys = @("Before", "After", "Control", "Around")
|
||||
$alt = @()
|
||||
$norm = @{}
|
||||
foreach ($k in $keys) {
|
||||
$alt += $kw.ru[$k]; $alt += $kw.en[$k]
|
||||
$norm[$kw.ru[$k].ToLower()] = $kw.ru[$k]
|
||||
$norm[$kw.en[$k].ToLower()] = $kw.ru[$k]
|
||||
}
|
||||
$re = '^&(' + ($alt -join '|') + ')\("([^"]+)"\)'
|
||||
$result = @()
|
||||
for ($i = 0; $i -lt $lines.Count; $i++) {
|
||||
$t = $lines[$i].Trim()
|
||||
if ($t -match $re) {
|
||||
$raw = $Matches[1]
|
||||
$result += @{ Type = $norm[$raw.ToLower()]; Raw = $raw; Method = $Matches[2]; Line = $i }
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
# Compute relative .bsl path segments from ModulePath (used for both ext and src)
|
||||
function Get-ModuleRelPath {
|
||||
param([string]$modulePath)
|
||||
@@ -124,7 +224,8 @@ function Split-TopLevel {
|
||||
# Is a trimmed line a context-directive annotation?
|
||||
function Test-ContextDirective {
|
||||
param([string]$trimmed)
|
||||
return $trimmed -match '^&(НаКлиенте|НаСервере|НаСервереБезКонтекста|НаКлиентеНаСервереБезКонтекста|НаКлиентеНаСервере)\s*$'
|
||||
$alt = ($script:bslKw.ru.Directives + $script:bslKw.en.Directives) -join '|'
|
||||
return $trimmed -match ('^&(' + $alt + ')\s*$')
|
||||
}
|
||||
|
||||
# Read a method signature starting at declaration line; returns @{ ParamsText; EndLineIdx }
|
||||
@@ -162,46 +263,54 @@ function Read-Signature {
|
||||
|
||||
# Compute effective condition of the current branch of an #Если frame
|
||||
function Get-EffectiveCondition {
|
||||
param($frame)
|
||||
param($frame, [string]$lang)
|
||||
$kwNot = $script:bslKw[$lang].Not
|
||||
$kwAnd = $script:bslKw[$lang].And
|
||||
$conds = $frame.Conds
|
||||
$n = $conds.Count
|
||||
if ($frame.InElse) {
|
||||
$parts = @()
|
||||
foreach ($c in $conds) { $parts += "НЕ ($c)" }
|
||||
return ($parts -join " И ")
|
||||
foreach ($c in $conds) { $parts += "$kwNot ($c)" }
|
||||
return ($parts -join " $kwAnd ")
|
||||
}
|
||||
if ($n -eq 1) { return $conds[0] }
|
||||
$parts = @()
|
||||
for ($j = 0; $j -lt ($n - 1); $j++) { $parts += "НЕ ($($conds[$j]))" }
|
||||
for ($j = 0; $j -lt ($n - 1); $j++) { $parts += "$kwNot ($($conds[$j]))" }
|
||||
$parts += $conds[$n - 1]
|
||||
return ($parts -join " И ")
|
||||
return ($parts -join " $kwAnd ")
|
||||
}
|
||||
|
||||
# Extract the enclosing wrapper chain (regions + preprocessor) at a target line.
|
||||
# Returns array outer->inner of @{ Kind='region'|'if'; Name=..; Cond=.. }
|
||||
function Get-EnclosingChain {
|
||||
param($lines, [int]$targetIdx)
|
||||
param($lines, [int]$targetIdx, [string]$lang)
|
||||
$reRegion = '^#' + (Get-KwAlt 'Region') + '\s+(\S+)'
|
||||
$reEndRegion = '^#' + (Get-KwAlt 'EndRegion')
|
||||
$reIf = '^#' + (Get-KwAlt 'If') + '\s+(.+?)\s+' + (Get-KwAlt 'Then')
|
||||
$reElsIf = '^#' + (Get-KwAlt 'ElsIf') + '\s+(.+?)\s+' + (Get-KwAlt 'Then')
|
||||
$reElse = '^#' + (Get-KwAlt 'Else') + '(\s|$)'
|
||||
$reEndIf = '^#' + (Get-KwAlt 'EndIf')
|
||||
$stack = New-Object System.Collections.ArrayList
|
||||
for ($i = 0; $i -lt $targetIdx; $i++) {
|
||||
$t = $lines[$i].Trim()
|
||||
if ($t -match '^#Область\s+(\S+)') {
|
||||
if ($t -match $reRegion) {
|
||||
[void]$stack.Add(@{ Kind = 'region'; Name = $Matches[1] })
|
||||
} elseif ($t -match '^#КонецОбласти') {
|
||||
} elseif ($t -match $reEndRegion) {
|
||||
for ($k = $stack.Count - 1; $k -ge 0; $k--) { if ($stack[$k].Kind -eq 'region') { $stack.RemoveAt($k); break } }
|
||||
} elseif ($t -match '^#Если\s+(.+?)\s+Тогда') {
|
||||
} elseif ($t -match $reIf) {
|
||||
[void]$stack.Add(@{ Kind = 'if'; Conds = @($Matches[1].Trim()); InElse = $false })
|
||||
} elseif ($t -match '^#ИначеЕсли\s+(.+?)\s+Тогда') {
|
||||
} elseif ($t -match $reElsIf) {
|
||||
for ($k = $stack.Count - 1; $k -ge 0; $k--) { if ($stack[$k].Kind -eq 'if') { $stack[$k].Conds += $Matches[1].Trim(); $stack[$k].InElse = $false; break } }
|
||||
} elseif ($t -match '^#Иначе(\s|$)') {
|
||||
} elseif ($t -match $reElse) {
|
||||
for ($k = $stack.Count - 1; $k -ge 0; $k--) { if ($stack[$k].Kind -eq 'if') { $stack[$k].InElse = $true; break } }
|
||||
} elseif ($t -match '^#КонецЕсли') {
|
||||
} elseif ($t -match $reEndIf) {
|
||||
for ($k = $stack.Count - 1; $k -ge 0; $k--) { if ($stack[$k].Kind -eq 'if') { $stack.RemoveAt($k); break } }
|
||||
}
|
||||
}
|
||||
$chain = @()
|
||||
foreach ($f in $stack) {
|
||||
if ($f.Kind -eq 'region') { $chain += @{ Kind = 'region'; Name = $f.Name } }
|
||||
else { $chain += @{ Kind = 'if'; Cond = (Get-EffectiveCondition $f) } }
|
||||
else { $chain += @{ Kind = 'if'; Cond = (Get-EffectiveCondition $f $lang) } }
|
||||
}
|
||||
return ,$chain
|
||||
}
|
||||
@@ -209,13 +318,14 @@ function Get-EnclosingChain {
|
||||
# Extract a method from source .bsl lines. Returns $null if not found.
|
||||
function Extract-Method {
|
||||
param($lines, [string]$methodName)
|
||||
$declRe = '^\s*(Асинх\s+)?(Процедура|Функция)\s+(' + [regex]::Escape($methodName) + ')\s*\('
|
||||
$declRe = '^\s*(' + (Get-KwAlt 'Async') + '\s+)?(' + (Get-KwAlt 'Proc') + '|' + (Get-KwAlt 'Func') + ')\s+(' + [regex]::Escape($methodName) + ')\s*\('
|
||||
for ($i = 0; $i -lt $lines.Count; $i++) {
|
||||
if ($lines[$i] -imatch $declRe) {
|
||||
$isAsync = [bool]$Matches[1]
|
||||
$keyword = $Matches[2]
|
||||
$canonical = $Matches[3]
|
||||
$isFunction = ($keyword -ieq "Функция")
|
||||
$lang = Get-BslLang $keyword
|
||||
$isFunction = ($keyword -ieq $script:bslKw.ru.Func -or $keyword -ieq $script:bslKw.en.Func)
|
||||
|
||||
$sig = Read-Signature $lines $i
|
||||
if (-not $sig) { throw "Не удалось разобрать сигнатуру метода '$methodName'" }
|
||||
@@ -226,13 +336,13 @@ function Extract-Method {
|
||||
$paramNames = @()
|
||||
if ($paramsText.Trim().Length -gt 0) {
|
||||
foreach ($seg in (Split-TopLevel $paramsText)) {
|
||||
$s = $seg.Trim() -replace '^Знач\s+', ''
|
||||
$s = $seg.Trim() -replace ('^' + (Get-KwAlt 'Val') + '\s+'), ''
|
||||
if ($s -match '^([\w]+)') { $paramNames += $Matches[1] }
|
||||
}
|
||||
}
|
||||
|
||||
# Body: from sigEnd+1 to matching Конец*
|
||||
$endRe = if ($isFunction) { '^\s*КонецФункции\b' } else { '^\s*КонецПроцедуры\b' }
|
||||
$endRe = if ($isFunction) { '^\s*' + (Get-KwAlt 'EndFunc') + '\b' } else { '^\s*' + (Get-KwAlt 'EndProc') + '\b' }
|
||||
$bodyStart = $sigEnd + 1
|
||||
$bodyEnd = -1
|
||||
for ($j = $bodyStart; $j -lt $lines.Count; $j++) {
|
||||
@@ -250,10 +360,11 @@ function Extract-Method {
|
||||
}
|
||||
|
||||
# Enclosing chain (regions + preprocessor)
|
||||
$chain = Get-EnclosingChain $lines $i
|
||||
$chain = Get-EnclosingChain $lines $i $lang
|
||||
|
||||
return @{
|
||||
Canonical = $canonical
|
||||
Lang = $lang
|
||||
IsFunction = $isFunction
|
||||
IsAsync = $isAsync
|
||||
ParamsText = $paramsText
|
||||
@@ -270,25 +381,13 @@ function Extract-Method {
|
||||
return $null
|
||||
}
|
||||
|
||||
# Parse interceptors present in a module (type + method)
|
||||
function Get-Interceptors {
|
||||
param($lines)
|
||||
$result = @()
|
||||
for ($i = 0; $i -lt $lines.Count; $i++) {
|
||||
$t = $lines[$i].Trim()
|
||||
if ($t -match '^&(Перед|После|ИзменениеИКонтроль|Вместо)\("([^"]+)"\)') {
|
||||
$result += @{ Type = $Matches[1]; Method = $Matches[2]; Line = $i }
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
# Parse declared procedure/function names in a module
|
||||
function Get-ProcNames {
|
||||
param($lines)
|
||||
$re = '^\s*(?:' + (Get-KwAlt 'Async') + '\s+)?(?:' + (Get-KwAlt 'Proc') + '|' + (Get-KwAlt 'Func') + ')\s+([\w]+)\s*\('
|
||||
$names = @()
|
||||
foreach ($line in $lines) {
|
||||
if ($line -imatch '^\s*(?:Асинх\s+)?(?:Процедура|Функция)\s+([\w]+)\s*\(') { $names += $Matches[1] }
|
||||
if ($line -imatch $re) { $names += $Matches[1] }
|
||||
}
|
||||
return $names
|
||||
}
|
||||
@@ -299,14 +398,15 @@ function Get-ProcNames {
|
||||
function Build-InterceptorCore {
|
||||
param($method, [string]$interceptorType, [string]$interceptorName)
|
||||
|
||||
$decoratorRu = $script:decoratorMap[$interceptorType]
|
||||
$asyncPrefix = if ($method.IsAsync) { "Асинх " } else { "" }
|
||||
$keyword = if ($method.IsFunction) { "Функция" } else { "Процедура" }
|
||||
$endKeyword = if ($method.IsFunction) { "КонецФункции" } else { "КонецПроцедуры" }
|
||||
$kw = $script:bslKw[$method.Lang]
|
||||
$decorator = $kw[$script:decoratorKey[$interceptorType]]
|
||||
$asyncPrefix = if ($method.IsAsync) { "$($kw.Async) " } else { "" }
|
||||
$keyword = if ($method.IsFunction) { $kw.Func } else { $kw.Proc }
|
||||
$endKeyword = if ($method.IsFunction) { $kw.EndFunc } else { $kw.EndProc }
|
||||
|
||||
$lines = @()
|
||||
if ($method.Context) { $lines += $method.Context }
|
||||
$lines += "&$decoratorRu(`"$($method.Canonical)`")"
|
||||
$lines += "&$decorator(`"$($method.Canonical)`")"
|
||||
$lines += "$asyncPrefix$keyword $interceptorName($($method.ParamsText))"
|
||||
|
||||
switch ($interceptorType) {
|
||||
@@ -319,11 +419,11 @@ function Build-InterceptorCore {
|
||||
"Instead" {
|
||||
$namesJoined = ($method.ParamNames -join ", ")
|
||||
if ($method.IsFunction) {
|
||||
$lines += "`tРезультат = ПродолжитьВызов($namesJoined);"
|
||||
$lines += "`t$($kw.ResultVar) = $($kw.Proceed)($namesJoined);"
|
||||
$lines += "`t// TODO: доработать поведение"
|
||||
$lines += "`tВозврат Результат;"
|
||||
$lines += "`t$($kw.Return) $($kw.ResultVar);"
|
||||
} else {
|
||||
$lines += "`tПродолжитьВызов($namesJoined);"
|
||||
$lines += "`t$($kw.Proceed)($namesJoined);"
|
||||
$lines += "`t// TODO: доработать поведение"
|
||||
}
|
||||
}
|
||||
@@ -338,16 +438,17 @@ function Build-InterceptorCore {
|
||||
# Wrap core with region/preprocessor lines, adding blank lines ("air") around
|
||||
# each structural boundary. Empty chain -> core as-is.
|
||||
function Build-WrappedBlock {
|
||||
param($chainArr, $core)
|
||||
param($chainArr, $core, [string]$lang)
|
||||
$kw = $script:bslKw[$lang]
|
||||
$b = @()
|
||||
foreach ($w in $chainArr) {
|
||||
if ($w.Kind -eq 'region') { $b += "#Область $($w.Name)" } else { $b += "#Если $($w.Cond) Тогда" }
|
||||
if ($w.Kind -eq 'region') { $b += "#$($kw.Region) $($w.Name)" } else { $b += "#$($kw.If) $($w.Cond) $($kw.Then)" }
|
||||
$b += ""
|
||||
}
|
||||
$b += $core
|
||||
for ($c = $chainArr.Count - 1; $c -ge 0; $c--) {
|
||||
$b += ""
|
||||
if ($chainArr[$c].Kind -eq 'region') { $b += "#КонецОбласти" } else { $b += "#КонецЕсли" }
|
||||
if ($chainArr[$c].Kind -eq 'region') { $b += "#$($kw.EndRegion)" } else { $b += "#$($kw.EndIf)" }
|
||||
}
|
||||
return $b
|
||||
}
|
||||
@@ -361,6 +462,22 @@ function Get-Normalized {
|
||||
return (($line -replace '\s+', ' ').Trim())
|
||||
}
|
||||
|
||||
# Control comparison key, as the platform compares a &ИзменениеИКонтроль copy with the original:
|
||||
# each line trimmed, blank lines dropped, everything else byte-for-byte and case-sensitive
|
||||
# (inner spaces, comments and letter case are significant). Measured on 8.3.24 and 8.3.27.
|
||||
function Get-ControlKey {
|
||||
param($lines)
|
||||
return (@($lines | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) -join "`n")
|
||||
}
|
||||
|
||||
# Parameter count of a signature params text. The platform compares only the number of
|
||||
# parameters of a &ИзменениеИКонтроль copy (names and default values it ignores).
|
||||
function Get-ParamCount {
|
||||
param([string]$paramsText)
|
||||
if ([string]::IsNullOrWhiteSpace($paramsText)) { return 0 }
|
||||
return @(Split-TopLevel $paramsText | Where-Object { $_.Trim() -ne '' }).Count
|
||||
}
|
||||
|
||||
# Reconstruct v1 body and edit ops from a marked body
|
||||
function Parse-MarkedBody {
|
||||
param($bodyLines)
|
||||
@@ -368,20 +485,27 @@ function Parse-MarkedBody {
|
||||
$ops = @() # edit operations
|
||||
$i = 0
|
||||
while ($i -lt $bodyLines.Count) {
|
||||
$t = $bodyLines[$i].Trim()
|
||||
if ($t -eq '#Вставка') {
|
||||
$kind = Get-BslMarkerKind $bodyLines[$i]
|
||||
if ($kind -eq 'Insert') {
|
||||
# Marker lines are kept verbatim: they carry the author's spelling, indent and — since
|
||||
# a tail comment is legal — the note explaining the edit. Re-emitting a bare keyword
|
||||
# would silently drop that note on -Actualize.
|
||||
$open = $bodyLines[$i]
|
||||
$ins = @()
|
||||
$i++
|
||||
while ($i -lt $bodyLines.Count -and $bodyLines[$i].Trim() -ne '#КонецВставки') { $ins += $bodyLines[$i]; $i++ }
|
||||
while ($i -lt $bodyLines.Count -and (Get-BslMarkerKind $bodyLines[$i]) -ne 'EndInsert') { $ins += $bodyLines[$i]; $i++ }
|
||||
$close = if ($i -lt $bodyLines.Count) { $bodyLines[$i] } else { $null }
|
||||
$i++ # skip #КонецВставки
|
||||
$ops += @{ Kind = 'insert'; After = ($v1.Count - 1); Lines = $ins }
|
||||
} elseif ($t -eq '#Удаление') {
|
||||
$ops += @{ Kind = 'insert'; After = ($v1.Count - 1); Lines = $ins; Open = $open; Close = $close }
|
||||
} elseif ($kind -eq 'Delete') {
|
||||
$open = $bodyLines[$i]
|
||||
$startIdx = $v1.Count
|
||||
$i++
|
||||
$del = @()
|
||||
while ($i -lt $bodyLines.Count -and $bodyLines[$i].Trim() -ne '#КонецУдаления') { $del += $bodyLines[$i]; $v1 += $bodyLines[$i]; $i++ }
|
||||
while ($i -lt $bodyLines.Count -and (Get-BslMarkerKind $bodyLines[$i]) -ne 'EndDelete') { $del += $bodyLines[$i]; $v1 += $bodyLines[$i]; $i++ }
|
||||
$close = if ($i -lt $bodyLines.Count) { $bodyLines[$i] } else { $null }
|
||||
$i++ # skip #КонецУдаления
|
||||
$ops += @{ Kind = 'delete'; Start = $startIdx; End = ($v1.Count - 1); Lines = $del }
|
||||
$ops += @{ Kind = 'delete'; Start = $startIdx; End = ($v1.Count - 1); Lines = $del; Open = $open; Close = $close }
|
||||
} else {
|
||||
$v1 += $bodyLines[$i]
|
||||
$i++
|
||||
@@ -577,7 +701,8 @@ function Get-ResyncConflictReason {
|
||||
|
||||
# Write per-method conflict folder: conflict.md + base/local/remote
|
||||
function Write-ConflictFolder {
|
||||
param($folder, $methodId, $extBsl, $existingName, $method, $v1, $markedBody, $v2, $v1norm, $v2norm, $disputed, $enc)
|
||||
param($folder, $methodId, $extBsl, $existingName, $method, $v1, $markedBody, $v2, $v1norm, $v2norm, $disputed, [string]$lang, $enc)
|
||||
$kw = $script:bslKw[$lang]
|
||||
if (-not (Test-Path $folder)) { New-Item -ItemType Directory -Path $folder -Force | Out-Null }
|
||||
[IO.File]::WriteAllText((Join-Path $folder 'base.bsl'), (($v1 -join "`r`n") + "`r`n"), $enc)
|
||||
[IO.File]::WriteAllText((Join-Path $folder 'local.bsl'), (($markedBody -join "`r`n") + "`r`n"), $enc)
|
||||
@@ -585,7 +710,7 @@ function Write-ConflictFolder {
|
||||
$md = @()
|
||||
$md += "# $methodId"
|
||||
$md += "Править: $extBsl"
|
||||
$md += "Метод: $existingName (&ИзменениеИКонтроль(`"$($method.Canonical)`"))"
|
||||
$md += "Метод: $existingName (&$($kw.Control)(`"$($method.Canonical)`"))"
|
||||
$md += "Причина: $(Get-ResyncConflictReason $disputed)"
|
||||
$md += ""
|
||||
$md += "## Не размещено — перенести вручную"
|
||||
@@ -597,10 +722,12 @@ function Write-ConflictFolder {
|
||||
$md += "### Конфликт №$cn — вставка"
|
||||
$md += "Как блок стоял в вашей версии (local):"
|
||||
if ($d.Before -and $d.Before.Count -gt 0) { foreach ($l in $d.Before) { $md += $l } }
|
||||
$md += "#Вставка"; foreach ($l in $d.Lines) { $md += $l }; $md += "#КонецВставки"
|
||||
$openLine = if ([string]::IsNullOrEmpty($d.Open)) { "#$($kw.Insert)" } else { $d.Open }
|
||||
$closeLine = if ([string]::IsNullOrEmpty($d.Close)) { "#$($kw.EndInsert)" } else { $d.Close }
|
||||
$md += $openLine; foreach ($l in $d.Lines) { $md += $l }; $md += $closeLine
|
||||
if ($d.After -and $d.After.Count -gt 0) { foreach ($l in $d.After) { $md += $l } }
|
||||
$md += ""
|
||||
$md += "Якорь (строки вокруг #Вставка) изменился/исчез в новом оригинале — блок не лёг автоматически (см. дифф base→remote ниже)."
|
||||
$md += "Якорь (строки вокруг #$($kw.Insert)) изменился/исчез в новом оригинале — блок не лёг автоматически (см. дифф base→remote ниже)."
|
||||
$md += "В модуле расширения блок припаркован в конце метода под меткой // [РЕСИНК-КОНФЛИКТ №$cn] — найди по ней."
|
||||
$md += "Куда переносить: если якорного кода в новом методе больше нет — он, вероятно, вынесен/отрефакторен (ищите в диффе новый вызов/процедуру). Размести адаптацию по смыслу: например пост-обработкой после нового вызова, либо в заимствованной процедуре, куда переехал код. При правке файла сохрани кодировку (UTF-8 с BOM)."
|
||||
} else {
|
||||
@@ -627,15 +754,20 @@ function Invoke-Resync {
|
||||
$methodId = "$logicalModule.$($method.Canonical)"
|
||||
$decLine = $dup.Line
|
||||
$sigLineIdx = $decLine + 1
|
||||
if ($sigLineIdx -ge $extLines.Count -or $extLines[$sigLineIdx] -notmatch '^\s*(?:Асинх\s+)?(?:Процедура|Функция)\s+([\w]+)\s*\(') {
|
||||
$declRe = '^\s*(?:' + (Get-KwAlt 'Async') + '\s+)?(' + (Get-KwAlt 'Proc') + '|' + (Get-KwAlt 'Func') + ')\s+([\w]+)\s*\('
|
||||
if ($sigLineIdx -ge $extLines.Count -or $extLines[$sigLineIdx] -notmatch $declRe) {
|
||||
return @{ Id = $methodId; Status = 'ОШИБКА'; ExtBsl = $extBsl; Reason = 'не разобрать сигнатуру перехватчика' }
|
||||
}
|
||||
$existingName = $Matches[1]
|
||||
# The block we are about to rewrite is the interceptor already in the extension, so it is
|
||||
# its spelling — not the source module's — that the rewritten block must keep.
|
||||
$lang = Get-BslLang $Matches[1]
|
||||
$kw = $script:bslKw[$lang]
|
||||
$existingName = $Matches[2]
|
||||
$sig = Read-Signature $extLines $sigLineIdx
|
||||
if (-not $sig) { return @{ Id = $methodId; Status = 'ОШИБКА'; ExtBsl = $extBsl; Reason = 'не разобрать сигнатуру' } }
|
||||
$sigEnd = $sig.EndLineIdx
|
||||
$isFunc = ($extLines[$sigLineIdx] -imatch '^\s*(?:Асинх\s+)?Функция\b')
|
||||
$endRe = if ($isFunc) { '^\s*КонецФункции\b' } else { '^\s*КонецПроцедуры\b' }
|
||||
$isFunc = ($extLines[$sigLineIdx] -imatch ('^\s*(?:' + (Get-KwAlt 'Async') + '\s+)?' + (Get-KwAlt 'Func') + '\b'))
|
||||
$endRe = if ($isFunc) { '^\s*' + (Get-KwAlt 'EndFunc') + '\b' } else { '^\s*' + (Get-KwAlt 'EndProc') + '\b' }
|
||||
$blockEnd = -1
|
||||
for ($j = $sigEnd + 1; $j -lt $extLines.Count; $j++) { if ($extLines[$j] -imatch $endRe) { $blockEnd = $j; break } }
|
||||
if ($blockEnd -lt 0) { return @{ Id = $methodId; Status = 'ОШИБКА'; ExtBsl = $extBsl; Reason = 'не найден конец перехватчика' } }
|
||||
@@ -650,7 +782,14 @@ function Invoke-Resync {
|
||||
$v1norm = @($v1 | ForEach-Object { Get-Normalized $_ })
|
||||
$v2norm = @($v2 | ForEach-Object { Get-Normalized $_ })
|
||||
|
||||
if (($v1norm -join "`n") -eq ($v2norm -join "`n")) {
|
||||
# Signature: the platform rejects the interceptor when the parameter COUNT differs, so a
|
||||
# body-only comparison would miss a vendor-added parameter. Names/defaults it ignores.
|
||||
$extParamCount = Get-ParamCount $sig.ParamsText
|
||||
$srcParamCount = Get-ParamCount $method.ParamsText
|
||||
$paramsDrift = ($extParamCount -ne $srcParamCount)
|
||||
$paramsReason = if ($paramsDrift) { "список параметров: в оригинале $srcParamCount, в перехватчике $extParamCount" } else { '' }
|
||||
|
||||
if (-not $paramsDrift -and [string]::Equals((Get-ControlKey $v1), (Get-ControlKey $v2), 'Ordinal')) {
|
||||
return @{ Id = $methodId; Status = 'АКТУАЛЕН'; ExtBsl = $extBsl }
|
||||
}
|
||||
|
||||
@@ -679,14 +818,14 @@ function Invoke-Resync {
|
||||
elseif ($null -eq $k) {
|
||||
$dbefore = @(); if ($op.After -ge 0) { $bz = [Math]::Max(0, $op.After - 2); for ($z = $bz; $z -le $op.After; $z++) { $dbefore += $v1[$z] } }
|
||||
$dafter = @(); $az = [Math]::Min($v1.Count - 1, $op.After + 3); for ($z = $op.After + 1; $z -le $az; $z++) { $dafter += $v1[$z] }
|
||||
$disputed += @{ Kind = 'insert'; Lines = $op.Lines; Before = $dbefore; After = $dafter }
|
||||
$disputed += @{ Kind = 'insert'; Lines = $op.Lines; Open = $op.Open; Close = $op.Close; Before = $dbefore; After = $dafter }
|
||||
}
|
||||
elseif ($k -lt 0) { $insertTop += ,$op.Lines; $transferred += @{ Kind = 'insert' } }
|
||||
else { if (-not $insertAfter.ContainsKey($k)) { $insertAfter[$k] = @() }; $insertAfter[$k] += ,$op.Lines; $transferred += @{ Kind = 'insert' } }
|
||||
elseif ($k -lt 0) { $insertTop += $op; $transferred += @{ Kind = 'insert' } }
|
||||
else { if (-not $insertAfter.ContainsKey($k)) { $insertAfter[$k] = @() }; $insertAfter[$k] += $op; $transferred += @{ Kind = 'insert' } }
|
||||
} else {
|
||||
$keys = @(); for ($m = $op.Start; $m -le $op.End; $m++) { $keys += $v1norm[$m] }
|
||||
$p = Find-UniqueRun $v2norm $keys
|
||||
if ($p -ge 0) { $delStart[$p] = $true; $delEnd[$p + $keys.Count - 1] = $true; $transferred += @{ Kind = 'delete' } }
|
||||
if ($p -ge 0) { $delStart[$p] = $op.Open; $delEnd[$p + $keys.Count - 1] = $op.Close; $transferred += @{ Kind = 'delete' } }
|
||||
else {
|
||||
# Nearest significant neighbours around the deleted block; adjacency in the significant
|
||||
# projection means the block is already cut (blanks/comments left behind don't matter).
|
||||
@@ -700,18 +839,22 @@ function Invoke-Resync {
|
||||
|
||||
if ($ReportOnly) {
|
||||
$st = if ($disputed.Count -gt 0) { 'КОНФЛИКТ' } elseif ($transferred.Count -eq 0 -and $absorbed.Count -gt 0) { 'ПЕРЕНЕСЕНО В ОСНОВНУЮ' } else { 'ДРЕЙФ' }
|
||||
if ($paramsDrift -and $st -eq 'ПЕРЕНЕСЕНО В ОСНОВНУЮ') { $st = 'ДРЕЙФ' }
|
||||
$rsn = if ($disputed.Count -gt 0) { Get-ResyncConflictReason $disputed } elseif ($st -eq 'ПЕРЕНЕСЕНО В ОСНОВНУЮ') { 'все правки уже в основной конфигурации' } else { '' }
|
||||
if ($paramsDrift) { $rsn = if ($rsn) { "$paramsReason; $rsn" } else { $paramsReason } }
|
||||
return @{ Id = $methodId; Status = $st; ExtBsl = $extBsl; Transferred = $transferred.Count; Absorbed = $absorbed.Count; Disputed = $disputed.Count; Reason = $rsn; AbsorbedNotes = $absorbedNotes }
|
||||
}
|
||||
|
||||
# assemble new marked body
|
||||
# assemble new marked body. Marker lines come back as they were read (Open/Close); the keyword
|
||||
# form is only a fallback for a block whose closing marker the module never had.
|
||||
$mk = { param($orig, [string]$key) if ([string]::IsNullOrEmpty($orig)) { "#$($kw[$key])" } else { $orig } }
|
||||
$newBody = @()
|
||||
foreach ($blk in $insertTop) { $newBody += "#Вставка"; foreach ($l in $blk) { $newBody += $l }; $newBody += "#КонецВставки" }
|
||||
foreach ($blk in $insertTop) { $newBody += (& $mk $blk.Open 'Insert'); foreach ($l in $blk.Lines) { $newBody += $l }; $newBody += (& $mk $blk.Close 'EndInsert') }
|
||||
for ($k = 0; $k -lt $v2.Count; $k++) {
|
||||
if ($delStart.ContainsKey($k)) { $newBody += "#Удаление" }
|
||||
if ($delStart.ContainsKey($k)) { $newBody += (& $mk $delStart[$k] 'Delete') }
|
||||
$newBody += $v2[$k]
|
||||
if ($delEnd.ContainsKey($k)) { $newBody += "#КонецУдаления" }
|
||||
if ($insertAfter.ContainsKey($k)) { foreach ($blk in $insertAfter[$k]) { $newBody += "#Вставка"; foreach ($l in $blk) { $newBody += $l }; $newBody += "#КонецВставки" } }
|
||||
if ($delEnd.ContainsKey($k)) { $newBody += (& $mk $delEnd[$k] 'EndDelete') }
|
||||
if ($insertAfter.ContainsKey($k)) { foreach ($blk in $insertAfter[$k]) { $newBody += (& $mk $blk.Open 'Insert'); foreach ($l in $blk.Lines) { $newBody += $l }; $newBody += (& $mk $blk.Close 'EndInsert') } }
|
||||
}
|
||||
if ($disputed.Count -gt 0) {
|
||||
$newBody += "`t// [РЕСИНК-КОНФЛИКТ] блоки ниже не легли автоматически — перенесите вручную (по № см. conflict.md / index.md в merge-воркспейсе, путь в выводе)."
|
||||
@@ -720,7 +863,7 @@ function Invoke-Resync {
|
||||
$cn++
|
||||
if ($d.Kind -eq 'insert') {
|
||||
$newBody += "`t// [РЕСИНК-КОНФЛИКТ №$cn] вставка — исходный якорь изменён в новом оригинале."
|
||||
$newBody += "#Вставка"; foreach ($l in $d.Lines) { $newBody += $l }; $newBody += "#КонецВставки"
|
||||
$newBody += (& $mk $d.Open 'Insert'); foreach ($l in $d.Lines) { $newBody += $l }; $newBody += (& $mk $d.Close 'EndInsert')
|
||||
}
|
||||
else {
|
||||
$newBody += "`t// [РЕСИНК-КОНФЛИКТ №$cn] удаление — строки не найдены в новом оригинале:"
|
||||
@@ -728,12 +871,12 @@ function Invoke-Resync {
|
||||
}
|
||||
}
|
||||
}
|
||||
$asyncPrefix = if ($method.IsAsync) { "Асинх " } else { "" }
|
||||
$keyword = if ($method.IsFunction) { "Функция" } else { "Процедура" }
|
||||
$endKeyword = if ($method.IsFunction) { "КонецФункции" } else { "КонецПроцедуры" }
|
||||
$asyncPrefix = if ($method.IsAsync) { "$($kw.Async) " } else { "" }
|
||||
$keyword = if ($method.IsFunction) { $kw.Func } else { $kw.Proc }
|
||||
$endKeyword = if ($method.IsFunction) { $kw.EndFunc } else { $kw.EndProc }
|
||||
$newBlock = @()
|
||||
if ($method.Context) { $newBlock += $method.Context }
|
||||
$newBlock += "&ИзменениеИКонтроль(`"$($method.Canonical)`")"
|
||||
$newBlock += "&$($kw.Control)(`"$($method.Canonical)`")"
|
||||
$newBlock += "$asyncPrefix$keyword $existingName($($method.ParamsText))"
|
||||
$newBlock += $newBody
|
||||
$newBlock += $endKeyword
|
||||
@@ -749,7 +892,7 @@ function Invoke-Resync {
|
||||
$conflictDir = $null
|
||||
if ($disputed.Count -gt 0) {
|
||||
$conflictDir = $conflictFolder
|
||||
Write-ConflictFolder $conflictFolder $methodId $extBsl $existingName $method $v1 $markedBody $v2 $v1norm $v2norm $disputed $enc
|
||||
Write-ConflictFolder $conflictFolder $methodId $extBsl $existingName $method $v1 $markedBody $v2 $v1norm $v2norm $disputed $lang $enc
|
||||
}
|
||||
$status = if ($disputed.Count -gt 0) { 'ЧАСТИЧНО' } elseif ($transferred.Count -eq 0 -and $absorbed.Count -gt 0) { 'ПЕРЕНЕСЕНО В ОСНОВНУЮ' } else { 'АКТУАЛИЗИРОВАН' }
|
||||
$rsn = if ($disputed.Count -gt 0) { Get-ResyncConflictReason $disputed } elseif ($status -eq 'ПЕРЕНЕСЕНО В ОСНОВНУЮ') { 'все правки уже в основной конфигурации — перехватчик можно удалить' } else { '' }
|
||||
@@ -788,6 +931,100 @@ if (Test-Path $ExtensionPath -PathType Leaf) { $ExtensionPath = Split-Path $Exte
|
||||
$cfgFile = Join-Path $ExtensionPath "Configuration.xml"
|
||||
if (-not (Test-Path $cfgFile)) { Write-Error "Configuration.xml не найден в расширении: $ExtensionPath"; exit 1 }
|
||||
|
||||
# --- Пометка расширенного свойства (<xr:PropertyState>) ---
|
||||
# Свойство появилось в формате 2.19 (8.3.26): на 2.18 и ниже платформа молча выбрасывает элемент
|
||||
# при загрузке. С 2.19 Конфигуратор ставит его сам при выгрузке. Правило: флаг ставит тот, кто
|
||||
# создал файл модуля, — здесь это мы. Имя свойства = базовое имя файла модуля.
|
||||
# Копии этих функций есть в cfe-borrow (навыки автономны); держать их одинаковыми — сознательно.
|
||||
function Get-FormatRank([string]$ver) {
|
||||
if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
|
||||
return 0
|
||||
}
|
||||
|
||||
function Detect-FormatVersion([string]$dir) {
|
||||
$d = $dir
|
||||
while ($d) {
|
||||
# Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
|
||||
# корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
|
||||
$extPath = "$d.xml"
|
||||
if (Test-Path $extPath) {
|
||||
$extText = [System.IO.File]::ReadAllText($extPath, [System.Text.Encoding]::UTF8)
|
||||
$extHead = $extText.Substring(0, [Math]::Min(2000, $extText.Length))
|
||||
if ($extHead -match '<(ExternalDataProcessor|ExternalReport)[ >]' -and $extHead -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
|
||||
}
|
||||
$cfgPath = Join-Path $d "Configuration.xml"
|
||||
if (Test-Path $cfgPath) {
|
||||
$cfgText = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8)
|
||||
# Длину среза берём по СТРОКЕ, а не по размеру файла: размер в БАЙТАХ, Substring считает
|
||||
# СИМВОЛЫ, и на кириллице байт больше — короткий Configuration.xml ронял навык исключением.
|
||||
$head = $cfgText.Substring(0, [Math]::Min(2000, $cfgText.Length))
|
||||
if ($head -match '<MetaDataObject[^>]+version="(\d+\.\d+)"') { return $Matches[1] }
|
||||
}
|
||||
$parent = Split-Path $d -Parent
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return "2.17"
|
||||
}
|
||||
|
||||
function Build-PropertyStateXml {
|
||||
param([string]$propertyName, [string]$indent)
|
||||
|
||||
$sb = New-Object System.Text.StringBuilder
|
||||
$sb.AppendLine("${indent}<xr:PropertyState>") | Out-Null
|
||||
$sb.AppendLine("${indent}`t<xr:Property>${propertyName}</xr:Property>") | Out-Null
|
||||
$sb.AppendLine("${indent}`t<xr:State>Extended</xr:State>") | Out-Null
|
||||
$sb.Append("${indent}</xr:PropertyState>") | Out-Null
|
||||
return $sb.ToString()
|
||||
}
|
||||
|
||||
function Set-PropertyStateFlag {
|
||||
param([string]$objFile, [string]$propertyName, [string]$formatVersion)
|
||||
|
||||
if ((Get-FormatRank $formatVersion) -lt 219) { return }
|
||||
if (-not (Test-Path $objFile)) { return }
|
||||
|
||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||
$text = [System.IO.File]::ReadAllText($objFile, $enc)
|
||||
$nl = if ($text -match "`r`n") { "`r`n" } else { "`n" }
|
||||
|
||||
# ПЕРВЫЙ <InternalInfo> в файле — собственный у объекта: у реквизитов и подобъектов свои,
|
||||
# но они лежат ниже, внутри <ChildObjects>.
|
||||
$empty = [regex]::Match($text, '([ \t]*)<InternalInfo\s*/>')
|
||||
$open = [regex]::Match($text, '(?s)([ \t]*)<InternalInfo>(.*?)</InternalInfo>')
|
||||
|
||||
if ($empty.Success -and (-not $open.Success -or $empty.Index -lt $open.Index)) {
|
||||
$ind = $empty.Groups[1].Value
|
||||
$block = Build-PropertyStateXml $propertyName ($ind + "`t")
|
||||
$replacement = "${ind}<InternalInfo>${nl}${block}${nl}${ind}</InternalInfo>"
|
||||
$text = $text.Remove($empty.Index, $empty.Length).Insert($empty.Index, $replacement)
|
||||
} elseif ($open.Success) {
|
||||
if ($open.Groups[2].Value -match "<xr:Property>$([regex]::Escape($propertyName))</xr:Property>") { return }
|
||||
$ind = $open.Groups[1].Value
|
||||
$block = Build-PropertyStateXml $propertyName ($ind + "`t")
|
||||
# Дописываем в КОНЕЦ InternalInfo: у Конфигуратора PropertyState идёт после GeneratedType.
|
||||
$closeAt = $open.Index + $open.Length - "</InternalInfo>".Length - $ind.Length
|
||||
$text = $text.Insert($closeAt, "${block}${nl}")
|
||||
} else {
|
||||
return
|
||||
}
|
||||
|
||||
[System.IO.File]::WriteAllText($objFile, $text, $enc)
|
||||
}
|
||||
|
||||
# Модуль формы сюда не попадает: у формы флаг называется Form и ставится при заимствовании,
|
||||
# а не при появлении модуля (замер на 8.3.26 — пустой модуль формы платформа не выгружает).
|
||||
function Get-ModuleFlagTarget {
|
||||
param([string[]]$relParts, [string]$extRoot)
|
||||
|
||||
if ($relParts.Count -ne 4 -or $relParts[2] -ne "Ext") { return $null }
|
||||
$prop = [System.IO.Path]::GetFileNameWithoutExtension($relParts[3])
|
||||
return @{
|
||||
File = (Join-Path (Join-Path $extRoot $relParts[0]) "$($relParts[1]).xml")
|
||||
Property = $prop
|
||||
}
|
||||
}
|
||||
|
||||
# --- Read NamePrefix ---
|
||||
$cfgDoc = New-Object System.Xml.XmlDocument
|
||||
$cfgDoc.PreserveWhitespace = $false
|
||||
@@ -942,6 +1179,8 @@ if ($method.IsFunction -and ($InterceptorType -eq "Before" -or $InterceptorType
|
||||
}
|
||||
|
||||
$decoratorRu = $script:decoratorMap[$InterceptorType]
|
||||
# What the annotation will actually look like in the module: the source's spelling
|
||||
$decoratorOut = $script:bslKw[$method.Lang][$script:decoratorKey[$InterceptorType]]
|
||||
|
||||
# --- Read existing extension module (if any) ---
|
||||
$extLines = @()
|
||||
@@ -958,7 +1197,7 @@ $enc = New-Object System.Text.UTF8Encoding($true)
|
||||
|
||||
if ($dup) {
|
||||
if ($InterceptorType -ne "ModificationAndControl") {
|
||||
Write-Host "[ПРОПУЩЕН] Перехватчик &$decoratorRu(`"$MethodName`") уже есть в модуле — дубль не создаётся."
|
||||
Write-Host "[ПРОПУЩЕН] Перехватчик &$($dup.Raw)(`"$MethodName`") уже есть в модуле — дубль не создаётся."
|
||||
Write-Host " Файл: $extBsl"
|
||||
exit 0
|
||||
}
|
||||
@@ -1003,11 +1242,7 @@ $candidate = "${namePrefix}$($method.Canonical)"
|
||||
$taken = @($existingProcNames | ForEach-Object { $_.ToLower() })
|
||||
$interceptorName = $candidate
|
||||
if ($taken -contains $candidate.ToLower()) {
|
||||
if ($InterceptorType -eq "ModificationAndControl") {
|
||||
$interceptorName = "${candidate}_ИзменениеИКонтроль"
|
||||
} else {
|
||||
$interceptorName = "${candidate}_$decoratorRu"
|
||||
}
|
||||
$interceptorName = "${candidate}_$($script:bslKw[$method.Lang][$script:decoratorKey[$InterceptorType]])"
|
||||
}
|
||||
|
||||
$core = Build-InterceptorCore $method $InterceptorType $interceptorName
|
||||
@@ -1022,7 +1257,7 @@ if ($extExists) {
|
||||
if ($chain[$c].Kind -eq 'region') {
|
||||
$rname = $chain[$c].Name
|
||||
for ($li = 0; $li -lt $extLines.Count; $li++) {
|
||||
if ($extLines[$li].Trim() -match ('^#Область\s+' + [regex]::Escape($rname) + '\s*$')) {
|
||||
if ($extLines[$li].Trim() -match ('^#' + (Get-KwAlt 'Region') + '\s+' + [regex]::Escape($rname) + '\s*$')) {
|
||||
$reuseRegionIdx = $c; $reuseLineIdx = $li; break
|
||||
}
|
||||
}
|
||||
@@ -1037,14 +1272,14 @@ if ($reuseRegionIdx -ge 0) {
|
||||
$innerChain = @()
|
||||
for ($c = $reuseRegionIdx + 1; $c -lt $chain.Count; $c++) { $innerChain += $chain[$c] }
|
||||
|
||||
$block = Build-WrappedBlock $innerChain $core
|
||||
$block = Build-WrappedBlock $innerChain $core $method.Lang
|
||||
|
||||
# find matching #КонецОбласти for the reused region
|
||||
$depth = 0; $closeIdx = -1
|
||||
for ($li = $reuseLineIdx; $li -lt $extLines.Count; $li++) {
|
||||
$t = $extLines[$li].Trim()
|
||||
if ($t -match '^#Область\s') { $depth++ }
|
||||
elseif ($t -match '^#КонецОбласти') { $depth--; if ($depth -eq 0) { $closeIdx = $li; break } }
|
||||
if ($t -match ('^#' + (Get-KwAlt 'Region') + '\s')) { $depth++ }
|
||||
elseif ($t -match ('^#' + (Get-KwAlt 'EndRegion'))) { $depth--; if ($depth -eq 0) { $closeIdx = $li; break } }
|
||||
}
|
||||
if ($closeIdx -lt 0) { Write-Error "Не найден #КонецОбласти для региона (переиспользование)"; exit 1 }
|
||||
|
||||
@@ -1061,7 +1296,7 @@ if ($reuseRegionIdx -ge 0) {
|
||||
$placement = "в существующий регион '$($chain[$reuseRegionIdx].Name)'"
|
||||
} else {
|
||||
# Build full wrapper chain (source order) and append (or create file).
|
||||
$block = Build-WrappedBlock $chain $core
|
||||
$block = Build-WrappedBlock $chain $core $method.Lang
|
||||
$blockText = ($block -join "`r`n") + "`r`n"
|
||||
|
||||
$bslDir = Split-Path $extBsl -Parent
|
||||
@@ -1084,7 +1319,13 @@ if ($reuseRegionIdx -ge 0) {
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "[OK] Перехватчик &$decoratorRu(`"$MethodName`") — $placement"
|
||||
# Модуль в расширении есть — отражаем это в метаданных объекта (формат ≥ 2.19).
|
||||
$flagTarget = Get-ModuleFlagTarget $relParts $ExtensionPath
|
||||
if ($flagTarget) {
|
||||
Set-PropertyStateFlag $flagTarget.File $flagTarget.Property (Detect-FormatVersion $ExtensionPath)
|
||||
}
|
||||
|
||||
Write-Host "[OK] Перехватчик &$decoratorOut(`"$MethodName`") — $placement"
|
||||
Write-Host " Файл: $extBsl"
|
||||
Write-Host " Процедура: $interceptorName($($method.ParamsText -replace '\s+', ' '))"
|
||||
if ($method.Context) { Write-Host " Контекст: $($method.Context)" }
|
||||
+372
-79
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# cfe-patch-method v2.5 — Source-aware method interceptor for 1C extension (CFE)
|
||||
# cfe-patch-method v2.12 — Source-aware method interceptor for 1C extension (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -10,6 +10,28 @@ import sys
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
TYPE_DIR_MAP = {
|
||||
"Catalog": "Catalogs", "Document": "Documents", "Enum": "Enums",
|
||||
"CommonModule": "CommonModules", "Report": "Reports", "DataProcessor": "DataProcessors",
|
||||
@@ -19,6 +41,24 @@ TYPE_DIR_MAP = {
|
||||
"BusinessProcess": "BusinessProcesses", "Task": "Tasks",
|
||||
"InformationRegister": "InformationRegisters", "AccumulationRegister": "AccumulationRegisters",
|
||||
"AccountingRegister": "AccountingRegisters", "CalculationRegister": "CalculationRegisters",
|
||||
# Прощающий ввод: имя каталога принимается наравне с именем типа (Catalogs.X ≡ Catalog.X) —
|
||||
# PS1-порт так умел с самого начала, PY отставал.
|
||||
"Catalogs": "Catalogs",
|
||||
"Documents": "Documents",
|
||||
"Enums": "Enums",
|
||||
"CommonModules": "CommonModules",
|
||||
"Reports": "Reports",
|
||||
"DataProcessors": "DataProcessors",
|
||||
"ExchangePlans": "ExchangePlans",
|
||||
"ChartsOfAccounts": "ChartsOfAccounts",
|
||||
"ChartsOfCharacteristicTypes": "ChartsOfCharacteristicTypes",
|
||||
"ChartsOfCalculationTypes": "ChartsOfCalculationTypes",
|
||||
"BusinessProcesses": "BusinessProcesses",
|
||||
"Tasks": "Tasks",
|
||||
"InformationRegisters": "InformationRegisters",
|
||||
"AccumulationRegisters": "AccumulationRegisters",
|
||||
"AccountingRegisters": "AccountingRegisters",
|
||||
"CalculationRegisters": "CalculationRegisters",
|
||||
}
|
||||
# accept plural forms too
|
||||
for _v in list(TYPE_DIR_MAP.values()):
|
||||
@@ -30,11 +70,179 @@ DECORATOR_MAP = {
|
||||
"ModificationAndControl": "ИзменениеИКонтроль",
|
||||
}
|
||||
|
||||
# InterceptorType -> keyword table key (emission goes through the table, the map above stays
|
||||
# the normalized value the logic compares against)
|
||||
DECORATOR_KEY = {
|
||||
"Before": "Before", "After": "After", "Instead": "Around",
|
||||
"ModificationAndControl": "Control",
|
||||
}
|
||||
|
||||
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
def bsl_keywords():
|
||||
return {
|
||||
"ru": {
|
||||
"Async": "Асинх", "Proc": "Процедура", "EndProc": "КонецПроцедуры",
|
||||
"Func": "Функция", "EndFunc": "КонецФункции", "Val": "Знач",
|
||||
"Region": "Область", "EndRegion": "КонецОбласти",
|
||||
"If": "Если", "Then": "Тогда", "ElsIf": "ИначеЕсли", "Else": "Иначе", "EndIf": "КонецЕсли",
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
"And": "И", "Or": "Или", "Not": "НЕ",
|
||||
"Insert": "Вставка", "EndInsert": "КонецВставки", "Delete": "Удаление", "EndDelete": "КонецУдаления",
|
||||
"Before": "Перед", "After": "После", "Around": "Вместо", "Control": "ИзменениеИКонтроль",
|
||||
"Proceed": "ПродолжитьВызов", "Return": "Возврат",
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
"ResultVar": "Результат",
|
||||
"Directives": ["НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере"],
|
||||
},
|
||||
"en": {
|
||||
"Async": "Async", "Proc": "Procedure", "EndProc": "EndProcedure",
|
||||
"Func": "Function", "EndFunc": "EndFunction", "Val": "Val",
|
||||
"Region": "Region", "EndRegion": "EndRegion",
|
||||
"If": "If", "Then": "Then", "ElsIf": "ElsIf", "Else": "Else", "EndIf": "EndIf",
|
||||
"And": "And", "Or": "Or", "Not": "Not",
|
||||
"Insert": "Insert", "EndInsert": "EndInsert", "Delete": "Delete", "EndDelete": "EndDelete",
|
||||
"Before": "Before", "After": "After", "Around": "Around", "Control": "ChangeAndValidate",
|
||||
"Proceed": "ProceedWithCall", "Return": "Return",
|
||||
"ResultVar": "Result",
|
||||
"Directives": ["AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
BSL_KW = bsl_keywords()
|
||||
|
||||
|
||||
# Regex alternation for a keyword in both spellings
|
||||
def kw_alt(key):
|
||||
return '(?:' + BSL_KW["ru"][key] + '|' + BSL_KW["en"][key] + ')'
|
||||
|
||||
|
||||
# Spelling language of a recognized keyword. English is the discriminator: a Russian keyword
|
||||
# never equals an English one, so anything else is 'ru'.
|
||||
def bsl_lang(word):
|
||||
w = word.strip().lower()
|
||||
for k in ("Async", "Proc", "EndProc", "Func", "EndFunc", "Region", "If", "Insert", "Delete",
|
||||
"Before", "After", "Around", "Control"):
|
||||
if BSL_KW["en"][k].lower() == w:
|
||||
return "en"
|
||||
return "ru"
|
||||
|
||||
|
||||
# Edit marker kind at the start of a line: Insert/Delete/EndInsert/EndDelete, None if none.
|
||||
# The marker owns the start of the line only — a trailing comment does not bother the platform
|
||||
# and must not bother us either.
|
||||
def bsl_marker_kind(line):
|
||||
kw = BSL_KW
|
||||
for k in ("EndInsert", "EndDelete", "Insert", "Delete"):
|
||||
if re.match(r'^\s*#(?:' + kw["ru"][k] + '|' + kw["en"][k] + r')\b', line, re.IGNORECASE):
|
||||
return k
|
||||
return None
|
||||
|
||||
|
||||
CONTEXT_RE = re.compile(
|
||||
r'^&(НаКлиенте|НаСервере|НаСервереБезКонтекста|НаКлиентеНаСервереБезКонтекста|НаКлиентеНаСервере)\s*$'
|
||||
r'^&(' + '|'.join(BSL_KW["ru"]["Directives"] + BSL_KW["en"]["Directives"]) + r')\s*$',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
# --- Пометка расширенного свойства (<xr:PropertyState>) ---
|
||||
# Свойство появилось в формате 2.19 (8.3.26): на 2.18 и ниже платформа молча выбрасывает элемент
|
||||
# при загрузке. С 2.19 Конфигуратор ставит его сам при выгрузке. Правило: флаг ставит тот, кто
|
||||
# создал файл модуля, — здесь это мы. Имя свойства = базовое имя файла модуля.
|
||||
# Копии этих функций есть в cfe-borrow (навыки автономны); держать их одинаковыми — сознательно.
|
||||
def detect_format_version(d):
|
||||
while d:
|
||||
# Автономная внешняя обработка/отчёт: своего Configuration.xml у неё нет, версию несёт
|
||||
# корень самой обработки. Без этого форма и макет внутри обработки 2.21 писались бы 2.17.
|
||||
ext_path = d + ".xml"
|
||||
if os.path.isfile(ext_path):
|
||||
with open(ext_path, "r", encoding="utf-8-sig") as f:
|
||||
ext_head = f.read(2000)
|
||||
if re.search(r'<(ExternalDataProcessor|ExternalReport)[ >]', ext_head):
|
||||
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', ext_head)
|
||||
if m:
|
||||
return m.group(1)
|
||||
cfg_path = os.path.join(d, "Configuration.xml")
|
||||
if os.path.isfile(cfg_path):
|
||||
with open(cfg_path, "r", encoding="utf-8-sig") as f:
|
||||
head = f.read(2000)
|
||||
m = re.search(r'<MetaDataObject[^>]+version="(\d+\.\d+)"', head)
|
||||
if m:
|
||||
return m.group(1)
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return "2.17"
|
||||
|
||||
|
||||
def format_rank(ver):
|
||||
""""2.20" → 220, "2.9" → 209. Строковое сравнение неверно ("2.9" > "2.17")."""
|
||||
m = re.match(r'^(\d+)\.(\d+)$', ver or '')
|
||||
return int(m.group(1)) * 100 + int(m.group(2)) if m else 0
|
||||
|
||||
|
||||
def build_property_state_xml(property_name, indent):
|
||||
return "\n".join([
|
||||
f"{indent}<xr:PropertyState>",
|
||||
f"{indent}\t<xr:Property>{property_name}</xr:Property>",
|
||||
f"{indent}\t<xr:State>Extended</xr:State>",
|
||||
f"{indent}</xr:PropertyState>",
|
||||
])
|
||||
|
||||
|
||||
def set_property_state_flag(obj_file, property_name, format_version):
|
||||
if format_rank(format_version) < 219:
|
||||
return
|
||||
if not os.path.isfile(obj_file):
|
||||
return
|
||||
|
||||
with open(obj_file, "r", encoding="utf-8-sig", newline="") as fh:
|
||||
text = fh.read()
|
||||
nl = "\r\n" if "\r\n" in text else "\n"
|
||||
|
||||
# ПЕРВЫЙ <InternalInfo> в файле — собственный у объекта: у реквизитов и подобъектов свои,
|
||||
# но они лежат ниже, внутри <ChildObjects>.
|
||||
empty = re.search(r"([ \t]*)<InternalInfo\s*/>", text)
|
||||
opened = re.search(r"([ \t]*)<InternalInfo>(.*?)</InternalInfo>", text, re.S)
|
||||
|
||||
if empty and (not opened or empty.start() < opened.start()):
|
||||
ind = empty.group(1)
|
||||
block = build_property_state_xml(property_name, ind + "\t")
|
||||
replacement = f"{ind}<InternalInfo>{nl}{block}{nl}{ind}</InternalInfo>"
|
||||
text = text[:empty.start()] + replacement + text[empty.end():]
|
||||
elif opened:
|
||||
if re.search(rf"<xr:Property>{re.escape(property_name)}</xr:Property>", opened.group(2)):
|
||||
return
|
||||
ind = opened.group(1)
|
||||
block = build_property_state_xml(property_name, ind + "\t")
|
||||
# Дописываем в КОНЕЦ InternalInfo: у Конфигуратора PropertyState идёт после GeneratedType.
|
||||
close_at = opened.end() - len("</InternalInfo>") - len(ind)
|
||||
text = text[:close_at] + block + nl + text[close_at:]
|
||||
else:
|
||||
return
|
||||
|
||||
with open(obj_file, "w", encoding="utf-8-sig", newline="") as fh:
|
||||
fh.write(text)
|
||||
|
||||
|
||||
# Модуль формы сюда не попадает: у формы флаг называется Form и ставится при заимствовании,
|
||||
# а не при появлении модуля (замер на 8.3.26 — пустой модуль формы платформа не выгружает).
|
||||
def get_module_flag_target(rel_parts, ext_root):
|
||||
if len(rel_parts) != 4 or rel_parts[2] != "Ext":
|
||||
return None
|
||||
prop = os.path.splitext(rel_parts[3])[0]
|
||||
return {
|
||||
"file": os.path.join(ext_root, rel_parts[0], f"{rel_parts[1]}.xml"),
|
||||
"property": prop,
|
||||
}
|
||||
|
||||
|
||||
def get_module_rel_path(module_path):
|
||||
parts = module_path.split(".")
|
||||
if len(parts) < 2:
|
||||
@@ -167,37 +375,45 @@ def read_signature(lines, start_idx):
|
||||
return None
|
||||
|
||||
|
||||
def effective_condition(frame):
|
||||
def effective_condition(frame, lang):
|
||||
kw_not = BSL_KW[lang]["Not"]
|
||||
kw_and = BSL_KW[lang]["And"]
|
||||
conds = frame["conds"]
|
||||
n = len(conds)
|
||||
if frame["in_else"]:
|
||||
return " И ".join("НЕ (%s)" % c for c in conds)
|
||||
return (" %s " % kw_and).join("%s (%s)" % (kw_not, c) for c in conds)
|
||||
if n == 1:
|
||||
return conds[0]
|
||||
parts = ["НЕ (%s)" % conds[j] for j in range(n - 1)]
|
||||
parts = ["%s (%s)" % (kw_not, conds[j]) for j in range(n - 1)]
|
||||
parts.append(conds[n - 1])
|
||||
return " И ".join(parts)
|
||||
return (" %s " % kw_and).join(parts)
|
||||
|
||||
|
||||
def get_enclosing_chain(lines, target_idx):
|
||||
def get_enclosing_chain(lines, target_idx, lang):
|
||||
re_region = re.compile(r'^#' + kw_alt("Region") + r'\s+(\S+)', re.IGNORECASE)
|
||||
re_end_region = re.compile(r'^#' + kw_alt("EndRegion"), re.IGNORECASE)
|
||||
re_if = re.compile(r'^#' + kw_alt("If") + r'\s+(.+?)\s+' + kw_alt("Then"), re.IGNORECASE)
|
||||
re_elsif = re.compile(r'^#' + kw_alt("ElsIf") + r'\s+(.+?)\s+' + kw_alt("Then"), re.IGNORECASE)
|
||||
re_else = re.compile(r'^#' + kw_alt("Else") + r'(\s|$)', re.IGNORECASE)
|
||||
re_endif = re.compile(r'^#' + kw_alt("EndIf"), re.IGNORECASE)
|
||||
stack = []
|
||||
for i in range(target_idx):
|
||||
t = lines[i].strip()
|
||||
m = re.match(r'^#Область\s+(\S+)', t)
|
||||
m = re_region.match(t)
|
||||
if m:
|
||||
stack.append({"kind": "region", "name": m.group(1)})
|
||||
continue
|
||||
if re.match(r'^#КонецОбласти', t):
|
||||
if re_end_region.match(t):
|
||||
for k in range(len(stack) - 1, -1, -1):
|
||||
if stack[k]["kind"] == "region":
|
||||
del stack[k]
|
||||
break
|
||||
continue
|
||||
m = re.match(r'^#Если\s+(.+?)\s+Тогда', t)
|
||||
m = re_if.match(t)
|
||||
if m:
|
||||
stack.append({"kind": "if", "conds": [m.group(1).strip()], "in_else": False})
|
||||
continue
|
||||
m = re.match(r'^#ИначеЕсли\s+(.+?)\s+Тогда', t)
|
||||
m = re_elsif.match(t)
|
||||
if m:
|
||||
for k in range(len(stack) - 1, -1, -1):
|
||||
if stack[k]["kind"] == "if":
|
||||
@@ -205,13 +421,13 @@ def get_enclosing_chain(lines, target_idx):
|
||||
stack[k]["in_else"] = False
|
||||
break
|
||||
continue
|
||||
if re.match(r'^#Иначе(\s|$)', t):
|
||||
if re_else.match(t):
|
||||
for k in range(len(stack) - 1, -1, -1):
|
||||
if stack[k]["kind"] == "if":
|
||||
stack[k]["in_else"] = True
|
||||
break
|
||||
continue
|
||||
if re.match(r'^#КонецЕсли', t):
|
||||
if re_endif.match(t):
|
||||
for k in range(len(stack) - 1, -1, -1):
|
||||
if stack[k]["kind"] == "if":
|
||||
del stack[k]
|
||||
@@ -222,13 +438,14 @@ def get_enclosing_chain(lines, target_idx):
|
||||
if f["kind"] == "region":
|
||||
chain.append({"kind": "region", "name": f["name"]})
|
||||
else:
|
||||
chain.append({"kind": "if", "cond": effective_condition(f)})
|
||||
chain.append({"kind": "if", "cond": effective_condition(f, lang)})
|
||||
return chain
|
||||
|
||||
|
||||
def extract_method(lines, method_name):
|
||||
decl_re = re.compile(
|
||||
r'^\s*(Асинх\s+)?(Процедура|Функция)\s+(' + re.escape(method_name) + r')\s*\(',
|
||||
r'^\s*(' + kw_alt("Async") + r'\s+)?(' + kw_alt("Proc") + '|' + kw_alt("Func") + r')\s+('
|
||||
+ re.escape(method_name) + r')\s*\(',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
for i in range(len(lines)):
|
||||
@@ -238,7 +455,8 @@ def extract_method(lines, method_name):
|
||||
is_async = bool(m.group(1))
|
||||
keyword = m.group(2)
|
||||
canonical = m.group(3)
|
||||
is_function = keyword.lower() == "функция"
|
||||
lang = bsl_lang(keyword)
|
||||
is_function = keyword.lower() in (BSL_KW["ru"]["Func"].lower(), BSL_KW["en"]["Func"].lower())
|
||||
|
||||
sig = read_signature(lines, i)
|
||||
if not sig:
|
||||
@@ -248,12 +466,12 @@ def extract_method(lines, method_name):
|
||||
param_names = []
|
||||
if params_text.strip():
|
||||
for seg in split_top_level(params_text):
|
||||
s = re.sub(r'^Знач\s+', '', seg.strip())
|
||||
s = re.sub(r'^' + kw_alt("Val") + r'\s+', '', seg.strip(), flags=re.IGNORECASE)
|
||||
mm = re.match(r'^([\w]+)', s)
|
||||
if mm:
|
||||
param_names.append(mm.group(1))
|
||||
|
||||
end_re = re.compile(r'^\s*КонецФункции\b' if is_function else r'^\s*КонецПроцедуры\b',
|
||||
end_re = re.compile(r'^\s*' + (kw_alt("EndFunc") if is_function else kw_alt("EndProc")) + r'\b',
|
||||
re.IGNORECASE)
|
||||
body_start = sig_end + 1
|
||||
body_end = -1
|
||||
@@ -271,10 +489,11 @@ def extract_method(lines, method_name):
|
||||
if is_context_directive(prev):
|
||||
context = prev
|
||||
|
||||
chain = get_enclosing_chain(lines, i)
|
||||
chain = get_enclosing_chain(lines, i, lang)
|
||||
|
||||
return {
|
||||
"canonical": canonical,
|
||||
"lang": lang,
|
||||
"is_function": is_function,
|
||||
"is_async": is_async,
|
||||
"params_text": params_text,
|
||||
@@ -289,19 +508,32 @@ def extract_method(lines, method_name):
|
||||
return None
|
||||
|
||||
|
||||
# Parse interceptor annotations present in a module. Type is normalized to the Russian spelling
|
||||
# so everything downstream stays single-language; raw keeps what the file actually says.
|
||||
def get_interceptors(lines):
|
||||
kw = BSL_KW
|
||||
keys = ("Before", "After", "Control", "Around")
|
||||
alt = []
|
||||
norm = {}
|
||||
for k in keys:
|
||||
alt.append(kw["ru"][k])
|
||||
alt.append(kw["en"][k])
|
||||
norm[kw["ru"][k].lower()] = kw["ru"][k]
|
||||
norm[kw["en"][k].lower()] = kw["ru"][k]
|
||||
pat = re.compile(r'^&(' + '|'.join(alt) + r')\("([^"]+)"\)', re.IGNORECASE)
|
||||
result = []
|
||||
pat = re.compile(r'^&(Перед|После|ИзменениеИКонтроль|Вместо)\("([^"]+)"\)')
|
||||
for i in range(len(lines)):
|
||||
m = pat.match(lines[i].strip())
|
||||
if m:
|
||||
result.append({"type": m.group(1), "method": m.group(2), "line": i})
|
||||
raw = m.group(1)
|
||||
result.append({"type": norm[raw.lower()], "raw": raw, "method": m.group(2), "line": i})
|
||||
return result
|
||||
|
||||
|
||||
def get_proc_names(lines):
|
||||
names = []
|
||||
pat = re.compile(r'^\s*(?:Асинх\s+)?(?:Процедура|Функция)\s+([\w]+)\s*\(', re.IGNORECASE)
|
||||
pat = re.compile(r'^\s*(?:' + kw_alt("Async") + r'\s+)?(?:' + kw_alt("Proc") + '|' + kw_alt("Func")
|
||||
+ r')\s+([\w]+)\s*\(', re.IGNORECASE)
|
||||
for line in lines:
|
||||
m = pat.match(line)
|
||||
if m:
|
||||
@@ -310,15 +542,16 @@ def get_proc_names(lines):
|
||||
|
||||
|
||||
def build_interceptor_core(method, interceptor_type, interceptor_name):
|
||||
decorator_ru = DECORATOR_MAP[interceptor_type]
|
||||
async_prefix = "Асинх " if method["is_async"] else ""
|
||||
keyword = "Функция" if method["is_function"] else "Процедура"
|
||||
end_keyword = "КонецФункции" if method["is_function"] else "КонецПроцедуры"
|
||||
kw = BSL_KW[method["lang"]]
|
||||
decorator = kw[DECORATOR_KEY[interceptor_type]]
|
||||
async_prefix = (kw["Async"] + " ") if method["is_async"] else ""
|
||||
keyword = kw["Func"] if method["is_function"] else kw["Proc"]
|
||||
end_keyword = kw["EndFunc"] if method["is_function"] else kw["EndProc"]
|
||||
|
||||
lines = []
|
||||
if method["context"]:
|
||||
lines.append(method["context"])
|
||||
lines.append('&%s("%s")' % (decorator_ru, method["canonical"]))
|
||||
lines.append('&%s("%s")' % (decorator, method["canonical"]))
|
||||
lines.append("%s%s %s(%s)" % (async_prefix, keyword, interceptor_name, method["params_text"]))
|
||||
|
||||
if interceptor_type == "Before":
|
||||
@@ -328,11 +561,11 @@ def build_interceptor_core(method, interceptor_type, interceptor_name):
|
||||
elif interceptor_type == "Instead":
|
||||
names_joined = ", ".join(method["param_names"])
|
||||
if method["is_function"]:
|
||||
lines.append("\tРезультат = ПродолжитьВызов(%s);" % names_joined)
|
||||
lines.append("\t%s = %s(%s);" % (kw["ResultVar"], kw["Proceed"], names_joined))
|
||||
lines.append("\t// TODO: доработать поведение")
|
||||
lines.append("\tВозврат Результат;")
|
||||
lines.append("\t%s %s;" % (kw["Return"], kw["ResultVar"]))
|
||||
else:
|
||||
lines.append("\tПродолжитьВызов(%s);" % names_joined)
|
||||
lines.append("\t%s(%s);" % (kw["Proceed"], names_joined))
|
||||
lines.append("\t// TODO: доработать поведение")
|
||||
elif interceptor_type == "ModificationAndControl":
|
||||
lines.extend(method["body_lines"])
|
||||
@@ -341,16 +574,18 @@ def build_interceptor_core(method, interceptor_type, interceptor_name):
|
||||
return lines
|
||||
|
||||
|
||||
def build_wrapped_block(chain_arr, core):
|
||||
def build_wrapped_block(chain_arr, core, lang):
|
||||
"""Wrap core with region/preprocessor lines, adding blank lines around each boundary."""
|
||||
kw = BSL_KW[lang]
|
||||
b = []
|
||||
for w in chain_arr:
|
||||
b.append("#Область %s" % w["name"] if w["kind"] == "region" else "#Если %s Тогда" % w["cond"])
|
||||
b.append(("#%s %s" % (kw["Region"], w["name"])) if w["kind"] == "region"
|
||||
else ("#%s %s %s" % (kw["If"], w["cond"], kw["Then"])))
|
||||
b.append("")
|
||||
b.extend(core)
|
||||
for w in reversed(chain_arr):
|
||||
b.append("")
|
||||
b.append("#КонецОбласти" if w["kind"] == "region" else "#КонецЕсли")
|
||||
b.append(("#" + kw["EndRegion"]) if w["kind"] == "region" else ("#" + kw["EndIf"]))
|
||||
return b
|
||||
|
||||
|
||||
@@ -358,31 +593,55 @@ def normalize(line):
|
||||
return re.sub(r'\s+', ' ', line).strip()
|
||||
|
||||
|
||||
# Control comparison key, as the platform compares a &ИзменениеИКонтроль copy with the original:
|
||||
# each line trimmed, blank lines dropped, everything else byte-for-byte and case-sensitive
|
||||
# (inner spaces, comments and letter case are significant). Measured on 8.3.24 and 8.3.27.
|
||||
def control_key(lines):
|
||||
return "\n".join([k for k in (x.strip() for x in lines) if k != ""])
|
||||
|
||||
|
||||
# Parameter count of a signature params text. The platform compares only the number of
|
||||
# parameters of a &ИзменениеИКонтроль copy (names and default values it ignores).
|
||||
def param_count(params_text):
|
||||
if not params_text or not params_text.strip():
|
||||
return 0
|
||||
return len([p for p in split_top_level(params_text) if p.strip()])
|
||||
|
||||
|
||||
def parse_marked_body(body_lines):
|
||||
v1 = []
|
||||
ops = []
|
||||
i = 0
|
||||
n = len(body_lines)
|
||||
while i < n:
|
||||
t = body_lines[i].strip()
|
||||
if t == "#Вставка":
|
||||
kind = bsl_marker_kind(body_lines[i])
|
||||
if kind == "Insert":
|
||||
# Marker lines are kept verbatim: they carry the author's spelling, indent and — since
|
||||
# a tail comment is legal — the note explaining the edit. Re-emitting a bare keyword
|
||||
# would silently drop that note on -Actualize.
|
||||
open_line = body_lines[i]
|
||||
ins = []
|
||||
i += 1
|
||||
while i < n and body_lines[i].strip() != "#КонецВставки":
|
||||
while i < n and bsl_marker_kind(body_lines[i]) != "EndInsert":
|
||||
ins.append(body_lines[i])
|
||||
i += 1
|
||||
close_line = body_lines[i] if i < n else None
|
||||
i += 1
|
||||
ops.append({"kind": "insert", "after": len(v1) - 1, "lines": ins})
|
||||
elif t == "#Удаление":
|
||||
ops.append({"kind": "insert", "after": len(v1) - 1, "lines": ins,
|
||||
"open": open_line, "close": close_line})
|
||||
elif kind == "Delete":
|
||||
open_line = body_lines[i]
|
||||
start_idx = len(v1)
|
||||
i += 1
|
||||
dels = []
|
||||
while i < n and body_lines[i].strip() != "#КонецУдаления":
|
||||
while i < n and bsl_marker_kind(body_lines[i]) != "EndDelete":
|
||||
dels.append(body_lines[i])
|
||||
v1.append(body_lines[i])
|
||||
i += 1
|
||||
close_line = body_lines[i] if i < n else None
|
||||
i += 1
|
||||
ops.append({"kind": "delete", "start": start_idx, "end": len(v1) - 1, "lines": dels})
|
||||
ops.append({"kind": "delete", "start": start_idx, "end": len(v1) - 1, "lines": dels,
|
||||
"open": open_line, "close": close_line})
|
||||
else:
|
||||
v1.append(body_lines[i])
|
||||
i += 1
|
||||
@@ -539,7 +798,7 @@ def main():
|
||||
choices=["", "Before", "After", "Instead", "ModificationAndControl"])
|
||||
parser.add_argument("-Check", action="store_true")
|
||||
parser.add_argument("-Actualize", action="store_true")
|
||||
args = parser.parse_args()
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
extension_path = args.ExtensionPath
|
||||
config_path = args.ConfigPath
|
||||
@@ -731,6 +990,8 @@ def main():
|
||||
"(перехват &Перед/&После к функциям неприменим)." % method_name)
|
||||
|
||||
decorator_ru = DECORATOR_MAP[interceptor_type]
|
||||
# What the annotation will actually look like in the module: the source's spelling
|
||||
decorator_out = BSL_KW[method["lang"]][DECORATOR_KEY[interceptor_type]]
|
||||
|
||||
# --- Read existing extension module (if any) ---
|
||||
ext_exists = os.path.isfile(ext_bsl)
|
||||
@@ -748,7 +1009,7 @@ def main():
|
||||
if dup:
|
||||
if interceptor_type != "ModificationAndControl":
|
||||
print('[ПРОПУЩЕН] Перехватчик &%s("%s") уже есть в модуле — дубль не создаётся.'
|
||||
% (decorator_ru, method_name))
|
||||
% (dup["raw"], method_name))
|
||||
print(" Файл: %s" % ext_bsl)
|
||||
sys.exit(0)
|
||||
rel = rel_parts_under(extension_path, ext_bsl)
|
||||
@@ -792,18 +1053,21 @@ def main():
|
||||
taken = [n.lower() for n in existing_proc_names]
|
||||
interceptor_name = candidate
|
||||
if candidate.lower() in taken:
|
||||
if interceptor_type == "ModificationAndControl":
|
||||
interceptor_name = candidate + "_ИзменениеИКонтроль"
|
||||
else:
|
||||
interceptor_name = candidate + "_" + decorator_ru
|
||||
interceptor_name = candidate + "_" + decorator_out
|
||||
|
||||
core = build_interceptor_core(method, interceptor_type, interceptor_name)
|
||||
|
||||
place_new(ext_bsl, ext_lines, ext_exists, method["chain"], core)
|
||||
place_new(ext_bsl, ext_lines, ext_exists, method["chain"], core, method["lang"])
|
||||
|
||||
# Модуль в расширении есть — отражаем это в метаданных объекта (формат ≥ 2.19).
|
||||
flag_target = get_module_flag_target(rel_parts, extension_path)
|
||||
if flag_target:
|
||||
set_property_state_flag(flag_target["file"], flag_target["property"],
|
||||
detect_format_version(extension_path))
|
||||
|
||||
# emit summary
|
||||
placement = place_new.placement
|
||||
print('[OK] Перехватчик &%s("%s") — %s' % (decorator_ru, method_name, placement))
|
||||
print('[OK] Перехватчик &%s("%s") — %s' % (decorator_out, method_name, placement))
|
||||
print(" Файл: %s" % ext_bsl)
|
||||
print(" Процедура: %s(%s)" % (interceptor_name, normalize(method["params_text"])))
|
||||
if method["context"]:
|
||||
@@ -816,7 +1080,7 @@ def main():
|
||||
print(" Обрамление: %s" % desc)
|
||||
|
||||
|
||||
def place_new(ext_bsl, ext_lines, ext_exists, chain, core):
|
||||
def place_new(ext_bsl, ext_lines, ext_exists, chain, core, lang):
|
||||
enc_bom = True # noqa
|
||||
|
||||
# find innermost region in chain that already exists in the extension module
|
||||
@@ -826,7 +1090,7 @@ def place_new(ext_bsl, ext_lines, ext_exists, chain, core):
|
||||
for c in range(len(chain) - 1, -1, -1):
|
||||
if chain[c]["kind"] == "region":
|
||||
rname = chain[c]["name"]
|
||||
rre = re.compile(r'^#Область\s+' + re.escape(rname) + r'\s*$')
|
||||
rre = re.compile(r'^#' + kw_alt("Region") + r'\s+' + re.escape(rname) + r'\s*$', re.IGNORECASE)
|
||||
for li in range(len(ext_lines)):
|
||||
if rre.match(ext_lines[li].strip()):
|
||||
reuse_region_idx = c
|
||||
@@ -837,15 +1101,15 @@ def place_new(ext_bsl, ext_lines, ext_exists, chain, core):
|
||||
|
||||
if reuse_region_idx >= 0:
|
||||
inner_chain = chain[reuse_region_idx + 1:]
|
||||
block = build_wrapped_block(inner_chain, core)
|
||||
block = build_wrapped_block(inner_chain, core, lang)
|
||||
|
||||
depth = 0
|
||||
close_idx = -1
|
||||
for li in range(reuse_line_idx, len(ext_lines)):
|
||||
t = ext_lines[li].strip()
|
||||
if re.match(r'^#Область\s', t):
|
||||
if re.match(r'^#' + kw_alt("Region") + r'\s', t, re.IGNORECASE):
|
||||
depth += 1
|
||||
elif re.match(r'^#КонецОбласти', t):
|
||||
elif re.match(r'^#' + kw_alt("EndRegion"), t, re.IGNORECASE):
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
close_idx = li
|
||||
@@ -867,7 +1131,7 @@ def place_new(ext_bsl, ext_lines, ext_exists, chain, core):
|
||||
return
|
||||
|
||||
# full wrapper chain, append (or create)
|
||||
block = build_wrapped_block(chain, core)
|
||||
block = build_wrapped_block(chain, core, lang)
|
||||
block_text = "\r\n".join(block) + "\r\n"
|
||||
|
||||
bsl_dir = os.path.dirname(ext_bsl)
|
||||
@@ -929,7 +1193,8 @@ def conflict_reason(disputed):
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def write_conflict_folder(folder, method_id, ext_bsl, existing_name, method, v1, marked_body, v2, v1norm, v2norm, disputed):
|
||||
def write_conflict_folder(folder, method_id, ext_bsl, existing_name, method, v1, marked_body, v2, v1norm, v2norm, disputed, lang):
|
||||
kw = BSL_KW[lang]
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
write_bsl(os.path.join(folder, "base.bsl"), v1)
|
||||
write_bsl(os.path.join(folder, "local.bsl"), marked_body)
|
||||
@@ -937,7 +1202,7 @@ def write_conflict_folder(folder, method_id, ext_bsl, existing_name, method, v1,
|
||||
md = []
|
||||
md.append("# %s" % method_id)
|
||||
md.append("Править: %s" % ext_bsl)
|
||||
md.append('Метод: %s (&ИзменениеИКонтроль("%s"))' % (existing_name, method["canonical"]))
|
||||
md.append('Метод: %s (&%s("%s"))' % (existing_name, kw["Control"], method["canonical"]))
|
||||
md.append("Причина: %s" % conflict_reason(disputed))
|
||||
md.append("")
|
||||
md.append("## Не размещено — перенести вручную")
|
||||
@@ -951,12 +1216,13 @@ def write_conflict_folder(folder, method_id, ext_bsl, existing_name, method, v1,
|
||||
if d.get("before"):
|
||||
for l in d["before"]:
|
||||
md.append(l)
|
||||
md.append("#Вставка"); md.extend(d["lines"]); md.append("#КонецВставки")
|
||||
md.append(d.get("open") or ("#" + kw["Insert"])); md.extend(d["lines"])
|
||||
md.append(d.get("close") or ("#" + kw["EndInsert"]))
|
||||
if d.get("after"):
|
||||
for l in d["after"]:
|
||||
md.append(l)
|
||||
md.append("")
|
||||
md.append("Якорь (строки вокруг #Вставка) изменился/исчез в новом оригинале — блок не лёг автоматически (см. дифф base→remote ниже).")
|
||||
md.append("Якорь (строки вокруг #%s) изменился/исчез в новом оригинале — блок не лёг автоматически (см. дифф base→remote ниже)." % kw["Insert"])
|
||||
md.append("В модуле расширения блок припаркован в конце метода под меткой // [РЕСИНК-КОНФЛИКТ №%d] — найди по ней." % cn)
|
||||
md.append("Куда переносить: если якорного кода в новом методе больше нет — он, вероятно, вынесен/отрефакторен (ищите в диффе новый вызов/процедуру). Размести адаптацию по смыслу: например пост-обработкой после нового вызова, либо в заимствованной процедуре, куда переехал код. При правке файла сохрани кодировку (UTF-8 с BOM).")
|
||||
else:
|
||||
@@ -982,17 +1248,23 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
method_id = "%s.%s" % (logical_module, method["canonical"])
|
||||
dec_line = dup["line"]
|
||||
sig_line_idx = dec_line + 1
|
||||
name_re = re.compile(r'^\s*(?:Асинх\s+)?(?:Процедура|Функция)\s+([\w]+)\s*\(', re.IGNORECASE)
|
||||
name_re = re.compile(r'^\s*(?:' + kw_alt("Async") + r'\s+)?(' + kw_alt("Proc") + '|' + kw_alt("Func")
|
||||
+ r')\s+([\w]+)\s*\(', re.IGNORECASE)
|
||||
m0 = name_re.match(ext_lines[sig_line_idx]) if sig_line_idx < len(ext_lines) else None
|
||||
if not m0:
|
||||
return {"id": method_id, "status": "ОШИБКА", "ext_bsl": ext_bsl, "reason": "не разобрать сигнатуру перехватчика"}
|
||||
existing_name = m0.group(1)
|
||||
# The block we are about to rewrite is the interceptor already in the extension, so it is
|
||||
# its spelling — not the source module's — that the rewritten block must keep.
|
||||
lang = bsl_lang(m0.group(1))
|
||||
kw = BSL_KW[lang]
|
||||
existing_name = m0.group(2)
|
||||
sig = read_signature(ext_lines, sig_line_idx)
|
||||
if not sig:
|
||||
return {"id": method_id, "status": "ОШИБКА", "ext_bsl": ext_bsl, "reason": "не разобрать сигнатуру"}
|
||||
_params, sig_end = sig
|
||||
is_func = bool(re.match(r'^\s*(?:Асинх\s+)?Функция\b', ext_lines[sig_line_idx], re.IGNORECASE))
|
||||
end_re = re.compile(r'^\s*КонецФункции\b' if is_func else r'^\s*КонецПроцедуры\b', re.IGNORECASE)
|
||||
ext_params_text, sig_end = sig
|
||||
is_func = bool(re.match(r'^\s*(?:' + kw_alt("Async") + r'\s+)?' + kw_alt("Func") + r'\b',
|
||||
ext_lines[sig_line_idx], re.IGNORECASE))
|
||||
end_re = re.compile(r'^\s*' + (kw_alt("EndFunc") if is_func else kw_alt("EndProc")) + r'\b', re.IGNORECASE)
|
||||
block_end = -1
|
||||
for j in range(sig_end + 1, len(ext_lines)):
|
||||
if end_re.match(ext_lines[j]):
|
||||
@@ -1007,10 +1279,18 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
v1norm = [normalize(x) for x in v1]
|
||||
v2norm = [normalize(x) for x in v2]
|
||||
|
||||
if "\n".join(v1norm) == "\n".join(v2norm):
|
||||
# Signature: the platform rejects the interceptor when the parameter COUNT differs, so a
|
||||
# body-only comparison would miss a vendor-added parameter. Names/defaults it ignores.
|
||||
ext_param_count = param_count(ext_params_text)
|
||||
src_param_count = param_count(method["params_text"])
|
||||
params_drift = ext_param_count != src_param_count
|
||||
params_reason = ("список параметров: в оригинале %d, в перехватчике %d"
|
||||
% (src_param_count, ext_param_count)) if params_drift else ""
|
||||
|
||||
if not params_drift and control_key(v1) == control_key(v2):
|
||||
return {"id": method_id, "status": "АКТУАЛЕН", "ext_bsl": ext_bsl}
|
||||
|
||||
insert_top = []; insert_after = {}; del_start = set(); del_end = set(); disputed = []; transferred = 0; absorbed = 0; absorbed_notes = []
|
||||
insert_top = []; insert_after = {}; del_start = {}; del_end = {}; disputed = []; transferred = 0; absorbed = 0; absorbed_notes = []
|
||||
v2sig, v2map = significant_projection(v2norm)
|
||||
for op in ops:
|
||||
if op["kind"] == "insert":
|
||||
@@ -1036,16 +1316,17 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
elif k is None:
|
||||
dbefore = v1[max(0, after - 2):after + 1] if after >= 0 else []
|
||||
dafter = v1[after + 1:after + 4]
|
||||
disputed.append({"kind": "insert", "lines": op["lines"], "before": dbefore, "after": dafter})
|
||||
disputed.append({"kind": "insert", "lines": op["lines"], "open": op.get("open"),
|
||||
"close": op.get("close"), "before": dbefore, "after": dafter})
|
||||
elif k < 0:
|
||||
insert_top.append(op["lines"]); transferred += 1
|
||||
insert_top.append(op); transferred += 1
|
||||
else:
|
||||
insert_after.setdefault(k, []).append(op["lines"]); transferred += 1
|
||||
insert_after.setdefault(k, []).append(op); transferred += 1
|
||||
else:
|
||||
keys = v1norm[op["start"]:op["end"] + 1]
|
||||
p = find_unique_run(v2norm, keys)
|
||||
if p >= 0:
|
||||
del_start.add(p); del_end.add(p + len(keys) - 1); transferred += 1
|
||||
del_start[p] = op.get("open"); del_end[p + len(keys) - 1] = op.get("close"); transferred += 1
|
||||
else:
|
||||
# Nearest significant neighbours; adjacency in the significant projection means the
|
||||
# block is already cut (blanks/comments left behind don't matter).
|
||||
@@ -1069,22 +1350,33 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
st = "ПЕРЕНЕСЕНО В ОСНОВНУЮ"
|
||||
else:
|
||||
st = "ДРЕЙФ"
|
||||
if params_drift and st == "ПЕРЕНЕСЕНО В ОСНОВНУЮ":
|
||||
st = "ДРЕЙФ"
|
||||
rsn = conflict_reason(disputed) if disputed else ("все правки уже в основной конфигурации" if st == "ПЕРЕНЕСЕНО В ОСНОВНУЮ" else "")
|
||||
if params_drift:
|
||||
rsn = ("%s; %s" % (params_reason, rsn)) if rsn else params_reason
|
||||
return {"id": method_id, "status": st, "ext_bsl": ext_bsl, "transferred": transferred,
|
||||
"absorbed": absorbed, "disputed": len(disputed), "reason": rsn, "absorbed_notes": absorbed_notes}
|
||||
|
||||
# Marker lines come back as they were read (open/close); the keyword form is only a fallback
|
||||
# for a block whose closing marker the module never had.
|
||||
def mk(orig, key):
|
||||
return ("#" + kw[key]) if not orig else orig
|
||||
|
||||
new_body = []
|
||||
for blk in insert_top:
|
||||
new_body.append("#Вставка"); new_body.extend(blk); new_body.append("#КонецВставки")
|
||||
new_body.append(mk(blk.get("open"), "Insert")); new_body.extend(blk["lines"])
|
||||
new_body.append(mk(blk.get("close"), "EndInsert"))
|
||||
for k in range(len(v2)):
|
||||
if k in del_start:
|
||||
new_body.append("#Удаление")
|
||||
new_body.append(mk(del_start[k], "Delete"))
|
||||
new_body.append(v2[k])
|
||||
if k in del_end:
|
||||
new_body.append("#КонецУдаления")
|
||||
new_body.append(mk(del_end[k], "EndDelete"))
|
||||
if k in insert_after:
|
||||
for blk in insert_after[k]:
|
||||
new_body.append("#Вставка"); new_body.extend(blk); new_body.append("#КонецВставки")
|
||||
new_body.append(mk(blk.get("open"), "Insert")); new_body.extend(blk["lines"])
|
||||
new_body.append(mk(blk.get("close"), "EndInsert"))
|
||||
if disputed:
|
||||
new_body.append("\t// [РЕСИНК-КОНФЛИКТ] блоки ниже не легли автоматически — перенесите вручную (по № см. conflict.md / index.md в merge-воркспейсе, путь в выводе).")
|
||||
cn = 0
|
||||
@@ -1092,19 +1384,20 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
cn += 1
|
||||
if d["kind"] == "insert":
|
||||
new_body.append("\t// [РЕСИНК-КОНФЛИКТ №%d] вставка — исходный якорь изменён в новом оригинале." % cn)
|
||||
new_body.append("#Вставка"); new_body.extend(d["lines"]); new_body.append("#КонецВставки")
|
||||
new_body.append(mk(d.get("open"), "Insert")); new_body.extend(d["lines"])
|
||||
new_body.append(mk(d.get("close"), "EndInsert"))
|
||||
else:
|
||||
new_body.append("\t// [РЕСИНК-КОНФЛИКТ №%d] удаление — строки не найдены в новом оригинале:" % cn)
|
||||
for l in d["lines"]:
|
||||
new_body.append("\t// " + l.strip())
|
||||
|
||||
async_prefix = "Асинх " if method["is_async"] else ""
|
||||
keyword = "Функция" if method["is_function"] else "Процедура"
|
||||
end_keyword = "КонецФункции" if method["is_function"] else "КонецПроцедуры"
|
||||
async_prefix = (kw["Async"] + " ") if method["is_async"] else ""
|
||||
keyword = kw["Func"] if method["is_function"] else kw["Proc"]
|
||||
end_keyword = kw["EndFunc"] if method["is_function"] else kw["EndProc"]
|
||||
new_block = []
|
||||
if method["context"]:
|
||||
new_block.append(method["context"])
|
||||
new_block.append('&ИзменениеИКонтроль("%s")' % method["canonical"])
|
||||
new_block.append('&%s("%s")' % (kw["Control"], method["canonical"]))
|
||||
new_block.append("%s%s %s(%s)" % (async_prefix, keyword, existing_name, method["params_text"]))
|
||||
new_block.extend(new_body)
|
||||
new_block.append(end_keyword)
|
||||
@@ -1118,7 +1411,7 @@ def resync_one(ext_bsl, ext_lines, dup, method, logical_module, conflict_folder,
|
||||
conflict_dir = None
|
||||
if disputed:
|
||||
conflict_dir = conflict_folder
|
||||
write_conflict_folder(conflict_folder, method_id, ext_bsl, existing_name, method, v1, marked_body, v2, v1norm, v2norm, disputed)
|
||||
write_conflict_folder(conflict_folder, method_id, ext_bsl, existing_name, method, v1, marked_body, v2, v1norm, v2norm, disputed, lang)
|
||||
if disputed:
|
||||
status = "ЧАСТИЧНО"
|
||||
elif transferred == 0 and absorbed > 0:
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: cfe-validate
|
||||
description: Валидация расширения конфигурации 1С (CFE). Используй после создания или модификации расширения для проверки корректности
|
||||
argument-hint: <ExtensionPath> [-ConfigPath <ConfigDir>] [-Detailed] [-MaxErrors 30]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
---
|
||||
|
||||
# /cfe-validate — валидация расширения конфигурации (CFE)
|
||||
|
||||
Проверяет структурную корректность расширения: XML-формат, свойства, состав, заимствованные объекты, права ролей. Аналог `/cf-validate`, но для расширений.
|
||||
|
||||
Проверяются исходники. Применимость — уже после загрузки в базу: `/db-cfe-admin check`.
|
||||
|
||||
## Параметры
|
||||
|
||||
| Параметр | Обяз. | Умолч. | Описание |
|
||||
|---------------|:-----:|---------|-------------------------------------------------|
|
||||
| ExtensionPath | да | — | Путь к каталогу или Configuration.xml расширения |
|
||||
| ConfigPath | нет | — | Каталог конфигурации, из которой заимствованы объекты |
|
||||
| Detailed | нет | — | Подробный вывод (все проверки, включая успешные) |
|
||||
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||
| OutFile | нет | — | Записать результат в файл |
|
||||
|
||||
### ConfigPath
|
||||
|
||||
Указывай всегда, когда конфигурация-источник доступна: без неё часть ошибок заимствованных форм не ловится, и расширение может пройти валидацию, а потом быть отвергнутым платформой при загрузке.
|
||||
|
||||
Если пользователь не указал путь — определи сам:
|
||||
1. Прочитай `.v8-project.json` из корня проекта
|
||||
2. Разреши целевую базу (по имени, ветке или `default`)
|
||||
3. Возьми её поле `configSrc`
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-validate/scripts/cfe-validate.ps1" -ExtensionPath "src\cfe\extname"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-validate/scripts/cfe-validate.ps1" -ExtensionPath "src\cfe\extname\Configuration.xml"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/cfe-validate/scripts/cfe-validate.ps1" -ExtensionPath "src\cfe\extname" -ConfigPath "src\cf"
|
||||
```
|
||||
+419
-13
@@ -1,7 +1,8 @@
|
||||
# cfe-validate v1.5 — Validate 1C configuration extension structure (CFE)
|
||||
# cfe-validate v1.17 — Validate 1C configuration extension structure (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory)]
|
||||
[Parameter(Mandatory, Position=0)]
|
||||
[Alias('Path')]
|
||||
[string]$ExtensionPath,
|
||||
|
||||
@@ -9,7 +10,11 @@ param(
|
||||
|
||||
[int]$MaxErrors = 30,
|
||||
|
||||
[string]$OutFile
|
||||
[string]$OutFile,
|
||||
|
||||
# Конфигурация-источник. Без неё проверки, требующие сравнения с основной конфигурацией,
|
||||
# пропускаются (о чём сказано в отчёте), остальные работают как раньше.
|
||||
[string]$ConfigPath
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -89,8 +94,42 @@ $finalize = {
|
||||
}
|
||||
}
|
||||
|
||||
# --- Format version ---
|
||||
# Проверенный диапазон версий формата выгрузки: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница —
|
||||
# docs/1c-configuration-spec.md, «Лестница версий». Версию задаёт платформа ВЫГРУЗКИ, а не режим
|
||||
# совместимости конфигурации. Версии ниже 2.17 (платформы 8.3.23 и старше) существуют, но навыки
|
||||
# на них не проверялись — это предупреждение о непокрытии, а не о некорректности файла.
|
||||
$formatVerifiedMin = "2.17"
|
||||
$formatVerifiedMax = "2.21"
|
||||
# Версия формата как число: "2.20" → 220. Строковое сравнение неверно ("2.9" > "2.17").
|
||||
function Get-FormatRank([string]$ver) {
|
||||
if ($ver -match '^(\d+)\.(\d+)$') { return [int]$Matches[1] * 100 + [int]$Matches[2] }
|
||||
return 0
|
||||
}
|
||||
|
||||
# --- Reference tables ---
|
||||
$guidPattern = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
|
||||
# Модули заимствованных объектов: тип → виды модулей. Имя свойства в <xr:PropertyState>
|
||||
# совпадает с базовым именем файла модуля. Копия таблицы есть в cfe-borrow (навыки автономны).
|
||||
$moduleKindsByType = @{
|
||||
"CommonModule"=@("Module"); "HTTPService"=@("Module"); "WebService"=@("Module")
|
||||
"Catalog"=@("ObjectModule","ManagerModule"); "Document"=@("ObjectModule","ManagerModule")
|
||||
"Report"=@("ObjectModule","ManagerModule"); "DataProcessor"=@("ObjectModule","ManagerModule")
|
||||
"ExchangePlan"=@("ObjectModule","ManagerModule")
|
||||
"ChartOfCharacteristicTypes"=@("ObjectModule","ManagerModule")
|
||||
"ChartOfAccounts"=@("ObjectModule","ManagerModule")
|
||||
"ChartOfCalculationTypes"=@("ObjectModule","ManagerModule")
|
||||
"BusinessProcess"=@("ObjectModule","ManagerModule"); "Task"=@("ObjectModule","ManagerModule")
|
||||
"InformationRegister"=@("RecordSetModule","ManagerModule")
|
||||
"AccumulationRegister"=@("RecordSetModule","ManagerModule")
|
||||
"AccountingRegister"=@("RecordSetModule","ManagerModule")
|
||||
"CalculationRegister"=@("RecordSetModule","ManagerModule")
|
||||
"Sequence"=@("RecordSetModule","ManagerModule")
|
||||
"Constant"=@("ValueManagerModule","ManagerModule")
|
||||
"Enum"=@("ManagerModule"); "DocumentJournal"=@("ManagerModule")
|
||||
"FilterCriterion"=@("ManagerModule")
|
||||
}
|
||||
|
||||
$guidPattern ='^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
|
||||
$identPattern = '^[A-Za-z\u0410-\u042F\u0401\u0430-\u044F\u0451_][A-Za-z0-9\u0410-\u042F\u0401\u0430-\u044F\u0451_]*$'
|
||||
|
||||
# 7 fixed ClassIds for Configuration
|
||||
@@ -104,25 +143,25 @@ $validClassIds = @(
|
||||
"fb282519-d103-4dd3-bc12-cb271d631dfc"
|
||||
)
|
||||
|
||||
# 44 types in canonical order
|
||||
# 46 types in canonical order
|
||||
$childObjectTypes = @(
|
||||
"Language","Subsystem","StyleItem","Style",
|
||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||
"FunctionalOptionsParameter","DefinedType","Bot","PaletteColor","CommonCommand","CommandGroup",
|
||||
"Constant","CommonForm","Catalog","Document",
|
||||
"DocumentNumerator","Sequence","DocumentJournal","Enum",
|
||||
"Report","DataProcessor","InformationRegister","AccumulationRegister",
|
||||
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
|
||||
"ChartOfCalculationTypes","CalculationRegister",
|
||||
"BusinessProcess","Task","IntegrationService"
|
||||
"BusinessProcess","Task","ExternalDataSource","IntegrationService"
|
||||
)
|
||||
|
||||
# Type -> directory mapping
|
||||
$childTypeDirMap = @{
|
||||
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
||||
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"; "Bot"="Bots"; "PaletteColor"="PaletteColors"
|
||||
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"
|
||||
"CommonTemplate"="CommonTemplates"; "FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"
|
||||
"CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"; "XDTOPackage"="XDTOPackages"
|
||||
@@ -141,9 +180,50 @@ $childTypeDirMap = @{
|
||||
"ChartOfCalculationTypes"="ChartsOfCalculationTypes"
|
||||
"CalculationRegister"="CalculationRegisters"
|
||||
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
|
||||
"IntegrationService"="IntegrationServices"
|
||||
"ExternalDataSource"="ExternalDataSources"; "IntegrationService"="IntegrationServices"
|
||||
}
|
||||
|
||||
# Наборы GeneratedType по типу объекта (эталон — таблица §2.5 спецификации конфигурации).
|
||||
# Неполный набор в заимствованной оболочке платформа отвергает при загрузке: «отсутствует один
|
||||
# или более типов объекта <Тип>». Типы, у которых GeneratedType нет вовсе (общие модули,
|
||||
# подписки, регламентные задания и т.п.), в карте отсутствуют — для них проверка не выполняется.
|
||||
$generatedTypeCategories = @{
|
||||
"Catalog" = @("Object","Ref","Selection","List","Manager")
|
||||
"Document" = @("Object","Ref","Selection","List","Manager")
|
||||
"Enum" = @("Ref","Manager","List")
|
||||
"Constant" = @("Manager","ValueManager","ValueKey")
|
||||
"Report" = @("Object","Manager")
|
||||
"DataProcessor" = @("Object","Manager")
|
||||
"ExchangePlan" = @("Object","Ref","Selection","List","Manager")
|
||||
"Task" = @("Object","Ref","Selection","List","Manager")
|
||||
"BusinessProcess" = @("Object","Ref","Selection","List","Manager","RoutePointRef")
|
||||
"ChartOfCharacteristicTypes" = @("Object","Ref","Selection","List","Manager","Characteristic")
|
||||
"ChartOfAccounts" = @("Object","Ref","Selection","List","Manager","ExtDimensionTypes","ExtDimensionTypesRow")
|
||||
"ChartOfCalculationTypes" = @("Object","Ref","Selection","List","Manager","DisplacingCalculationTypes","DisplacingCalculationTypesRow","BaseCalculationTypes","BaseCalculationTypesRow","LeadingCalculationTypes","LeadingCalculationTypesRow")
|
||||
"InformationRegister" = @("Record","Manager","Selection","List","RecordSet","RecordKey","RecordManager")
|
||||
"AccumulationRegister" = @("Record","Manager","Selection","List","RecordSet","RecordKey")
|
||||
"AccountingRegister" = @("Record","Manager","Selection","List","RecordSet","RecordKey","ExtDimensions")
|
||||
"CalculationRegister" = @("Record","Manager","Selection","List","RecordSet","RecordKey","Recalcs")
|
||||
"DocumentJournal" = @("Selection","List","Manager")
|
||||
"Sequence" = @("Record","Manager","RecordSet")
|
||||
"FilterCriterion" = @("Manager","List")
|
||||
"SettingsStorage" = @("Manager")
|
||||
"ExternalDataSource" = @("Manager","TablesManager","CubesManager")
|
||||
"IntegrationService" = @("Manager")
|
||||
"WSReference" = @("Manager")
|
||||
"DefinedType" = @("DefinedType")
|
||||
}
|
||||
|
||||
# Стандартные реквизиты объектов: в ChildObjects их нет, но пути Объект.<Стандартный> законны.
|
||||
# Имена зависят от варианта встроенного языка, поэтому держим оба написания.
|
||||
$script:standardObjectFields = @(
|
||||
"Code","Description","Ref","Parent","Owner","DeletionMark","Predefined","IsFolder","LineNumber",
|
||||
"Number","Date","Posted","PredefinedDataName","RegisterRecords","DataVersion","RowsCount",
|
||||
"Код","Наименование","Ссылка","Родитель","Владелец","ПометкаУдаления","Предопределенный",
|
||||
"ЭтоГруппа","НомерСтроки","Номер","Дата","Проведен","ИмяПредопределенныхДанных",
|
||||
"Движения","ВерсияДанных","КоличествоСтрок"
|
||||
)
|
||||
|
||||
# Valid enum values for extension properties
|
||||
$validEnumValues = @{
|
||||
"ConfigurationExtensionCompatibilityMode" = @("DontUse","Version8_1","Version8_2_13","Version8_2_16","Version8_3_1","Version8_3_2","Version8_3_3","Version8_3_4","Version8_3_5","Version8_3_6","Version8_3_7","Version8_3_8","Version8_3_9","Version8_3_10","Version8_3_11","Version8_3_12","Version8_3_13","Version8_3_14","Version8_3_15","Version8_3_16","Version8_3_17","Version8_3_18","Version8_3_19","Version8_3_20","Version8_3_21","Version8_3_22","Version8_3_23","Version8_3_24","Version8_3_25","Version8_3_26","Version8_3_27","Version8_3_28","Version8_5_1")
|
||||
@@ -195,11 +275,15 @@ if ($root.NamespaceURI -ne $expectedNs) {
|
||||
}
|
||||
|
||||
$version = $root.GetAttribute("version")
|
||||
$versionRank = Get-FormatRank $version
|
||||
if (-not $version) {
|
||||
Report-Warn "1. Missing version attribute on MetaDataObject"
|
||||
} elseif ($version -notin @("2.17", "2.18", "2.19", "2.20", "2.21")) {
|
||||
# Лестница версий формата: 2.17 (8.3.20-8.3.24), 2.18 (8.3.25), 2.19 (8.3.26), 2.20 (8.3.27).
|
||||
Report-Warn "1. Unusual version '$version' (expected 2.17-2.20 or 2.21)"
|
||||
} elseif ($versionRank -eq 0) {
|
||||
Report-Error "1. Malformed version '$version' (expected N.N)"
|
||||
} elseif ($versionRank -lt (Get-FormatRank $formatVerifiedMin)) {
|
||||
Report-Warn "1. Format version '$version' is below the tested range $formatVerifiedMin-$formatVerifiedMax — skills were not verified on it"
|
||||
} elseif ($versionRank -gt (Get-FormatRank $formatVerifiedMax)) {
|
||||
Report-Warn "1. Format version '$version' is above the tested range $formatVerifiedMin-$formatVerifiedMax — skills were not verified on it"
|
||||
}
|
||||
|
||||
# Must have Configuration child
|
||||
@@ -537,6 +621,7 @@ if ($script:stopped) { & $finalize; exit 1 }
|
||||
|
||||
# --- Check 9: Borrowed objects validation + Check 10: Sub-items ---
|
||||
$script:enumValuesIndex = @{}
|
||||
$script:borrowedTSIndex = @{}
|
||||
$script:formList = @()
|
||||
|
||||
# Helper: check if sub-item has explicit borrowed metadata
|
||||
@@ -640,6 +725,25 @@ if ($childObjNode) {
|
||||
} else {
|
||||
$borrowedOk++
|
||||
}
|
||||
|
||||
# Полнота набора GeneratedType: платформа отвергает оболочку с неполным набором
|
||||
# («отсутствует один или более типов объекта ChartOfCharacteristicTypes»)
|
||||
$expectedCats = $generatedTypeCategories[$typeName]
|
||||
if ($expectedCats) {
|
||||
$objInfo = $objEl.SelectSingleNode("md:InternalInfo", $objNs)
|
||||
$foundCats = @{}
|
||||
if ($objInfo) {
|
||||
foreach ($gt in $objInfo.SelectNodes("xr:GeneratedType", $objNs)) {
|
||||
$cat = $gt.GetAttribute("category")
|
||||
if ($cat) { $foundCats[$cat] = $true }
|
||||
}
|
||||
}
|
||||
$missingCats = @($expectedCats | Where-Object { -not $foundCats.ContainsKey($_) })
|
||||
if ($missingCats.Count -gt 0) {
|
||||
Report-Error "9. Borrowed ${typeName}.${childName}: missing GeneratedType categor$(if ($missingCats.Count -eq 1) { 'y' } else { 'ies' }) $($missingCats -join ', ')"
|
||||
$check9Ok = $false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- Check 10: Sub-items (Attribute, TabularSection, EnumValue, Form) ---
|
||||
@@ -667,6 +771,12 @@ if ($childObjNode) {
|
||||
$tsInfo = $subItem.SelectSingleNode("md:InternalInfo", $objNs)
|
||||
$tsName = $subItem.SelectSingleNode("md:Properties/md:Name", $objNs)
|
||||
$tsLabel = if ($tsName) { $tsName.InnerText } else { "?" }
|
||||
# Индекс заимствованных ТЧ — по нему Check 12 сверяет <AdditionalColumns table="Объект.X">
|
||||
if ($tsName) {
|
||||
$tsKey = "${typeName}.${childName}"
|
||||
if (-not $script:borrowedTSIndex.ContainsKey($tsKey)) { $script:borrowedTSIndex[$tsKey] = @{} }
|
||||
$script:borrowedTSIndex[$tsKey][$tsName.InnerText] = $true
|
||||
}
|
||||
if (-not $tsInfo) {
|
||||
Report-Error "10. ${ctx}: TabularSection.${tsLabel} missing InternalInfo"
|
||||
$check10Ok = $false
|
||||
@@ -896,6 +1006,38 @@ foreach ($bf in $script:borrowedFormsWithTree) {
|
||||
}
|
||||
}
|
||||
|
||||
# Корень путей формы — имя её основного реквизита: «Объект» только у формы объекта, у формы
|
||||
# списка «Список», у формы записи регистра «Запись». С зашитым «Объект» обе проверки ниже на
|
||||
# таких формах молча не срабатывали. Ищем сначала в <Attributes> самой формы, потом в <BaseForm>.
|
||||
$rootName = ""
|
||||
$rootMatch = [regex]::Match($raw, '(?s)<Attribute name="([^"]+)"[^>]*>(?:(?!</Attribute>).)*?<MainAttribute>true</MainAttribute>')
|
||||
if ($rootMatch.Success) { $rootName = $rootMatch.Groups[1].Value }
|
||||
|
||||
# <AdditionalColumns table="Объект.X"> — доп. колонки табличной части, объявленные в самой форме.
|
||||
# Колонки есть, а самой ТЧ в расширении нет → платформа отвергает загрузку: «Неверный путь к
|
||||
# данным» плюс «Колонки не могут быть добавлены к реквизиту».
|
||||
$acTables = @{}
|
||||
if ($rootName) {
|
||||
$rootPat = [regex]::Escape($rootName)
|
||||
foreach ($m in [regex]::Matches($raw, "<AdditionalColumns table=`"${rootPat}\.(\w+)`"")) {
|
||||
$acTables[$m.Groups[1].Value] = $true
|
||||
}
|
||||
}
|
||||
# Соседние проверки этого блока эвристичны (имя стиля добывается регуляркой), поэтому там
|
||||
# предупреждение. Здесь сигнал точный — имя ТЧ берётся из атрибута, — а последствие жёсткое,
|
||||
# поэтому ошибка.
|
||||
if ($acTables.Count -gt 0) {
|
||||
$ownerKey = ($ctx -split '\.Form\.')[0]
|
||||
$ownerTS = $script:borrowedTSIndex[$ownerKey]
|
||||
foreach ($tblName in $acTables.Keys) {
|
||||
$depCheckCount++
|
||||
if (-not $ownerTS -or -not $ownerTS.ContainsKey($tblName)) {
|
||||
Report-Error "12. ${ctx}: <AdditionalColumns table=`"${rootName}.${tblName}`"> — TabularSection.${tblName} not borrowed in extension"
|
||||
$check12Ok = $false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($mi in $missingItems) {
|
||||
Report-Warn "12. ${ctx}: references ${mi} not borrowed in extension"
|
||||
$check12Ok = $false
|
||||
@@ -931,12 +1073,276 @@ if ($script:borrowedFormsWithTree.Count -eq 0) {
|
||||
Report-OK "13. TypeLink: clean"
|
||||
}
|
||||
|
||||
# --- Check 14: пути Объект.* заимствованных форм против конфигурации-источника ---
|
||||
# Требует -ConfigPath: отличить живой путь от висячего можно только по исходному объекту.
|
||||
# «Объект.Партнер» валиден и без заимствования реквизита (наследуется от базы), а «Объект.Товары.Артикул»
|
||||
# не разрешится нигде, если Артикул — не реквизит объекта и не колонка из <Columns> самой формы.
|
||||
# Такой путь платформа отвергает на загрузке: «Неверный путь к данным».
|
||||
if (-not $script:stopped -and $script:borrowedFormsWithTree.Count -gt 0) {
|
||||
if (-not $ConfigPath) {
|
||||
Out-Line "[INFO] 14. Пути Объект.* против конфигурации-источника не проверялись: не задан -ConfigPath"
|
||||
} else {
|
||||
$cfgRoot = $ConfigPath
|
||||
if (-not [System.IO.Path]::IsPathRooted($cfgRoot)) { $cfgRoot = Join-Path (Get-Location).Path $cfgRoot }
|
||||
if ((Test-Path $cfgRoot) -and -not (Test-Path $cfgRoot -PathType Container)) { $cfgRoot = Split-Path $cfgRoot -Parent }
|
||||
|
||||
if (-not (Test-Path (Join-Path $cfgRoot "Configuration.xml"))) {
|
||||
Report-Warn "14. -ConfigPath '$ConfigPath': Configuration.xml не найден — проверка путей пропущена"
|
||||
} else {
|
||||
$check14Ok = $true
|
||||
$pathCheckCount = 0
|
||||
|
||||
foreach ($bf in $script:borrowedFormsWithTree) {
|
||||
$raw = $bf.RawText
|
||||
$ctx = $bf.Context
|
||||
# Корень путей — имя основного реквизита формы (см. проверку 12). Нет его ни в
|
||||
# <Attributes> формы, ни в <BaseForm> — путей с корнем не бывает, проверять нечего.
|
||||
$rootMatch14 = [regex]::Match($raw, '(?s)<Attribute name="([^"]+)"[^>]*>(?:(?!</Attribute>).)*?<MainAttribute>true</MainAttribute>')
|
||||
if (-not $rootMatch14.Success) { continue }
|
||||
$rootName = $rootMatch14.Groups[1].Value
|
||||
# У динамического списка набор полей — результат его запроса, а не состав объекта:
|
||||
# туда входят и стандартные поля списка (Ref, Date, DefaultPicture), и псевдонимы
|
||||
# запроса. Сверять такие пути с ChildObjects объекта нельзя — будут ложные ошибки
|
||||
# (корпусная проверка: 3383 таких сегмента на 1094 формах списка УТ).
|
||||
if ($rootMatch14.Value -match '>cfg:DynamicList<') { continue }
|
||||
$ownerKey = ($ctx -split '\.Form\.')[0]
|
||||
$ownerParts = $ownerKey -split '\.', 2
|
||||
if ($ownerParts.Count -lt 2) { continue }
|
||||
$ownerType = $ownerParts[0]; $ownerName = $ownerParts[1]
|
||||
$ownerDir = $childTypeDirMap[$ownerType]
|
||||
if (-not $ownerDir) { continue }
|
||||
$srcObjFile = Join-Path (Join-Path $cfgRoot $ownerDir) "${ownerName}.xml"
|
||||
if (-not (Test-Path $srcObjFile)) {
|
||||
Report-Warn "14. ${ctx}: объект-источник не найден в конфигурации ($ownerDir/${ownerName}.xml)"
|
||||
continue
|
||||
}
|
||||
|
||||
# Имена, доступные первым сегментом пути: реквизиты и ТЧ объекта-источника.
|
||||
# Плюс для каждой ТЧ — её колонки: второй сегмент проверяем по ним (именно там
|
||||
# и жил дефект — Объект.Товары.Артикул при живой ТЧ Товары).
|
||||
$srcNames = @{}
|
||||
$srcTSColumns = @{}
|
||||
$srcDoc = New-Object System.Xml.XmlDocument
|
||||
$srcDoc.PreserveWhitespace = $false
|
||||
$srcDoc.Load($srcObjFile)
|
||||
$srcObjEl = $null
|
||||
foreach ($c in $srcDoc.DocumentElement.ChildNodes) {
|
||||
if ($c.NodeType -eq 'Element') { $srcObjEl = $c; break }
|
||||
}
|
||||
$srcChildObjects = if ($srcObjEl) { $srcObjEl.SelectSingleNode("*[local-name()='ChildObjects']") } else { $null }
|
||||
if ($srcChildObjects) {
|
||||
foreach ($sub in $srcChildObjects.ChildNodes) {
|
||||
if ($sub.NodeType -ne 'Element') { continue }
|
||||
# У регистра дочерние объекты — Dimension/Resource, а не Attribute: без них замена
|
||||
# корня превратила бы тихий пропуск в ложные ошибки на форме записи.
|
||||
if ($sub.LocalName -notin @('Attribute','Dimension','Resource','TabularSection')) { continue }
|
||||
$nameNode = $sub.SelectSingleNode("*[local-name()='Properties']/*[local-name()='Name']")
|
||||
if (-not $nameNode) { continue }
|
||||
$subName = $nameNode.InnerText.Trim()
|
||||
$srcNames[$subName] = $true
|
||||
if ($sub.LocalName -ne 'TabularSection') { continue }
|
||||
$cols = @{}
|
||||
foreach ($colName in $sub.SelectNodes("*[local-name()='ChildObjects']/*[local-name()='Attribute']/*[local-name()='Properties']/*[local-name()='Name']")) {
|
||||
$cols[$colName.InnerText.Trim()] = $true
|
||||
}
|
||||
$srcTSColumns[$subName] = $cols
|
||||
}
|
||||
}
|
||||
# Плюс колонки, объявленные в самой форме через <Columns>/<AdditionalColumns table="Объект.X">
|
||||
$rootPat14 = [regex]::Escape($rootName)
|
||||
foreach ($acm in [regex]::Matches($raw, "(?s)<AdditionalColumns table=`"${rootPat14}\.(\w+)`">(.*?)</AdditionalColumns>")) {
|
||||
$tbl = $acm.Groups[1].Value
|
||||
if (-not $srcTSColumns.ContainsKey($tbl)) { $srcTSColumns[$tbl] = @{} }
|
||||
foreach ($cm in [regex]::Matches($acm.Groups[2].Value, '<Column name="(\w+)"')) {
|
||||
$srcTSColumns[$tbl][$cm.Groups[1].Value] = $true
|
||||
}
|
||||
}
|
||||
|
||||
$badPaths = @{}
|
||||
foreach ($m in [regex]::Matches($raw, "<(?:\w+:)?\w*DataPath[^>]*>${rootPat14}\.([^<]+)</(?:\w+:)?\w*DataPath>")) {
|
||||
$segments = $m.Groups[1].Value -split '\.'
|
||||
$seg0 = $segments[0]
|
||||
$pathCheckCount++
|
||||
if ($script:standardObjectFields -contains $seg0) { continue }
|
||||
if (-not $srcNames.ContainsKey($seg0)) {
|
||||
$badPaths["${rootName}.${seg0}"] = "у ${ownerKey} нет такого реквизита или табличной части"
|
||||
continue
|
||||
}
|
||||
# Второй сегмент проверяем только для табличных частей: у ссылочного реквизита
|
||||
# он ведёт в чужой объект, и это уже другая проверка.
|
||||
if ($segments.Count -lt 2 -or -not $srcTSColumns.ContainsKey($seg0)) { continue }
|
||||
$seg1 = $segments[1]
|
||||
if ($script:standardObjectFields -contains $seg1) { continue }
|
||||
# Итог колонки — псевдополе платформы: Total<Колонка> при живой колонке законен
|
||||
if ($seg1 -like "Total*" -and $srcTSColumns[$seg0].ContainsKey($seg1.Substring(5))) { continue }
|
||||
if (-not $srcTSColumns[$seg0].ContainsKey($seg1)) {
|
||||
$badPaths["${rootName}.${seg0}.${seg1}"] = "у табличной части ${seg0} нет колонки ${seg1}, и <Columns> формы её не объявляет"
|
||||
}
|
||||
}
|
||||
foreach ($bad in ($badPaths.Keys | Sort-Object)) {
|
||||
Report-Error "14. ${ctx}: путь '${bad}' — $($badPaths[$bad])"
|
||||
$check14Ok = $false
|
||||
}
|
||||
}
|
||||
|
||||
if ($check14Ok) {
|
||||
Report-OK "14. Object paths vs source config: $pathCheckCount checked"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- Check 15: основные роли расширения не дают прав на заимствованные объекты ---
|
||||
# Платформа: «Назначение прав доступа на заимствованные объекты основными ролями в
|
||||
# расширениях недопустимо». Роль вне <DefaultRoles> так делать вправе — проверяем только
|
||||
# основные. Ловится статически, а по симптому (отказ загрузки) причина не читается.
|
||||
$defaultRoleNodes = @($cfgNode.SelectNodes("md:Properties/md:DefaultRoles/xr:Item", $ns))
|
||||
if ($defaultRoleNodes.Count -gt 0) {
|
||||
$adoptedCache = @{}
|
||||
|
||||
function Test-ObjectAdopted {
|
||||
param([string]$typeName, [string]$objName)
|
||||
$key = "$typeName.$objName"
|
||||
if ($adoptedCache.ContainsKey($key)) { return $adoptedCache[$key] }
|
||||
$adoptedCache[$key] = $false
|
||||
if ($childTypeDirMap.ContainsKey($typeName)) {
|
||||
$objPath = Join-Path (Join-Path $configDir $childTypeDirMap[$typeName]) "$objName.xml"
|
||||
if (Test-Path $objPath) {
|
||||
try {
|
||||
$objDoc = New-Object System.Xml.XmlDocument
|
||||
$objDoc.Load($objPath)
|
||||
$objNs = New-Object System.Xml.XmlNamespaceManager($objDoc.NameTable)
|
||||
$objNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||
$ob = $objDoc.SelectSingleNode("/md:MetaDataObject/md:$typeName/md:Properties/md:ObjectBelonging", $objNs)
|
||||
if ($ob -and $ob.InnerText -eq "Adopted") { $adoptedCache[$key] = $true }
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return $adoptedCache[$key]
|
||||
}
|
||||
|
||||
$check15Ok = $true
|
||||
$check15Count = 0
|
||||
foreach ($rn in $defaultRoleNodes) {
|
||||
$roleRef = $rn.InnerText
|
||||
if ($roleRef -notmatch '^Role\.(.+)$') { continue }
|
||||
$defRoleName = $Matches[1]
|
||||
$rightsPath = Join-Path (Join-Path (Join-Path $configDir "Roles") $defRoleName) "Ext\Rights.xml"
|
||||
if (-not (Test-Path $rightsPath)) { continue }
|
||||
try {
|
||||
$rDoc = New-Object System.Xml.XmlDocument
|
||||
$rDoc.Load($rightsPath)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
$rNs = New-Object System.Xml.XmlNamespaceManager($rDoc.NameTable)
|
||||
$rNs.AddNamespace("r", "http://v8.1c.ru/8.2/roles")
|
||||
foreach ($nameNode in $rDoc.SelectNodes("/r:Rights/r:object/r:name", $rNs)) {
|
||||
$fullName = $nameNode.InnerText
|
||||
$segs = $fullName.Split(".")
|
||||
# Configuration.* — права самого расширения, не объект; заимствования там нет.
|
||||
if ($segs.Count -lt 2 -or $segs[0] -eq "Configuration") { continue }
|
||||
$check15Count++
|
||||
if (Test-ObjectAdopted $segs[0] $segs[1]) {
|
||||
Report-Error ("15. Роль '$defRoleName' входит в DefaultRoles и даёт права на заимствованный $($segs[0]).$($segs[1]) " +
|
||||
"($fullName): платформа это запрещает. Вынесите такие права в отдельную роль вне DefaultRoles.")
|
||||
$check15Ok = $false
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($check15Ok -and $check15Count -gt 0) {
|
||||
Report-OK "15. Основные роли: прав на заимствованные объекты нет ($check15Count checked)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($script:stopped) { & $finalize; exit 1 }
|
||||
|
||||
# --- Check 16: модуль заимствованного объекта и пометка расширенного свойства ---
|
||||
# Свойство <xr:PropertyState> появилось в формате 2.19 (8.3.26); ниже платформа его молча
|
||||
# выбрасывает, поэтому там проверять нечего. С 2.19 состояние обязано соответствовать факту:
|
||||
# есть файл модуля — есть пометка, и наоборот. Перекос платформа принимает (проверено на стенде),
|
||||
# но выгрузка Конфигуратора так не выглядит — отсюда предупреждение, а не ошибка.
|
||||
if ($versionRank -ge 219 -and $childObjNode) {
|
||||
$stateIssues = @()
|
||||
$stateChecked = 0
|
||||
foreach ($child in $childObjNode.ChildNodes) {
|
||||
if ($child.NodeType -ne 'Element') { continue }
|
||||
$typeName = $child.LocalName
|
||||
if (-not $moduleKindsByType.ContainsKey($typeName)) { continue }
|
||||
if (-not $childTypeDirMap.ContainsKey($typeName)) { continue }
|
||||
$stateObjName = $child.InnerText.Trim()
|
||||
if (-not $stateObjName) { continue }
|
||||
$typeDir = Join-Path $configDir $childTypeDirMap[$typeName]
|
||||
$objFile = Join-Path $typeDir "$stateObjName.xml"
|
||||
if (-not (Test-Path $objFile)) { continue }
|
||||
$objText = [System.IO.File]::ReadAllText($objFile, [System.Text.Encoding]::UTF8)
|
||||
if ($objText -notmatch '<ObjectBelonging>Adopted</ObjectBelonging>') { continue }
|
||||
|
||||
foreach ($kind in $moduleKindsByType[$typeName]) {
|
||||
$stateChecked++
|
||||
$hasFile = Test-Path (Join-Path (Join-Path (Join-Path $typeDir $stateObjName) "Ext") "$kind.bsl")
|
||||
$hasFlag = $objText -match "<xr:Property>$kind</xr:Property>"
|
||||
if ($hasFile -and -not $hasFlag) {
|
||||
$stateIssues += "$typeName.$stateObjName — есть $kind.bsl, но нет <xr:PropertyState> для $kind"
|
||||
} elseif ($hasFlag -and -not $hasFile) {
|
||||
$stateIssues += "$typeName.$stateObjName — есть <xr:PropertyState> для $kind, но нет $kind.bsl"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($stateChecked -gt 0) {
|
||||
if ($stateIssues.Count -eq 0) {
|
||||
Report-OK "16. Модули заимствованных объектов: пометки расширенных свойств согласованы ($stateChecked)"
|
||||
} else {
|
||||
foreach ($issue in $stateIssues) { Report-Warn "16. $issue" }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
function Get-BslKeywords {
|
||||
return @{
|
||||
ru = @{
|
||||
Async="Асинх"; Proc="Процедура"; EndProc="КонецПроцедуры"
|
||||
Func="Функция"; EndFunc="КонецФункции"; Val="Знач"
|
||||
Region="Область"; EndRegion="КонецОбласти"
|
||||
If="Если"; Then="Тогда"; ElsIf="ИначеЕсли"; Else="Иначе"; EndIf="КонецЕсли"
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
And="И"; Or="Или"; Not="НЕ"
|
||||
Insert="Вставка"; EndInsert="КонецВставки"; Delete="Удаление"; EndDelete="КонецУдаления"
|
||||
Before="Перед"; After="После"; Around="Вместо"; Control="ИзменениеИКонтроль"
|
||||
Proceed="ПродолжитьВызов"; Return="Возврат"
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
ResultVar="Результат"
|
||||
Directives=@("НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере")
|
||||
}
|
||||
en = @{
|
||||
Async="Async"; Proc="Procedure"; EndProc="EndProcedure"
|
||||
Func="Function"; EndFunc="EndFunction"; Val="Val"
|
||||
Region="Region"; EndRegion="EndRegion"
|
||||
If="If"; Then="Then"; ElsIf="ElsIf"; Else="Else"; EndIf="EndIf"
|
||||
And="And"; Or="Or"; Not="Not"
|
||||
Insert="Insert"; EndInsert="EndInsert"; Delete="Delete"; EndDelete="EndDelete"
|
||||
Before="Before"; After="After"; Around="Around"; Control="ChangeAndValidate"
|
||||
Proceed="ProceedWithCall"; Return="Return"
|
||||
ResultVar="Result"
|
||||
Directives=@("AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# --- Breadcrumb: controlled methods (&ИзменениеИКонтроль) drift is not checked here ---
|
||||
$extRootDir = Split-Path $resolvedPath -Parent
|
||||
$ctrlKw = Get-BslKeywords
|
||||
$ctrlRe = '(?im)^\s*&(?:' + $ctrlKw.ru.Control + '|' + $ctrlKw.en.Control + ')\('
|
||||
$ctrlCount = 0
|
||||
foreach ($bslFile in (Get-ChildItem -Path $extRootDir -Recurse -Filter *.bsl -File -ErrorAction SilentlyContinue)) {
|
||||
$txt = [System.IO.File]::ReadAllText($bslFile.FullName, [System.Text.Encoding]::UTF8)
|
||||
$ctrlCount += ([regex]::Matches($txt, '(?m)^\s*&ИзменениеИКонтроль\(')).Count
|
||||
$ctrlCount += ([regex]::Matches($txt, $ctrlRe)).Count
|
||||
}
|
||||
if ($ctrlCount -gt 0) {
|
||||
Out-Line "[INFO] Контролируемых методов (&ИзменениеИКонтроль): $ctrlCount — их актуальность здесь не проверяется. Сверьте: /cfe-patch-method -Check -ExtensionPath <ext> -ConfigPath <cf>"
|
||||
+427
-9
@@ -1,10 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
# cfe-validate v1.5 — Validate 1C configuration extension XML structure (CFE)
|
||||
# cfe-validate v1.17 — Validate 1C configuration extension XML structure (CFE)
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
"""Validates extension Configuration.xml: root, InternalInfo, extension properties, ChildObjects, borrowed objects."""
|
||||
import sys, os, argparse, re
|
||||
from lxml import etree
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
# Built-in language keywords in both spellings. The platform accepts either one in any module
|
||||
# (pairs taken from the platform string tables), so a module written in English is ordinary
|
||||
# source, not a broken one: we must read both and emit the spelling we read.
|
||||
def bsl_keywords():
|
||||
return {
|
||||
"ru": {
|
||||
"Async": "Асинх", "Proc": "Процедура", "EndProc": "КонецПроцедуры",
|
||||
"Func": "Функция", "EndFunc": "КонецФункции", "Val": "Знач",
|
||||
"Region": "Область", "EndRegion": "КонецОбласти",
|
||||
"If": "Если", "Then": "Тогда", "ElsIf": "ИначеЕсли", "Else": "Иначе", "EndIf": "КонецЕсли",
|
||||
# Platform spells the negation "Не"; we emit "НЕ" as this skill always has —
|
||||
# the language is case-insensitive, and the lower case would churn every snapshot.
|
||||
"And": "И", "Or": "Или", "Not": "НЕ",
|
||||
"Insert": "Вставка", "EndInsert": "КонецВставки", "Delete": "Удаление", "EndDelete": "КонецУдаления",
|
||||
"Before": "Перед", "After": "После", "Around": "Вместо", "Control": "ИзменениеИКонтроль",
|
||||
"Proceed": "ПродолжитьВызов", "Return": "Возврат",
|
||||
# Not a keyword: name of the local the generated Instead-stub declares. Lives here so
|
||||
# that the language of emitted text is decided in exactly one place.
|
||||
"ResultVar": "Результат",
|
||||
"Directives": ["НаКлиенте", "НаСервере", "НаСервереБезКонтекста", "НаКлиентеНаСервереБезКонтекста", "НаКлиентеНаСервере"],
|
||||
},
|
||||
"en": {
|
||||
"Async": "Async", "Proc": "Procedure", "EndProc": "EndProcedure",
|
||||
"Func": "Function", "EndFunc": "EndFunction", "Val": "Val",
|
||||
"Region": "Region", "EndRegion": "EndRegion",
|
||||
"If": "If", "Then": "Then", "ElsIf": "ElsIf", "Else": "Else", "EndIf": "EndIf",
|
||||
"And": "And", "Or": "Or", "Not": "Not",
|
||||
"Insert": "Insert", "EndInsert": "EndInsert", "Delete": "Delete", "EndDelete": "EndDelete",
|
||||
"Before": "Before", "After": "After", "Around": "Around", "Control": "ChangeAndValidate",
|
||||
"Proceed": "ProceedWithCall", "Return": "Return",
|
||||
"ResultVar": "Result",
|
||||
"Directives": ["AtClient", "AtServer", "AtServerNoContext", "AtClientAtServerNoContext", "AtClientAtServer"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
NS = {
|
||||
'md': 'http://v8.1c.ru/8.3/MDClasses',
|
||||
'v8': 'http://v8.1c.ru/8.1/data/core',
|
||||
@@ -33,27 +91,49 @@ VALID_CLASS_IDS = [
|
||||
'fb282519-d103-4dd3-bc12-cb271d631dfc',
|
||||
]
|
||||
|
||||
# 44 types in canonical order
|
||||
# 46 types in canonical order
|
||||
CHILD_OBJECT_TYPES = [
|
||||
'Language', 'Subsystem', 'StyleItem', 'Style',
|
||||
'CommonPicture', 'SessionParameter', 'Role', 'CommonTemplate',
|
||||
'FilterCriterion', 'CommonModule', 'CommonAttribute', 'ExchangePlan',
|
||||
'XDTOPackage', 'WebService', 'HTTPService', 'WSReference',
|
||||
'EventSubscription', 'ScheduledJob', 'SettingsStorage', 'FunctionalOption',
|
||||
'FunctionalOptionsParameter', 'DefinedType', 'CommonCommand', 'CommandGroup',
|
||||
'FunctionalOptionsParameter', 'DefinedType', 'Bot', 'PaletteColor', 'CommonCommand', 'CommandGroup',
|
||||
'Constant', 'CommonForm', 'Catalog', 'Document',
|
||||
'DocumentNumerator', 'Sequence', 'DocumentJournal', 'Enum',
|
||||
'Report', 'DataProcessor', 'InformationRegister', 'AccumulationRegister',
|
||||
'ChartOfCharacteristicTypes', 'ChartOfAccounts', 'AccountingRegister',
|
||||
'ChartOfCalculationTypes', 'CalculationRegister',
|
||||
'BusinessProcess', 'Task', 'IntegrationService',
|
||||
'BusinessProcess', 'Task', 'ExternalDataSource', 'IntegrationService',
|
||||
]
|
||||
|
||||
# Модули заимствованных объектов: тип → виды модулей. Имя свойства в <xr:PropertyState>
|
||||
# совпадает с базовым именем файла модуля. Копия таблицы есть в cfe-borrow (навыки автономны).
|
||||
MODULE_KINDS_BY_TYPE = {
|
||||
"CommonModule": ["Module"], "HTTPService": ["Module"], "WebService": ["Module"],
|
||||
"Catalog": ["ObjectModule", "ManagerModule"], "Document": ["ObjectModule", "ManagerModule"],
|
||||
"Report": ["ObjectModule", "ManagerModule"], "DataProcessor": ["ObjectModule", "ManagerModule"],
|
||||
"ExchangePlan": ["ObjectModule", "ManagerModule"],
|
||||
"ChartOfCharacteristicTypes": ["ObjectModule", "ManagerModule"],
|
||||
"ChartOfAccounts": ["ObjectModule", "ManagerModule"],
|
||||
"ChartOfCalculationTypes": ["ObjectModule", "ManagerModule"],
|
||||
"BusinessProcess": ["ObjectModule", "ManagerModule"], "Task": ["ObjectModule", "ManagerModule"],
|
||||
"InformationRegister": ["RecordSetModule", "ManagerModule"],
|
||||
"AccumulationRegister": ["RecordSetModule", "ManagerModule"],
|
||||
"AccountingRegister": ["RecordSetModule", "ManagerModule"],
|
||||
"CalculationRegister": ["RecordSetModule", "ManagerModule"],
|
||||
"Sequence": ["RecordSetModule", "ManagerModule"],
|
||||
"Constant": ["ValueManagerModule", "ManagerModule"],
|
||||
"Enum": ["ManagerModule"], "DocumentJournal": ["ManagerModule"],
|
||||
"FilterCriterion": ["ManagerModule"],
|
||||
}
|
||||
|
||||
# Type -> directory mapping
|
||||
CHILD_TYPE_DIR_MAP = {
|
||||
'Language': 'Languages', 'Subsystem': 'Subsystems', 'StyleItem': 'StyleItems', 'Style': 'Styles',
|
||||
'CommonPicture': 'CommonPictures', 'SessionParameter': 'SessionParameters', 'Role': 'Roles',
|
||||
'CommonTemplate': 'CommonTemplates', 'FilterCriterion': 'FilterCriteria', 'CommonModule': 'CommonModules',
|
||||
'Bot': 'Bots', 'PaletteColor': 'PaletteColors',
|
||||
'CommonAttribute': 'CommonAttributes', 'ExchangePlan': 'ExchangePlans', 'XDTOPackage': 'XDTOPackages',
|
||||
'WebService': 'WebServices', 'HTTPService': 'HTTPServices', 'WSReference': 'WSReferences',
|
||||
'EventSubscription': 'EventSubscriptions', 'ScheduledJob': 'ScheduledJobs',
|
||||
@@ -70,9 +150,55 @@ CHILD_TYPE_DIR_MAP = {
|
||||
'ChartOfCalculationTypes': 'ChartsOfCalculationTypes',
|
||||
'CalculationRegister': 'CalculationRegisters',
|
||||
'BusinessProcess': 'BusinessProcesses', 'Task': 'Tasks',
|
||||
'ExternalDataSource': 'ExternalDataSources',
|
||||
'IntegrationService': 'IntegrationServices',
|
||||
}
|
||||
|
||||
# Наборы GeneratedType по типу объекта (эталон — таблица §2.5 спецификации конфигурации).
|
||||
# Неполный набор в заимствованной оболочке платформа отвергает при загрузке: «отсутствует один
|
||||
# или более типов объекта <Тип>». Типы, у которых GeneratedType нет вовсе (общие модули,
|
||||
# подписки, регламентные задания и т.п.), в карте отсутствуют — для них проверка не выполняется.
|
||||
GENERATED_TYPE_CATEGORIES = {
|
||||
'Catalog': ['Object', 'Ref', 'Selection', 'List', 'Manager'],
|
||||
'Document': ['Object', 'Ref', 'Selection', 'List', 'Manager'],
|
||||
'Enum': ['Ref', 'Manager', 'List'],
|
||||
'Constant': ['Manager', 'ValueManager', 'ValueKey'],
|
||||
'Report': ['Object', 'Manager'],
|
||||
'DataProcessor': ['Object', 'Manager'],
|
||||
'ExchangePlan': ['Object', 'Ref', 'Selection', 'List', 'Manager'],
|
||||
'Task': ['Object', 'Ref', 'Selection', 'List', 'Manager'],
|
||||
'BusinessProcess': ['Object', 'Ref', 'Selection', 'List', 'Manager', 'RoutePointRef'],
|
||||
'ChartOfCharacteristicTypes': ['Object', 'Ref', 'Selection', 'List', 'Manager', 'Characteristic'],
|
||||
'ChartOfAccounts': ['Object', 'Ref', 'Selection', 'List', 'Manager', 'ExtDimensionTypes', 'ExtDimensionTypesRow'],
|
||||
'ChartOfCalculationTypes': ['Object', 'Ref', 'Selection', 'List', 'Manager', 'DisplacingCalculationTypes', 'DisplacingCalculationTypesRow', 'BaseCalculationTypes', 'BaseCalculationTypesRow', 'LeadingCalculationTypes', 'LeadingCalculationTypesRow'],
|
||||
'InformationRegister': ['Record', 'Manager', 'Selection', 'List', 'RecordSet', 'RecordKey', 'RecordManager'],
|
||||
'AccumulationRegister': ['Record', 'Manager', 'Selection', 'List', 'RecordSet', 'RecordKey'],
|
||||
'AccountingRegister': ['Record', 'Manager', 'Selection', 'List', 'RecordSet', 'RecordKey', 'ExtDimensions'],
|
||||
'CalculationRegister': ['Record', 'Manager', 'Selection', 'List', 'RecordSet', 'RecordKey', 'Recalcs'],
|
||||
'DocumentJournal': ['Selection', 'List', 'Manager'],
|
||||
'Sequence': ['Record', 'Manager', 'RecordSet'],
|
||||
'FilterCriterion': ['Manager', 'List'],
|
||||
'SettingsStorage': ['Manager'],
|
||||
'ExternalDataSource': ['Manager', 'TablesManager', 'CubesManager'],
|
||||
'IntegrationService': ['Manager'],
|
||||
'WSReference': ['Manager'],
|
||||
'DefinedType': ['DefinedType'],
|
||||
}
|
||||
|
||||
# Стандартные реквизиты объектов: в ChildObjects их нет, но пути Объект.<Стандартный> законны.
|
||||
# Имена зависят от варианта встроенного языка, поэтому держим оба написания.
|
||||
# Основной реквизит формы: <Attribute name="X"> с <MainAttribute>true</MainAttribute> внутри
|
||||
MAIN_ATTR_RE = re.compile(
|
||||
r'<Attribute name=\"([^\"]+)\"[^>]*>(?:(?!</Attribute>).)*?<MainAttribute>true</MainAttribute>', re.DOTALL)
|
||||
|
||||
STANDARD_OBJECT_FIELDS = {
|
||||
'Code', 'Description', 'Ref', 'Parent', 'Owner', 'DeletionMark', 'Predefined', 'IsFolder', 'LineNumber',
|
||||
'Number', 'Date', 'Posted', 'PredefinedDataName', 'RegisterRecords', 'DataVersion', 'RowsCount',
|
||||
'Код', 'Наименование', 'Ссылка', 'Родитель', 'Владелец', 'ПометкаУдаления', 'Предопределенный',
|
||||
'ЭтоГруппа', 'НомерСтроки', 'Номер', 'Дата', 'Проведен', 'ИмяПредопределенныхДанных',
|
||||
'Движения', 'ВерсияДанных', 'КоличествоСтрок',
|
||||
}
|
||||
|
||||
# Valid enum values for extension properties
|
||||
VALID_ENUM_VALUES = {
|
||||
'ConfigurationExtensionCompatibilityMode': [
|
||||
@@ -94,6 +220,20 @@ VALID_ENUM_VALUES = {
|
||||
|
||||
EXPECTED_NS = 'http://v8.1c.ru/8.3/MDClasses'
|
||||
|
||||
# ── Format version ───────────────────────────────────────────
|
||||
# Проверенный диапазон версий формата выгрузки: 2.17 (8.3.24) … 2.21 (8.5). Полная лестница —
|
||||
# docs/1c-configuration-spec.md, «Лестница версий». Версию задаёт платформа ВЫГРУЗКИ, а не режим
|
||||
# совместимости конфигурации. Версии ниже 2.17 (платформы 8.3.23 и старше) существуют, но навыки
|
||||
# на них не проверялись — это предупреждение о непокрытии, а не о некорректности файла.
|
||||
FORMAT_VERIFIED_MIN = "2.17"
|
||||
FORMAT_VERIFIED_MAX = "2.21"
|
||||
|
||||
|
||||
def format_rank(ver):
|
||||
""""2.20" → 220, "2.9" → 209. Строковое сравнение неверно ("2.9" > "2.17")."""
|
||||
m = re.match(r'^(\d+)\.(\d+)$', ver or '')
|
||||
return int(m.group(1)) * 100 + int(m.group(2)) if m else 0
|
||||
|
||||
|
||||
class Reporter:
|
||||
def __init__(self, max_errors, detailed=False):
|
||||
@@ -154,11 +294,15 @@ def main():
|
||||
parser.add_argument('-Detailed', action='store_true')
|
||||
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
||||
parser.add_argument('-OutFile', dest='OutFile', default='')
|
||||
args = parser.parse_args()
|
||||
# Конфигурация-источник. Без неё проверки, требующие сравнения с основной конфигурацией,
|
||||
# пропускаются (о чём сказано в отчёте), остальные работают как раньше.
|
||||
parser.add_argument('-ConfigPath', dest='ConfigPath', default='')
|
||||
args = ci_parse_args(parser)
|
||||
|
||||
extension_path = args.ExtensionPath
|
||||
max_errors = args.MaxErrors
|
||||
out_file = args.OutFile
|
||||
config_path_arg = args.ConfigPath
|
||||
|
||||
# --- Resolve path ---
|
||||
if not os.path.isabs(extension_path):
|
||||
@@ -214,11 +358,17 @@ def main():
|
||||
check1_ok = False
|
||||
|
||||
version = root.get('version', '')
|
||||
version_rank = format_rank(version)
|
||||
if not version:
|
||||
r.warn('1. Missing version attribute on MetaDataObject')
|
||||
elif version not in ('2.17', '2.18', '2.19', '2.20', '2.21'):
|
||||
# Лестница версий формата: 2.17 (8.3.20-8.3.24), 2.18 (8.3.25), 2.19 (8.3.26), 2.20 (8.3.27).
|
||||
r.warn(f"1. Unusual version '{version}' (expected 2.17-2.20 or 2.21)")
|
||||
elif version_rank == 0:
|
||||
r.error(f"1. Malformed version '{version}' (expected N.N)")
|
||||
elif version_rank < format_rank(FORMAT_VERIFIED_MIN):
|
||||
r.warn(f"1. Format version '{version}' is below the tested range "
|
||||
f"{FORMAT_VERIFIED_MIN}-{FORMAT_VERIFIED_MAX} — skills were not verified on it")
|
||||
elif version_rank > format_rank(FORMAT_VERIFIED_MAX):
|
||||
r.warn(f"1. Format version '{version}' is above the tested range "
|
||||
f"{FORMAT_VERIFIED_MIN}-{FORMAT_VERIFIED_MAX} — skills were not verified on it")
|
||||
|
||||
# Must have Configuration child
|
||||
cfg_node = None
|
||||
@@ -537,6 +687,7 @@ def main():
|
||||
MD = NS['md']
|
||||
XR = NS['xr']
|
||||
enum_values_index = {}
|
||||
borrowed_ts_index = {}
|
||||
form_list = []
|
||||
|
||||
def is_borrowed_sub_item(sub_item):
|
||||
@@ -636,6 +787,23 @@ def main():
|
||||
else:
|
||||
borrowed_ok_count += 1
|
||||
|
||||
# Полнота набора GeneratedType: платформа отвергает оболочку с неполным набором
|
||||
# («отсутствует один или более типов объекта ChartOfCharacteristicTypes»)
|
||||
expected_cats = GENERATED_TYPE_CATEGORIES.get(type_name)
|
||||
if expected_cats:
|
||||
obj_info = obj_el.find(f'{{{MD}}}InternalInfo')
|
||||
found_cats = set()
|
||||
if obj_info is not None:
|
||||
for gt in obj_info.findall(f'{{{XR}}}GeneratedType'):
|
||||
cat = gt.get('category')
|
||||
if cat:
|
||||
found_cats.add(cat)
|
||||
missing_cats = [c for c in expected_cats if c not in found_cats]
|
||||
if missing_cats:
|
||||
word = 'category' if len(missing_cats) == 1 else 'categories'
|
||||
r.error(f"9. Borrowed {type_name}.{child_name}: missing GeneratedType {word} {', '.join(missing_cats)}")
|
||||
check9_ok = False
|
||||
|
||||
# --- Check 10: Sub-items (Attribute, TabularSection, EnumValue, Form) ---
|
||||
obj_child_objects = obj_el.find(f'{{{MD}}}ChildObjects')
|
||||
if obj_child_objects is not None:
|
||||
@@ -663,6 +831,9 @@ def main():
|
||||
ts_info = sub_item.find(f'{{{MD}}}InternalInfo')
|
||||
ts_name_el = sub_item.find(f'{{{MD}}}Properties/{{{MD}}}Name')
|
||||
ts_label = (ts_name_el.text or '?') if ts_name_el is not None else '?'
|
||||
# Индекс заимствованных ТЧ — по нему Check 12 сверяет <AdditionalColumns table="Объект.X">
|
||||
if ts_name_el is not None and ts_name_el.text:
|
||||
borrowed_ts_index.setdefault(f'{type_name}.{child_name}', {})[ts_name_el.text.strip()] = True
|
||||
if ts_info is None:
|
||||
r.error(f'10. {ctx}: TabularSection.{ts_label} missing InternalInfo')
|
||||
check10_ok = False
|
||||
@@ -855,6 +1026,29 @@ def main():
|
||||
elif entry['Enum'] not in enum_values_index or entry['Value'] not in enum_values_index.get(entry['Enum'], {}):
|
||||
missing_items.append(f"Enum.{entry['Enum']}.EnumValue.{entry['Value']}")
|
||||
|
||||
# <AdditionalColumns table="Объект.X"> — доп. колонки табличной части, объявленные в самой форме.
|
||||
# Колонки есть, а самой ТЧ в расширении нет → платформа отвергает загрузку: «Неверный путь к
|
||||
# данным» плюс «Колонки не могут быть добавлены к реквизиту».
|
||||
# Соседние проверки этого блока эвристичны (имя стиля добывается регуляркой), поэтому там
|
||||
# предупреждение. Здесь сигнал точный — имя ТЧ берётся из атрибута, — а последствие жёсткое,
|
||||
# поэтому ошибка.
|
||||
# Корень путей формы — имя её основного реквизита: «Объект» только у формы объекта, у формы
|
||||
# списка «Список», у формы записи регистра «Запись». С зашитым «Объект» обе проверки на
|
||||
# таких формах молча не срабатывали. Ищем сначала в <Attributes> формы, потом в <BaseForm>.
|
||||
root_match = MAIN_ATTR_RE.search(raw)
|
||||
root_name = root_match.group(1) if root_match else ""
|
||||
ac_tables = set()
|
||||
if root_name:
|
||||
ac_tables = set(re.findall(r'<AdditionalColumns table="' + re.escape(root_name) + r'\.(\w+)"', raw))
|
||||
if ac_tables:
|
||||
owner_key = ctx.split('.Form.')[0]
|
||||
owner_ts = borrowed_ts_index.get(owner_key, {})
|
||||
for tbl_name in sorted(ac_tables):
|
||||
dep_check_count += 1
|
||||
if tbl_name not in owner_ts:
|
||||
r.error(f'12. {ctx}: <AdditionalColumns table="{root_name}.{tbl_name}"> — TabularSection.{tbl_name} not borrowed in extension')
|
||||
check12_ok = False
|
||||
|
||||
for mi in missing_items:
|
||||
r.warn(f'12. {ctx}: references {mi} not borrowed in extension')
|
||||
check12_ok = False
|
||||
@@ -886,7 +1080,231 @@ def main():
|
||||
elif check13_ok:
|
||||
r.ok('13. TypeLink: clean')
|
||||
|
||||
# --- Check 14: пути Объект.* заимствованных форм против конфигурации-источника ---
|
||||
# Требует -ConfigPath: отличить живой путь от висячего можно только по исходному объекту.
|
||||
# «Объект.Партнер» валиден и без заимствования реквизита (наследуется от базы), а «Объект.Товары.Артикул»
|
||||
# не разрешится нигде, если Артикул — не колонка ТЧ и не колонка из <Columns> самой формы.
|
||||
# Такой путь платформа отвергает на загрузке: «Неверный путь к данным».
|
||||
if not r.stopped and borrowed_forms_with_tree:
|
||||
if not config_path_arg:
|
||||
r.out('[INFO] 14. Пути Объект.* против конфигурации-источника не проверялись: не задан -ConfigPath')
|
||||
else:
|
||||
cfg_root = config_path_arg
|
||||
if not os.path.isabs(cfg_root):
|
||||
cfg_root = os.path.join(os.getcwd(), cfg_root)
|
||||
if os.path.exists(cfg_root) and not os.path.isdir(cfg_root):
|
||||
cfg_root = os.path.dirname(cfg_root)
|
||||
|
||||
if not os.path.isfile(os.path.join(cfg_root, 'Configuration.xml')):
|
||||
r.warn(f"14. -ConfigPath '{config_path_arg}': Configuration.xml не найден — проверка путей пропущена")
|
||||
else:
|
||||
check14_ok = True
|
||||
path_check_count = 0
|
||||
|
||||
for bf in borrowed_forms_with_tree:
|
||||
raw = bf['RawText']
|
||||
ctx = bf['Context']
|
||||
# Корень путей — имя основного реквизита формы (см. проверку 12). Нет его ни в
|
||||
# <Attributes> формы, ни в <BaseForm> — путей с корнем не бывает, проверять нечего.
|
||||
root_match14 = MAIN_ATTR_RE.search(raw)
|
||||
if root_match14 is None:
|
||||
continue
|
||||
root_name14 = root_match14.group(1)
|
||||
# У динамического списка набор полей — результат его запроса, а не состав объекта:
|
||||
# туда входят и стандартные поля списка (Ref, Date, DefaultPicture), и псевдонимы
|
||||
# запроса. Сверять такие пути с ChildObjects объекта нельзя — будут ложные ошибки
|
||||
# (корпусная проверка: 3383 таких сегмента на 1094 формах списка УТ).
|
||||
if '>cfg:DynamicList<' in root_match14.group(0):
|
||||
continue
|
||||
owner_key = ctx.split('.Form.')[0]
|
||||
owner_parts = owner_key.split('.', 1)
|
||||
if len(owner_parts) < 2:
|
||||
continue
|
||||
owner_type, owner_name = owner_parts
|
||||
owner_dir = CHILD_TYPE_DIR_MAP.get(owner_type)
|
||||
if not owner_dir:
|
||||
continue
|
||||
src_obj_file = os.path.join(cfg_root, owner_dir, f'{owner_name}.xml')
|
||||
if not os.path.isfile(src_obj_file):
|
||||
r.warn(f'14. {ctx}: объект-источник не найден в конфигурации ({owner_dir}/{owner_name}.xml)')
|
||||
continue
|
||||
|
||||
# Имена, доступные первым сегментом пути: реквизиты и ТЧ объекта-источника.
|
||||
# Плюс для каждой ТЧ — её колонки: второй сегмент проверяем по ним (именно там
|
||||
# и жил дефект — Объект.Товары.Артикул при живой ТЧ Товары).
|
||||
src_names = set()
|
||||
src_ts_columns = {}
|
||||
src_tree = etree.parse(src_obj_file, etree.XMLParser(remove_blank_text=True))
|
||||
src_obj_el = None
|
||||
for c in src_tree.getroot():
|
||||
if isinstance(c.tag, str):
|
||||
src_obj_el = c
|
||||
break
|
||||
src_child_objects = src_obj_el.find(f'{{{MD}}}ChildObjects') if src_obj_el is not None else None
|
||||
if src_child_objects is not None:
|
||||
for sub in src_child_objects:
|
||||
if not isinstance(sub.tag, str):
|
||||
continue
|
||||
sub_ln = etree.QName(sub.tag).localname
|
||||
# У регистра дочерние объекты — Dimension/Resource, а не Attribute: без них
|
||||
# замена корня превратила бы тихий пропуск в ложные ошибки на форме записи.
|
||||
if sub_ln not in ('Attribute', 'Dimension', 'Resource', 'TabularSection'):
|
||||
continue
|
||||
name_el = sub.find(f'{{{MD}}}Properties/{{{MD}}}Name')
|
||||
if name_el is None or not name_el.text:
|
||||
continue
|
||||
sub_name = name_el.text.strip()
|
||||
src_names.add(sub_name)
|
||||
if sub_ln != 'TabularSection':
|
||||
continue
|
||||
cols = set()
|
||||
for col_name in sub.findall(f'{{{MD}}}ChildObjects/{{{MD}}}Attribute/{{{MD}}}Properties/{{{MD}}}Name'):
|
||||
if col_name.text:
|
||||
cols.add(col_name.text.strip())
|
||||
src_ts_columns[sub_name] = cols
|
||||
# Плюс колонки, объявленные в самой форме через <Columns>/<AdditionalColumns table="Объект.X">
|
||||
root_pat14 = re.escape(root_name14)
|
||||
for acm in re.finditer(r'<AdditionalColumns table="' + root_pat14 + r'\.(\w+)">(.*?)</AdditionalColumns>', raw, re.DOTALL):
|
||||
tbl = acm.group(1)
|
||||
cols = src_ts_columns.setdefault(tbl, set())
|
||||
for cm in re.finditer(r'<Column name="(\w+)"', acm.group(2)):
|
||||
cols.add(cm.group(1))
|
||||
|
||||
bad_paths = {}
|
||||
for m in re.finditer(r'<(?:\w+:)?\w*DataPath[^>]*>' + root_pat14 + r'\.([^<]+)</(?:\w+:)?\w*DataPath>', raw):
|
||||
segments = m.group(1).split('.')
|
||||
seg0 = segments[0]
|
||||
path_check_count += 1
|
||||
if seg0 in STANDARD_OBJECT_FIELDS:
|
||||
continue
|
||||
if seg0 not in src_names:
|
||||
bad_paths[f'{root_name14}.{seg0}'] = f'у {owner_key} нет такого реквизита или табличной части'
|
||||
continue
|
||||
# Второй сегмент проверяем только для табличных частей: у ссылочного реквизита
|
||||
# он ведёт в чужой объект, и это уже другая проверка.
|
||||
if len(segments) < 2 or seg0 not in src_ts_columns:
|
||||
continue
|
||||
seg1 = segments[1]
|
||||
if seg1 in STANDARD_OBJECT_FIELDS:
|
||||
continue
|
||||
# Итог колонки — псевдополе платформы: Total<Колонка> при живой колонке законен
|
||||
if seg1.startswith('Total') and seg1[5:] in src_ts_columns[seg0]:
|
||||
continue
|
||||
if seg1 not in src_ts_columns[seg0]:
|
||||
bad_paths[f'{root_name14}.{seg0}.{seg1}'] = f'у табличной части {seg0} нет колонки {seg1}, и <Columns> формы её не объявляет'
|
||||
|
||||
for bad in sorted(bad_paths):
|
||||
r.error(f"14. {ctx}: путь '{bad}' — {bad_paths[bad]}")
|
||||
check14_ok = False
|
||||
|
||||
if check14_ok:
|
||||
r.ok(f'14. Object paths vs source config: {path_check_count} checked')
|
||||
|
||||
# --- Check 15: основные роли расширения не дают прав на заимствованные объекты ---
|
||||
# Платформа: «Назначение прав доступа на заимствованные объекты основными ролями в
|
||||
# расширениях недопустимо». Роль вне <DefaultRoles> так делать вправе — проверяем только
|
||||
# основные. Ловится статически, а по симптому (отказ загрузки) причина не читается.
|
||||
default_role_nodes = cfg_node.findall('md:Properties/md:DefaultRoles/xr:Item', NS)
|
||||
if default_role_nodes:
|
||||
adopted_cache = {}
|
||||
|
||||
def is_object_adopted(type_name, obj_name):
|
||||
key = f"{type_name}.{obj_name}"
|
||||
if key in adopted_cache:
|
||||
return adopted_cache[key]
|
||||
adopted_cache[key] = False
|
||||
dir_name = CHILD_TYPE_DIR_MAP.get(type_name)
|
||||
if dir_name:
|
||||
obj_path = os.path.join(config_dir, dir_name, obj_name + '.xml')
|
||||
if os.path.isfile(obj_path):
|
||||
try:
|
||||
obj_root = etree.parse(obj_path).getroot()
|
||||
ob = obj_root.find(f'md:{type_name}/md:Properties/md:ObjectBelonging', NS)
|
||||
if ob is not None and (ob.text or '') == 'Adopted':
|
||||
adopted_cache[key] = True
|
||||
except Exception:
|
||||
pass
|
||||
return adopted_cache[key]
|
||||
|
||||
check15_ok = True
|
||||
check15_count = 0
|
||||
roles_ns = {'r': 'http://v8.1c.ru/8.2/roles'}
|
||||
for rn in default_role_nodes:
|
||||
m = re.match(r'^Role\.(.+)$', rn.text or '')
|
||||
if not m:
|
||||
continue
|
||||
def_role_name = m.group(1)
|
||||
rights_path = os.path.join(config_dir, 'Roles', def_role_name, 'Ext', 'Rights.xml')
|
||||
if not os.path.isfile(rights_path):
|
||||
continue
|
||||
try:
|
||||
rights_root = etree.parse(rights_path).getroot()
|
||||
except Exception:
|
||||
continue
|
||||
for name_node in rights_root.findall('r:object/r:name', roles_ns):
|
||||
full_name = name_node.text or ''
|
||||
segs = full_name.split('.')
|
||||
# Configuration.* — права самого расширения, не объект; заимствования там нет.
|
||||
if len(segs) < 2 or segs[0] == 'Configuration':
|
||||
continue
|
||||
check15_count += 1
|
||||
if is_object_adopted(segs[0], segs[1]):
|
||||
r.error(f"15. Роль '{def_role_name}' входит в DefaultRoles и даёт права на заимствованный "
|
||||
f"{segs[0]}.{segs[1]} ({full_name}): платформа это запрещает. "
|
||||
"Вынесите такие права в отдельную роль вне DefaultRoles.")
|
||||
check15_ok = False
|
||||
if check15_ok and check15_count > 0:
|
||||
r.ok(f'15. Основные роли: прав на заимствованные объекты нет ({check15_count} checked)')
|
||||
|
||||
if r.stopped:
|
||||
r.finalize(out_file)
|
||||
sys.exit(1)
|
||||
|
||||
# --- Check 16: модуль заимствованного объекта и пометка расширенного свойства ---
|
||||
# Свойство <xr:PropertyState> появилось в формате 2.19 (8.3.26); ниже платформа его молча
|
||||
# выбрасывает, поэтому там проверять нечего. С 2.19 состояние обязано соответствовать факту:
|
||||
# есть файл модуля — есть пометка, и наоборот. Перекос платформа принимает (проверено на
|
||||
# стенде), но выгрузка Конфигуратора так не выглядит — отсюда предупреждение, а не ошибка.
|
||||
if version_rank >= 219 and child_obj_node is not None:
|
||||
state_issues = []
|
||||
state_checked = 0
|
||||
for child in child_obj_node:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
type_name = etree.QName(child.tag).localname
|
||||
if type_name not in MODULE_KINDS_BY_TYPE or type_name not in CHILD_TYPE_DIR_MAP:
|
||||
continue
|
||||
obj_name_val = (child.text or '').strip()
|
||||
if not obj_name_val:
|
||||
continue
|
||||
type_dir = os.path.join(config_dir, CHILD_TYPE_DIR_MAP[type_name])
|
||||
obj_file = os.path.join(type_dir, f'{obj_name_val}.xml')
|
||||
if not os.path.isfile(obj_file):
|
||||
continue
|
||||
with open(obj_file, 'r', encoding='utf-8-sig') as f:
|
||||
obj_text = f.read()
|
||||
if '<ObjectBelonging>Adopted</ObjectBelonging>' not in obj_text:
|
||||
continue
|
||||
|
||||
for kind in MODULE_KINDS_BY_TYPE[type_name]:
|
||||
state_checked += 1
|
||||
has_file = os.path.isfile(os.path.join(type_dir, obj_name_val, 'Ext', f'{kind}.bsl'))
|
||||
has_flag = f'<xr:Property>{kind}</xr:Property>' in obj_text
|
||||
if has_file and not has_flag:
|
||||
state_issues.append(f'{type_name}.{obj_name_val} — есть {kind}.bsl, но нет <xr:PropertyState> для {kind}')
|
||||
elif has_flag and not has_file:
|
||||
state_issues.append(f'{type_name}.{obj_name_val} — есть <xr:PropertyState> для {kind}, но нет {kind}.bsl')
|
||||
|
||||
if state_checked > 0:
|
||||
if not state_issues:
|
||||
r.ok(f'16. Модули заимствованных объектов: пометки расширенных свойств согласованы ({state_checked})')
|
||||
else:
|
||||
for issue in state_issues:
|
||||
r.warn(f'16. {issue}')
|
||||
|
||||
# --- Breadcrumb: controlled methods (&ИзменениеИКонтроль) drift is not checked here ---
|
||||
ctrl_kw = bsl_keywords()
|
||||
ctrl_re = re.compile(r'^\s*&(?:' + ctrl_kw["ru"]["Control"] + '|' + ctrl_kw["en"]["Control"] + r')\(', re.IGNORECASE)
|
||||
ctrl_count = 0
|
||||
for dp, _dn, files in os.walk(config_dir):
|
||||
for fn in files:
|
||||
@@ -894,7 +1312,7 @@ def main():
|
||||
try:
|
||||
with open(os.path.join(dp, fn), 'r', encoding='utf-8-sig') as f:
|
||||
for ln in f:
|
||||
if re.match(r'^\s*&ИзменениеИКонтроль\(', ln):
|
||||
if ctrl_re.match(ln):
|
||||
ctrl_count += 1
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
name: db-cfe-admin
|
||||
description: Управление расширениями конфигурации в информационной базе 1С. Используй когда нужно узнать какие расширения подключены к базе, выполнить проверку применимости или синтаксическую проверку, изменить безопасный режим или активность, удалить расширение из базы
|
||||
argument-hint: <list|check|set-properties|delete> [database] [-Name <Имя>]
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
- AskUserQuestion
|
||||
---
|
||||
|
||||
# /db-cfe-admin — Управление расширениями конфигурации
|
||||
|
||||
Расширения **на стороне базы**: состав и свойства подключения, проверки, удаление.
|
||||
Про исходники расширения — другие навыки, см. «Смежное».
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/db-cfe-admin list [database]
|
||||
/db-cfe-admin check [database] [-Name Расш1]
|
||||
/db-cfe-admin set-properties [database] -Name Расш1 -SafeMode off
|
||||
/db-cfe-admin delete [database] -Name Расш1
|
||||
```
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-cfe-admin/scripts/db-cfe-admin.ps1" -Command <команда> <параметры>
|
||||
```
|
||||
|
||||
### Общие параметры
|
||||
|
||||
| Параметр | Обязательный | Описание |
|
||||
|----------|:------------:|----------|
|
||||
| `-Command <команда>` | да | `list` / `check` / `set-properties` / `delete` |
|
||||
| `-V8Path <путь>` | нет | Каталог bin платформы или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||
| `-UserName <имя>` | нет | Пользователь базы |
|
||||
| `-Password <пароль>` | нет | Пароль пользователя |
|
||||
| `-Name <имя>` | усл. | Расширение. Обязателен для `set-properties`; в `delete` — вместо `-All`. Без него `list` и `check` работают по всем расширениям |
|
||||
| `-All` | усл. | Только для `delete`: удалить все расширения. Вместо `-Name`, а не вместе с ним |
|
||||
| `-AdditionalV8Arguments <список>` | нет | Доп. аргументы `1cv8.exe` через запятую |
|
||||
| `-AdditionalIbcmdArguments <список>` | нет | Доп. аргументы `ibcmd` через запятую, в форме `--ключ=значение` |
|
||||
|
||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||
|
||||
### Параметры `check`
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `-Checks <список>` | `apply` — применимость расширения, `modules` — синтаксическая проверка, `config` — проверки конфигурации (целостность, ссылки, неиспользуемые процедуры и обработчики). Через запятую, по умолчанию `apply,modules` |
|
||||
| `-Context <список>` | Контексты синтаксической проверки: `ThinClient`, `WebClient`, `Server`, `ExternalConnection`, `ThickClientManagedApplication`, `ThickClientOrdinaryApplication`, `MobileClient` и др. Через запятую, по умолчанию `ThinClient,Server` |
|
||||
|
||||
Применимость и синтаксис проверяют разное и друг друга не заменяют. Проверяется только
|
||||
расширение: ошибки самой конфигурации сюда не попадают.
|
||||
|
||||
### Свойства `set-properties`
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `-SafeMode <on/off>` | Безопасный режим |
|
||||
| `-Active <on/off>` | Активность расширения |
|
||||
| `-UnsafeActionProtection <on/off>` | Защита от опасных действий |
|
||||
| `-UsedInDistributedInfobase <on/off>` | Использование в распределённой ИБ |
|
||||
| `-Scope <область>` | `infobase` / `data-separation` |
|
||||
| `-SecurityProfile <имя>` | Профиль безопасности |
|
||||
|
||||
Передавай только то, что меняешь: не указанное свойство остаётся как было. Расширение, впервые
|
||||
попавшее в базу загрузкой, создаётся с включённым безопасным режимом, а в нём расширение модуля не
|
||||
применяется.
|
||||
|
||||
Свойствами управляет `ibcmd` — он есть не в каждой установке платформы и работает с файловой базой;
|
||||
остальные команды работают всегда.
|
||||
|
||||
## Смежное
|
||||
|
||||
| Задача | Навык |
|
||||
|--------|-------|
|
||||
| Создать расширение, заимствовать объекты, перехватить метод | `/cfe-init`, `/cfe-borrow`, `/cfe-patch-method`, `/cfe-validate` |
|
||||
| Загрузить исходники расширения в базу | `/db-load-xml -Extension` (из коммита Git — `/db-load-git`) |
|
||||
| Загрузить готовый `.cfe` | `/db-load-cf -Extension` |
|
||||
| Выгрузить расширение из базы | `/db-dump-xml -Extension`, `/db-dump-cf -Extension` |
|
||||
| Обновить конфигурацию базы после загрузки | `/db-update -Extension` |
|
||||
| Проверить дрейф контролируемых методов по исходникам | `/cfe-patch-method -Check` |
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Что подключено к базе
|
||||
... -Command list -InfoBasePath "C:\Bases\MyDB"
|
||||
|
||||
# Проверить расширение
|
||||
... -Command check -InfoBasePath "C:\Bases\MyDB" -Name "Расш1"
|
||||
|
||||
# Синтаксическая проверка в контексте веб-клиента
|
||||
... -Command check -InfoBasePath "C:\Bases\MyDB" -Checks modules -Context WebClient,Server
|
||||
|
||||
# Снять безопасный режим
|
||||
... -Command set-properties -InfoBasePath "C:\Bases\MyDB" -Name "Расш1" -SafeMode off
|
||||
|
||||
# Отключить, не удаляя
|
||||
... -Command set-properties -InfoBasePath "C:\Bases\MyDB" -Name "Расш1" -Active off
|
||||
|
||||
# Убрать расширение из базы
|
||||
... -Command delete -InfoBasePath "C:\Bases\MyDB" -Name "Расш1"
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -24,14 +24,14 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта для `v8path` (путь к платформе).
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Прочитай `.v8-project.json` из корня проекта. Платформа — `v8path` записи создаваемой базы,
|
||||
если она уже в реестре, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
После создания базы предложи зарегистрировать через `/db-list add`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-create/scripts/db-create.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -59,14 +59,14 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" <п
|
||||
|
||||
```powershell
|
||||
# Создать файловую базу
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-create/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB"
|
||||
|
||||
# Создать серверную базу
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-create/scripts/db-create.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test"
|
||||
|
||||
# Создать из шаблона CF
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB" -UseTemplate "C:\Templates\config.cf"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-create/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB" -UseTemplate "C:\Templates\config.cf"
|
||||
|
||||
# Создать и добавить в список баз
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB" -AddToList -ListName "Новая база"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-create/scripts/db-create.ps1" -InfoBasePath "C:\Bases\NewDB" -AddToList -ListName "Новая база"
|
||||
```
|
||||
+65
-2
@@ -1,4 +1,4 @@
|
||||
# db-create v1.10 — Create 1C information base
|
||||
# db-create v1.15 — Create 1C information base
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -46,7 +46,7 @@
|
||||
.\db-create.ps1 -InfoBasePath "C:\Bases\NewDB" -UseTemplate "C:\Templates\config.cf" -AddToList -ListName "Новая база"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -88,6 +88,17 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
@@ -138,6 +149,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -224,8 +243,52 @@ $V8Path = ConvertTo-CleanPath $V8Path '-V8Path'
|
||||
$InfoBasePath = ConvertTo-CleanPath $InfoBasePath '-InfoBasePath'
|
||||
$UseTemplate = ConvertTo-CleanPath $UseTemplate '-UseTemplate'
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
+132
-23
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-create v1.10 — Create 1C information base
|
||||
# db-create v1.15 — Create 1C information base
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,85 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,6 +121,17 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
@@ -98,15 +185,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +267,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +297,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +314,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -270,7 +361,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -291,7 +382,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -310,11 +401,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -355,13 +466,13 @@ def main():
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
args.UseTemplate = clean_path(args.UseTemplate, "-UseTemplate")
|
||||
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -379,15 +490,15 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate template ---
|
||||
if args.UseTemplate and not os.path.exists(args.UseTemplate):
|
||||
print(f"Error: template file not found: {args.UseTemplate}", file=sys.stderr)
|
||||
print(f"Error: template file not found: {args.UseTemplate}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- ibcmd branch (file infobase only) ---
|
||||
@@ -414,10 +525,9 @@ def main():
|
||||
print(
|
||||
f"Error: exit code 0 but 1Cv8.1CD is missing or empty at {args.InfoBasePath} "
|
||||
"— information base was not created",
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
print(f"Error creating information base (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error creating information base (code: {exit_code})")
|
||||
print_platform_output(result)
|
||||
sys.exit(exit_code)
|
||||
|
||||
@@ -474,10 +584,9 @@ def main():
|
||||
print(
|
||||
f"Error: exit code 0 but 1Cv8.1CD is missing or empty at {args.InfoBasePath} "
|
||||
"— information base was not created",
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
print(f"Error creating information base (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error creating information base (code: {exit_code})")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -23,19 +23,19 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-cf.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-cf/scripts/db-dump-cf.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -60,11 +60,11 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-cf.ps1" <п
|
||||
|
||||
```powershell
|
||||
# Выгрузка конфигурации (файловая база)
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\config.cf"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-cf/scripts/db-dump-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\config.cf"
|
||||
|
||||
# Серверная база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-cf.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "config.cf"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-cf/scripts/db-dump-cf.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "config.cf"
|
||||
|
||||
# Выгрузка расширения
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-cf/scripts/db-dump-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
```
|
||||
+65
-2
@@ -1,4 +1,4 @@
|
||||
# db-dump-cf v1.12 — Dump 1C configuration to CF file
|
||||
# db-dump-cf v1.17 — Dump 1C configuration to CF file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -49,7 +49,7 @@
|
||||
.\db-dump-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -OutputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -104,6 +104,17 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
@@ -154,6 +165,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -253,8 +272,52 @@ function Assert-InfoBaseExists {
|
||||
|
||||
Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
+135
-24
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-dump-cf v1.12 — Dump 1C configuration to CF file
|
||||
# db-dump-cf v1.17 — Dump 1C configuration to CF file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,85 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,6 +121,17 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
@@ -98,15 +185,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +267,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +297,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +314,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +352,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +369,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +388,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -330,7 +441,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -375,14 +486,14 @@ def main():
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
assert_infobase_exists(args.InfoBasePath)
|
||||
args.OutputFile = clean_path(args.OutputFile, "-OutputFile")
|
||||
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -400,10 +511,10 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Ensure output directory exists ---
|
||||
@@ -414,7 +525,7 @@ def main():
|
||||
# --- ibcmd branch (file infobase only) ---
|
||||
if engine == "ibcmd":
|
||||
if args.AllExtensions:
|
||||
print("Error: ibcmd config save does not support -AllExtensions (use -Extension)", file=sys.stderr)
|
||||
print("Error: ibcmd config save does not support -AllExtensions (use -Extension)")
|
||||
sys.exit(1)
|
||||
arguments = ["infobase", "config", "save", f"--db-path={args.InfoBasePath}"]
|
||||
if args.Extension:
|
||||
@@ -437,9 +548,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Configuration dumped successfully to: {args.OutputFile}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — configuration was not dumped", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — configuration was not dumped")
|
||||
else:
|
||||
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error dumping configuration (code: {exit_code})")
|
||||
sys.exit(exit_code)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -487,9 +598,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Configuration dumped successfully to: {args.OutputFile}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — configuration was not dumped", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — configuration was not dumped")
|
||||
else:
|
||||
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error dumping configuration (code: {exit_code})")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -26,19 +26,19 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-dt.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-dt/scripts/db-dump-dt.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -61,10 +61,10 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-dt.ps1" <п
|
||||
|
||||
```powershell
|
||||
# Выгрузка ИБ (файловая база)
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\base.dt"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-dt/scripts/db-dump-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\base.dt"
|
||||
|
||||
# Серверная база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "base.dt"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-dt/scripts/db-dump-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "base.dt"
|
||||
```
|
||||
|
||||
## Связанные навыки
|
||||
+65
-2
@@ -1,4 +1,4 @@
|
||||
# db-dump-dt v1.11 — Dump 1C information base to DT file
|
||||
# db-dump-dt v1.16 — Dump 1C information base to DT file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -39,7 +39,7 @@
|
||||
.\db-dump-dt.ps1 -InfoBasePath "C:\Bases\MyDB" -OutputFile "backup.dt"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -88,6 +88,17 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
@@ -138,6 +149,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -237,8 +256,52 @@ function Assert-InfoBaseExists {
|
||||
|
||||
Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
+134
-23
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-dump-dt v1.11 — Dump 1C information base to DT file
|
||||
# db-dump-dt v1.16 — Dump 1C information base to DT file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,85 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,6 +121,17 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
@@ -98,15 +185,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +267,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +297,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +314,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +352,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +369,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +388,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -330,7 +441,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -373,14 +484,14 @@ def main():
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
assert_infobase_exists(args.InfoBasePath)
|
||||
args.OutputFile = clean_path(args.OutputFile, "-OutputFile")
|
||||
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -398,10 +509,10 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Ensure output directory exists ---
|
||||
@@ -430,9 +541,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Information base dumped successfully to: {args.OutputFile}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — information base was not dumped", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — information base was not dumped")
|
||||
else:
|
||||
print(f"Error dumping information base (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error dumping information base (code: {exit_code})")
|
||||
sys.exit(exit_code)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -474,9 +585,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Information base dumped successfully to: {args.OutputFile}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — information base was not dumped", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no non-empty file at {args.OutputFile} — information base was not dumped")
|
||||
else:
|
||||
print(f"Error dumping information base (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error dumping information base (code: {exit_code})")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -24,20 +24,21 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
Если в записи базы указан `configSrc` — используй как каталог выгрузки по умолчанию.
|
||||
Для `-Extension` каталог берётся из `extensions[].src` записи базы, если он там указан.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -76,17 +77,17 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" <
|
||||
|
||||
```powershell
|
||||
# Полная выгрузка (файловая база)
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
|
||||
# Инкрементальная выгрузка
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Changes
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Changes
|
||||
|
||||
# Частичная выгрузка
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Objects "Справочник.Номенклатура,Документ.Заказ"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Objects "Справочник.Номенклатура,Документ.Заказ"
|
||||
|
||||
# Серверная база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
|
||||
# Выгрузка расширения
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-dump-xml/scripts/db-dump-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||
```
|
||||
+159
-7
@@ -1,4 +1,4 @@
|
||||
# db-dump-xml v1.14 — Dump 1C configuration to XML files
|
||||
# db-dump-xml v1.22 — Dump 1C configuration to XML files
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -61,7 +61,7 @@
|
||||
.\db-dump-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Partial -Objects "Справочник.Номенклатура,Документ.Заказ"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -85,8 +85,10 @@ param(
|
||||
[string]$ConfigDir,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[ValidateSet("Full", "Changes", "Partial", "UpdateInfo")]
|
||||
[string]$Mode = "Changes",
|
||||
# Пустое значение = режим не задан. Прежнее умолчание Changes подставляется ниже, после
|
||||
# того как станет видно, перечислены ли объекты.
|
||||
[ValidateSet("", "Full", "Changes", "Partial", "UpdateInfo")]
|
||||
[string]$Mode = "",
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$Objects,
|
||||
@@ -101,6 +103,18 @@ param(
|
||||
[ValidateSet("Hierarchical", "Plain")]
|
||||
[string]$Format = "Hierarchical",
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$ObjectsFile,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPath,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryUser,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPassword,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string[]]$AdditionalV8Arguments = @(),
|
||||
|
||||
@@ -111,6 +125,91 @@ param(
|
||||
$OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Resolve-RepositorySettings {
|
||||
# Возвращает @{ Path; User; Password; FromRegistry }. Явные -Repository* всегда сильнее реестра.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
$rec = $null
|
||||
if ($dbRec) {
|
||||
if ($Extension) {
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
if ($dbRec.extensions) {
|
||||
foreach ($ext in $dbRec.extensions) {
|
||||
if ($ext.name -and $ext.name.Equals($Extension, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
$rec = $ext.repository
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$rec = $dbRec.repository
|
||||
}
|
||||
}
|
||||
$path = if ($RepositoryPath) { $RepositoryPath } elseif ($rec -and $rec.path) { [string]$rec.path } else { $null }
|
||||
$user = if ($RepositoryUser) { $RepositoryUser } elseif ($rec -and $rec.user) { [string]$rec.user } else { $null }
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
$pwd = if ($RepositoryPassword) { $RepositoryPassword } elseif ($rec -and $rec.password) { [string]$rec.password } else { $null }
|
||||
return @{
|
||||
Path = if ($path) { $path.Trim().Trim('"') } else { $null }
|
||||
User = $user
|
||||
Password = $pwd
|
||||
FromRegistry = [bool]($rec -and $rec.path)
|
||||
DbRecord = $dbRec
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RepositoryArgs {
|
||||
# Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P.
|
||||
param([hashtable]$Repo)
|
||||
$a = @()
|
||||
if (-not $Repo -or -not $Repo.Path) { return $a }
|
||||
$a += "/ConfigurationRepositoryF`"$($Repo.Path)`""
|
||||
if ($Repo.User) { $a += "/ConfigurationRepositoryN`"$($Repo.User)`"" }
|
||||
if ($Repo.Password) { $a += "/ConfigurationRepositoryP`"$($Repo.Password)`"" }
|
||||
return $a
|
||||
}
|
||||
|
||||
function Protect-Secrets {
|
||||
# Redact literal secret values from a display string (String.Replace is literal, not regex).
|
||||
param([string]$Text, [string[]]$Secrets)
|
||||
@@ -127,12 +226,23 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
'--user', '--password'
|
||||
)
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP')
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP', '/ConfigurationRepositoryP')
|
||||
$script:IbcmdSecretKeys = @('--password', '--token', '--db-pwd')
|
||||
|
||||
function Test-ArgKeyMatch {
|
||||
@@ -177,6 +287,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -278,6 +396,10 @@ Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
@@ -415,8 +537,33 @@ if ($engine -eq "ibcmd") {
|
||||
}
|
||||
|
||||
# --- Validate Partial mode ---
|
||||
# Список объектов приходит либо строкой, либо файлом: файл нужен, чтобы не перепечатывать
|
||||
# то, что уже напечатал другой навык (например /db-repo update со списком полученных объектов).
|
||||
if ($ObjectsFile) {
|
||||
if (-not (Test-Path $ObjectsFile)) {
|
||||
Write-Host "Error: -ObjectsFile not found: $ObjectsFile" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
$fromFile = @([System.IO.File]::ReadAllLines($ObjectsFile, [System.Text.Encoding]::UTF8) |
|
||||
ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') })
|
||||
$Objects = (@(@($Objects -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) + $fromFile) -join ',')
|
||||
}
|
||||
# Перечислены объекты — операция частичная. Иначе список молча игнорировался бы: умолчание
|
||||
# Changes выгружает «изменённое с прошлой выгрузки», а не то, что просили.
|
||||
if ($Objects) {
|
||||
if ($Mode -eq "UpdateInfo") {
|
||||
# Не «шире/уже», а другая операция: обновление ConfigDumpInfo без выгрузки файлов.
|
||||
Write-Host "Error: -Mode UpdateInfo does not take an object list — it only refreshes ConfigDumpInfo.xml" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Mode -eq "Full" -or $Mode -eq "Changes") {
|
||||
Write-Host "[note] перечислены объекты — выгружаются только они; -Mode $Mode не применён" -ForegroundColor Yellow
|
||||
}
|
||||
$Mode = "Partial"
|
||||
}
|
||||
if (-not $Mode) { $Mode = "Changes" }
|
||||
if ($Mode -eq "Partial" -and -not $Objects) {
|
||||
Write-Host "Error: -Objects required for Partial mode" -ForegroundColor Red
|
||||
Write-Host "Error: -Objects or -ObjectsFile required for Partial mode" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -486,6 +633,11 @@ try {
|
||||
if ($UserName) { $arguments += "/N`"$UserName`"" }
|
||||
if ($Password) { $arguments += "/P`"$Password`"" }
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
$__repo = Resolve-RepositorySettings
|
||||
$arguments += Get-RepositoryArgs $__repo
|
||||
|
||||
$arguments += "/DumpConfigToFiles", "`"$ConfigDir`""
|
||||
$arguments += "-Format", $Format
|
||||
|
||||
@@ -530,7 +682,7 @@ try {
|
||||
$arguments += $extraArgs
|
||||
|
||||
# --- Execute ---
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName))"
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName, $__repo.Password))"
|
||||
$__v8 = Invoke-PlatformProcess $V8Path $arguments -PreQuoted
|
||||
$exitCode = $__v8.ExitCode
|
||||
|
||||
+214
-30
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-dump-xml v1.14 — Dump 1C configuration to XML files
|
||||
# db-dump-xml v1.22 — Dump 1C configuration to XML files
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,38 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,15 +74,112 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
"--user", "--password",
|
||||
]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP"]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP", "/ConfigurationRepositoryP"]
|
||||
IBCMD_SECRET_KEYS = ["--password", "--token", "--db-pwd"]
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def resolve_repository_settings(args):
|
||||
"""Возвращает dict path/user/password/from_registry. Явные -Repository* сильнее реестра."""
|
||||
db_rec = find_project_database(args)
|
||||
rec = None
|
||||
if db_rec:
|
||||
if args.Extension:
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
for ext in db_rec.get("extensions") or []:
|
||||
if (ext.get("name") or "").lower() == args.Extension.lower():
|
||||
rec = ext.get("repository")
|
||||
break
|
||||
else:
|
||||
rec = db_rec.get("repository")
|
||||
path = args.RepositoryPath or ((rec or {}).get("path") or None)
|
||||
user = args.RepositoryUser or ((rec or {}).get("user") or None)
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
pwd = args.RepositoryPassword or ((rec or {}).get("password") or None)
|
||||
return {
|
||||
"path": path.strip().strip('"') if path else None,
|
||||
"user": user,
|
||||
"password": pwd,
|
||||
"from_registry": bool(rec and rec.get("path")),
|
||||
}
|
||||
|
||||
|
||||
def repository_args(repo):
|
||||
"""Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P."""
|
||||
a = []
|
||||
if not repo or not repo.get("path"):
|
||||
return a
|
||||
a.append('/ConfigurationRepositoryF"%s"' % repo["path"])
|
||||
if repo.get("user"):
|
||||
a.append('/ConfigurationRepositoryN"%s"' % repo["user"])
|
||||
if repo.get("password"):
|
||||
a.append('/ConfigurationRepositoryP"%s"' % repo["password"])
|
||||
return a
|
||||
|
||||
|
||||
def arg_key_match(token, key):
|
||||
"""Token matches a key when it equals it, or starts with it and the next character
|
||||
is not a letter — catches glued /N"user" and --password=x, while keeping
|
||||
@@ -98,15 +224,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +306,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +336,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +353,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +391,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +408,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +427,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -330,7 +480,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -366,14 +516,18 @@ def main():
|
||||
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
|
||||
parser.add_argument("-UserName", default="", help="1C user name")
|
||||
parser.add_argument("-Password", default="", help="1C user password")
|
||||
parser.add_argument("-RepositoryPath", default="")
|
||||
parser.add_argument("-RepositoryUser", default="")
|
||||
parser.add_argument("-RepositoryPassword", default="")
|
||||
parser.add_argument("-ConfigDir", required=True, help="Directory for configuration dump")
|
||||
parser.add_argument(
|
||||
"-Mode",
|
||||
default="Changes",
|
||||
choices=["Full", "Changes", "Partial", "UpdateInfo"],
|
||||
default="",
|
||||
choices=["", "Full", "Changes", "Partial", "UpdateInfo"],
|
||||
help="Dump mode (default: Changes)",
|
||||
)
|
||||
parser.add_argument("-Objects", default="", help="Comma-separated metadata object names (for Partial mode)")
|
||||
parser.add_argument("-ObjectsFile", default="")
|
||||
parser.add_argument("-Extension", default="", help="Extension name to dump")
|
||||
parser.add_argument("-AllExtensions", action="store_true", help="Dump all extensions")
|
||||
parser.add_argument(
|
||||
@@ -388,7 +542,7 @@ def main():
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
@@ -396,7 +550,7 @@ def main():
|
||||
args.ConfigDir = clean_path(args.ConfigDir, "-ConfigDir")
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -414,15 +568,40 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate Partial mode ---
|
||||
# Список объектов приходит либо строкой, либо файлом: файл нужен, чтобы не перепечатывать
|
||||
# то, что уже напечатал другой навык (например /db-repo update со списком полученных объектов).
|
||||
if args.ObjectsFile:
|
||||
if not os.path.exists(args.ObjectsFile):
|
||||
print("Error: -ObjectsFile not found: %s" % args.ObjectsFile)
|
||||
sys.exit(1)
|
||||
with open(args.ObjectsFile, encoding="utf-8-sig") as f:
|
||||
from_file = [s.strip() for s in f.read().splitlines()
|
||||
if s.strip() and not s.strip().startswith("#")]
|
||||
inline = [s.strip() for s in args.Objects.split(",") if s.strip()]
|
||||
args.Objects = ",".join(inline + from_file)
|
||||
# Перечислены объекты — операция частичная. Иначе список молча игнорировался бы: умолчание
|
||||
# Changes выгружает «изменённое с прошлой выгрузки», а не то, что просили.
|
||||
if args.Objects:
|
||||
if args.Mode == "UpdateInfo":
|
||||
# Не «шире/уже», а другая операция: обновление ConfigDumpInfo без выгрузки файлов.
|
||||
print("Error: -Mode UpdateInfo does not take an object list — it only refreshes "
|
||||
"ConfigDumpInfo.xml")
|
||||
sys.exit(1)
|
||||
if args.Mode in ("Full", "Changes"):
|
||||
print("[note] перечислены объекты — выгружаются только они; -Mode %s не применён"
|
||||
% args.Mode)
|
||||
args.Mode = "Partial"
|
||||
if not args.Mode:
|
||||
args.Mode = "Changes"
|
||||
if args.Mode == "Partial" and not args.Objects:
|
||||
print("Error: -Objects required for Partial mode", file=sys.stderr)
|
||||
print("Error: -Objects or -ObjectsFile required for Partial mode")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Create output dir if needed ---
|
||||
@@ -433,12 +612,12 @@ def main():
|
||||
# --- ibcmd branch (file infobase only; hierarchical Full/Changes) ---
|
||||
if engine == "ibcmd":
|
||||
if args.Format == "Plain":
|
||||
print("Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
|
||||
print("Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)")
|
||||
sys.exit(1)
|
||||
if args.AllExtensions:
|
||||
arguments = ["infobase", "config", "export", "all-extensions", args.ConfigDir, f"--db-path={args.InfoBasePath}"]
|
||||
elif args.Mode == "UpdateInfo":
|
||||
print("Error: ibcmd config export does not support Mode UpdateInfo; use 1cv8", file=sys.stderr)
|
||||
print("Error: ibcmd config export does not support Mode UpdateInfo; use 1cv8")
|
||||
sys.exit(1)
|
||||
elif args.Mode == "Partial":
|
||||
obj_list = [o.strip() for o in args.Objects.split(",") if o.strip()]
|
||||
@@ -468,9 +647,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Configuration exported successfully to: {args.ConfigDir}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no files under {args.ConfigDir} — configuration was not exported", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no files under {args.ConfigDir} — configuration was not exported")
|
||||
else:
|
||||
print(f"Error exporting configuration (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error exporting configuration (code: {exit_code})")
|
||||
sys.exit(exit_code)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -491,6 +670,11 @@ def main():
|
||||
if args.Password:
|
||||
arguments.append(f'/P"{args.Password}"')
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
repo = resolve_repository_settings(args)
|
||||
arguments.extend(repository_args(repo))
|
||||
|
||||
arguments += ["/DumpConfigToFiles", f'"{args.ConfigDir}"']
|
||||
arguments += ["-Format", args.Format]
|
||||
|
||||
@@ -529,7 +713,7 @@ def main():
|
||||
arguments.extend(quote_if_needed(a) for a in extra_args)
|
||||
|
||||
# --- Execute ---
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName)}")
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName, repo['password'])}")
|
||||
result = run_v8(v8path, arguments)
|
||||
exit_code = result.returncode
|
||||
|
||||
@@ -542,9 +726,9 @@ def main():
|
||||
print("Dump completed successfully")
|
||||
print(f"Configuration dumped to: {args.ConfigDir}")
|
||||
elif out_missing:
|
||||
print(f"Error: exit code 0 but no files under {args.ConfigDir} — configuration was not dumped", file=sys.stderr)
|
||||
print(f"Error: exit code 0 but no files under {args.ConfigDir} — configuration was not dumped")
|
||||
else:
|
||||
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
|
||||
print(f"Error dumping configuration (code: {exit_code})")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -36,11 +36,24 @@ allowed-tools:
|
||||
"name": "Разработка",
|
||||
"type": "file",
|
||||
"path": "C:\\Bases\\MyApp_Dev",
|
||||
"v8path": "C:\\Program Files\\1cv8\\8.3.27.1688\\bin",
|
||||
"user": "Admin",
|
||||
"password": "",
|
||||
"aliases": ["dev", "разработка"],
|
||||
"branches": ["dev", "develop", "feature/*"],
|
||||
"configSrc": "C:\\WS\\myapp\\cfsrc"
|
||||
"configSrc": "C:\\WS\\myapp\\cfsrc",
|
||||
"repository": {
|
||||
"path": "\\\\srv01\\repo\\MyApp",
|
||||
"user": "Ivanov",
|
||||
"password": ""
|
||||
},
|
||||
"extensions": [
|
||||
{
|
||||
"name": "МоёРасширение",
|
||||
"src": "src\\cfe\\МоёРасширение",
|
||||
"repository": { "path": "\\\\srv01\\repo\\MyApp_Ext", "user": "Ivanov", "password": "" }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "test",
|
||||
@@ -64,6 +77,9 @@ allowed-tools:
|
||||
| `v8path` | string | Каталог bin платформы 1С. Необязательный — если не задан, автоопределение |
|
||||
| `v8args` | array | Доп. аргументы запуска `1cv8.exe` для всех навыков, напр. `["/UseHwLicenses+"]` |
|
||||
| `ibcmdargs` | array | Доп. аргументы `ibcmd` (форма `--ключ=значение`) |
|
||||
| `newObjectPosition` | `"end"` / `"byName"` | Куда попадает новый объект в составе конфигурации: в конец своего вида (по умолчанию) или на место по имени. Переопределяется в `databases[]` |
|
||||
| `extensionApplyCheck` | bool | Проверять ли применимость расширения после загрузки в базу (по умолчанию `true`). Разово отключается ключом `-NoApplyCheck` |
|
||||
| `externalCheck` | bool | Проверять ли исходники внешней обработки/отчёта платформой перед сборкой (по умолчанию `true`). Разово отключается ключом `-Checks off` |
|
||||
| `databases` | array | Массив баз данных |
|
||||
| `default` | string | id базы по умолчанию |
|
||||
|
||||
@@ -77,11 +93,41 @@ allowed-tools:
|
||||
| `path` | string | для file | Путь к каталогу файловой базы |
|
||||
| `server` | string | для server | Адрес сервера 1С |
|
||||
| `ref` | string | для server | Имя базы на сервере |
|
||||
| `v8path` | string | нет | Платформа именно этой базы — перекрывает корневой `v8path` (см. ниже) |
|
||||
| `user` | string | нет | Имя пользователя 1С |
|
||||
| `password` | string | нет | Пароль |
|
||||
| `aliases` | string[] | нет | Альтернативные имена для быстрого доступа |
|
||||
| `branches` | string[] | нет | Git-ветки или glob-паттерны (`release/*`, `feature/*`), привязанные к этой базе |
|
||||
| `configSrc` | string | нет | Каталог XML-выгрузки конфигурации |
|
||||
| `repository` | object | нет | Хранилище конфигурации: `path`, `user`, `password` (см. ниже) |
|
||||
| `extensions` | array | нет | Расширения: `name`, `src`, необязательное `repository` (см. ниже) |
|
||||
|
||||
### Хранилище конфигурации
|
||||
|
||||
База, подключённая к хранилищу конфигурации 1С, **не принимает ни одной операции конфигуратора**
|
||||
без реквизитов доступа к хранилищу — это касается не только `/db-repo`, но и `/db-load-xml`,
|
||||
`/db-dump-xml`, `/db-update`, `/db-load-git`. Реквизиты берутся из `repository` записи базы,
|
||||
передавать их в каждом вызове не нужно.
|
||||
|
||||
| Поле | Тип | Обязательное | Описание |
|
||||
|------|-----|:------------:|----------|
|
||||
| `repository.path` | string | да | Каталог хранилища или `tcp://<хост>[:<порт>]/<имя>` |
|
||||
| `repository.user` | string | нет | Пользователь **хранилища**. Не наследуется от `user` базы |
|
||||
| `repository.password` | string | нет | Пароль пользователя хранилища |
|
||||
|
||||
У расширения **своё хранилище** со своим путём, поэтому одного `repository` мало:
|
||||
|
||||
| Поле | Тип | Обязательное | Описание |
|
||||
|------|-----|:------------:|----------|
|
||||
| `extensions[].name` | string | да | Имя расширения, как в конфигурации |
|
||||
| `extensions[].src` | string | нет | Каталог XML-исходников расширения |
|
||||
| `extensions[].repository` | object | нет | Хранилище расширения. Расширение без хранилища — обычный случай |
|
||||
|
||||
Пароль хранилища — такой же секрет, как `password` базы; `.v8-project.json` в `.gitignore`.
|
||||
|
||||
> **Сетевое хранилище.** Адрес — `tcp://<хост>[:<порт>]/<имя>`, порт по умолчанию 1542.
|
||||
> Обслуживается сервером хранилища. Если он недоступен, платформа отвечает «Соединение с
|
||||
> хранилищем конфигурации не установлено» — тем же сообщением, что и при отсутствии реквизитов.
|
||||
|
||||
## Алгоритм разрешения базы данных
|
||||
|
||||
@@ -101,9 +147,15 @@ allowed-tools:
|
||||
|
||||
После выполнения: если использованная база не зарегистрирована — предложи добавить через `/db-list add`.
|
||||
|
||||
### Автоопределение платформы
|
||||
### Выбор платформы
|
||||
|
||||
Если `v8path` не задан в конфиге:
|
||||
Порядок: явный `-V8Path` в вызове → `v8path` записи базы → корневой `v8path` → автоопределение.
|
||||
Запись базы находит сам скрипт, сопоставляя параметры соединения с `databases[]`, — передавать
|
||||
`-V8Path` руками не нужно. Поле у базы нужно, когда базы проекта живут на разных версиях платформы:
|
||||
формат XML-выгрузки задаёт та платформа, которая выгружает, а автоопределение берёт самую старшую
|
||||
установленную.
|
||||
|
||||
Если `v8path` не задан нигде:
|
||||
|
||||
```powershell
|
||||
$v8 = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort-Object -Descending | Select-Object -First 1
|
||||
@@ -128,6 +180,7 @@ test Тестовая server srv01/MyApp_Test
|
||||
- path (для file) или server + ref (для server)
|
||||
- user, password (необязательно)
|
||||
- aliases, branches (необязательно)
|
||||
- если база под хранилищем конфигурации — `repository`: путь, пользователь, пароль
|
||||
|
||||
Добавь в массив `databases`. Если это первая база — установи как `default`.
|
||||
|
||||
@@ -159,3 +212,10 @@ test Тестовая server srv01/MyApp_Test
|
||||
```
|
||||
|
||||
> **Важно**: между `/N` и именем пробела нет. Между `/P` и паролем пробела нет. Если пароль пустой — опусти `/P` целиком.
|
||||
|
||||
**Хранилище конфигурации** (если у базы задан `repository`) — скрипты навыков подставляют
|
||||
сами, сопоставляя параметры соединения с записью реестра:
|
||||
```
|
||||
/ConfigurationRepositoryF"<path>" /ConfigurationRepositoryN"<user>" /ConfigurationRepositoryP"<password>"
|
||||
```
|
||||
|
||||
@@ -24,19 +24,19 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-cf/scripts/db-load-cf.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -51,6 +51,7 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" <п
|
||||
| `-Password <пароль>` | нет | Пароль |
|
||||
| `-InputFile <путь>` | да | Путь к CF-файлу |
|
||||
| `-Extension <имя>` | нет | Загрузить как расширение |
|
||||
| `-NoApplyCheck` | нет | Не проверять применимость расширения после загрузки |
|
||||
| `-AllExtensions` | нет | Загрузить все расширения из архива |
|
||||
| `-AdditionalV8Arguments <список>` | нет | Доп. аргументы запуска `1cv8.exe` через запятую, напр. `/UseHwLicenses+` |
|
||||
| `-AdditionalIbcmdArguments <список>` | нет | Доп. аргументы `ibcmd` через запятую, в форме `--ключ=значение` |
|
||||
@@ -65,11 +66,11 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" <п
|
||||
|
||||
```powershell
|
||||
# Файловая база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\config.cf"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-cf/scripts/db-load-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\config.cf"
|
||||
|
||||
# Серверная база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "config.cf"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-cf/scripts/db-load-cf.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "config.cf"
|
||||
|
||||
# Загрузка расширения
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-cf/scripts/db-load-cf.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
```
|
||||
+162
-7
@@ -1,4 +1,4 @@
|
||||
# db-load-cf v1.13 — Load 1C configuration from CF file
|
||||
# db-load-cf v1.19 — Load 1C configuration from CF file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -49,7 +49,7 @@
|
||||
.\db-load-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -InputFile "ext.cfe" -Extension "МоёРасширение"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -78,6 +78,16 @@ param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$AllExtensions,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
# Ключ для регрессов и верификации снапшотов, не для повседневного вызова: в SKILL.md
|
||||
# намеренно не выносится. Поднимает код возврата, если платформа отчиталась об успехе,
|
||||
# но расширение при этом неприменимо.
|
||||
[switch]$StrictLog,
|
||||
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$NoApplyCheck,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string[]]$AdditionalV8Arguments = @(),
|
||||
|
||||
@@ -121,6 +131,17 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
@@ -171,6 +192,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -270,8 +299,52 @@ function Assert-InfoBaseExists {
|
||||
|
||||
Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
@@ -384,6 +457,73 @@ function Write-PlatformOutput {
|
||||
}
|
||||
|
||||
|
||||
# Постусловие применимости расширения: платформа отчитывается успехом и о расширении, которое
|
||||
# не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал регистрации.
|
||||
#
|
||||
# Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной командной
|
||||
# строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча отбрасывает —
|
||||
# проверено на 8.3.24, /LoadConfigFromFiles вместе с /CheckCanApplyConfigurationExtensions
|
||||
# завершились кодом 0 с пустым логом, и загрузка не состоялась.
|
||||
#
|
||||
# Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний исполняемый файл.
|
||||
function Invoke-ApplyCheck {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$exeDir = Split-Path $Exe -Parent
|
||||
$exeLeaf = Split-Path $Exe -Leaf
|
||||
$v8 = if ($exeLeaf -match '^ibcmd') { Join-Path $exeDir ("1cv8" + [System.IO.Path]::GetExtension($Exe)) } else { $Exe }
|
||||
if (-not (Test-Path $v8)) { return @{ Skipped = $true; Reason = "1cv8 not found at $v8"; ExitCode = 0; Lines = @() } }
|
||||
$dir = Join-Path $env:TEMP "apply_check_$(Get-Random)"
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
try {
|
||||
$a = @("DESIGNER") + $ConnArgs + @("/CheckCanApplyConfigurationExtensions")
|
||||
if ($Extension) { $a += "-Extension", "`"$Extension`"" }
|
||||
$outFile = Join-Path $dir "check_log.txt"
|
||||
$a += "/Out", "`"$outFile`"", "/DisableStartupDialogs"
|
||||
$a += $ExtraArgs
|
||||
$res = Invoke-PlatformProcess $v8 $a -PreQuoted
|
||||
$lines = @()
|
||||
if (Test-Path $outFile) {
|
||||
$raw = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||
if ($raw) { $lines = @($raw -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) }
|
||||
}
|
||||
return @{ Skipped = $false; Reason = ''; ExitCode = $res.ExitCode; Lines = $lines }
|
||||
} finally {
|
||||
if (Test-Path $dir) { Remove-Item -Path $dir -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
# Проверить и напечатать. $true, если платформа расширение не применит — вызывающий решает,
|
||||
# поднимать ли код возврата (строгий режим).
|
||||
function Invoke-ApplyCheckReport {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$ac = Invoke-ApplyCheck $Exe $ConnArgs $Extension $ExtraArgs
|
||||
if ($ac.Skipped) {
|
||||
Write-Host "[note] applicability check skipped: $($ac.Reason)" -ForegroundColor Yellow
|
||||
return $false
|
||||
}
|
||||
if ($ac.ExitCode -ne 0 -or $ac.Lines.Count -gt 0) {
|
||||
Write-Host "[warning] the extension is loaded, but the platform will not apply it:" -ForegroundColor Yellow
|
||||
foreach ($l in $ac.Lines) { Write-Host " $l" -ForegroundColor Yellow }
|
||||
return $true
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# Проверять ли применимость: -NoApplyCheck сильнее настройки проекта.
|
||||
function Get-ApplyCheckEnabled {
|
||||
param([switch]$Disabled)
|
||||
if ($Disabled) { return $false }
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if ($pf) {
|
||||
try {
|
||||
$proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if ($null -ne $proj.extensionApplyCheck) { return [bool]$proj.extensionApplyCheck }
|
||||
} catch {}
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
|
||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -434,22 +574,32 @@ try {
|
||||
} else {
|
||||
Write-Host "Error loading configuration (code: $exitCode)$(Get-ExitAnnotation $exitCode)" -ForegroundColor Red
|
||||
}
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
$acConn = @("/F", "`"$InfoBasePath`"")
|
||||
if ($UserName) { $acConn += "/N`"$UserName`"" }
|
||||
if ($Password) { $acConn += "/P`"$Password`"" }
|
||||
if ((Invoke-ApplyCheckReport $V8Path $acConn $Extension @()) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
Write-PlatformOutput $output
|
||||
exit $exitCode
|
||||
}
|
||||
|
||||
# --- 1cv8 branch ---
|
||||
# --- Build arguments ---
|
||||
$arguments = @("DESIGNER")
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт запуск проверки применимости.
|
||||
$connArgs = @()
|
||||
|
||||
if ($InfoBaseServer -and $InfoBaseRef) {
|
||||
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
$connArgs += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
} else {
|
||||
$arguments += "/F", "`"$InfoBasePath`""
|
||||
$connArgs += "/F", "`"$InfoBasePath`""
|
||||
}
|
||||
|
||||
if ($UserName) { $arguments += "/N`"$UserName`"" }
|
||||
if ($Password) { $arguments += "/P`"$Password`"" }
|
||||
if ($UserName) { $connArgs += "/N`"$UserName`"" }
|
||||
if ($Password) { $connArgs += "/P`"$Password`"" }
|
||||
|
||||
$arguments = @("DESIGNER") + $connArgs
|
||||
|
||||
$arguments += "/LoadCfg", "`"$InputFile`""
|
||||
|
||||
@@ -488,6 +638,11 @@ try {
|
||||
}
|
||||
Write-PlatformOutput $__v8.Output
|
||||
|
||||
# Расширение могло загрузиться «успешно» и остаться неприменимым — спрашиваем платформу.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
if ((Invoke-ApplyCheckReport $V8Path $connArgs $Extension $extraArgs) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
|
||||
} finally {
|
||||
+237
-28
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-load-cf v1.13 — Load 1C configuration from CF file
|
||||
# db-load-cf v1.19 — Load 1C configuration from CF file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,71 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,6 +107,17 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
@@ -98,15 +171,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +253,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +283,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +300,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +338,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +355,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +374,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -322,6 +419,91 @@ def print_platform_output(result):
|
||||
print("--- End ---")
|
||||
|
||||
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
|
||||
def run_apply_check(exe, conn_args, extension, extra_args):
|
||||
"""Постусловие применимости расширения: платформа отчитывается успехом и о расширении,
|
||||
которое не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал
|
||||
регистрации.
|
||||
|
||||
Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной
|
||||
командной строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча
|
||||
отбрасывает — проверено на 8.3.24, /LoadConfigFromFiles вместе с
|
||||
/CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка не
|
||||
состоялась.
|
||||
|
||||
Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний файл.
|
||||
"""
|
||||
exe_dir = os.path.dirname(exe)
|
||||
leaf = os.path.basename(exe)
|
||||
if leaf.lower().startswith("ibcmd"):
|
||||
v8 = os.path.join(exe_dir, "1cv8" + os.path.splitext(leaf)[1])
|
||||
else:
|
||||
v8 = exe
|
||||
if not os.path.isfile(v8):
|
||||
return {"skipped": True, "reason": f"1cv8 not found at {v8}", "exit": 0, "lines": []}
|
||||
temp_dir = tempfile.mkdtemp(prefix="apply_check_")
|
||||
try:
|
||||
a = ["DESIGNER"] + list(conn_args) + ["/CheckCanApplyConfigurationExtensions"]
|
||||
if extension:
|
||||
a += ["-Extension", f'"{extension}"']
|
||||
out_file = os.path.join(temp_dir, "check_log.txt")
|
||||
a += ["/Out", f'"{out_file}"', "/DisableStartupDialogs"]
|
||||
a += list(extra_args)
|
||||
r = run_v8(v8, a)
|
||||
lines = []
|
||||
if os.path.isfile(out_file):
|
||||
with open(out_file, encoding="utf-8-sig", errors="replace") as f:
|
||||
lines = [x.strip() for x in f.read().splitlines() if x.strip()]
|
||||
return {"skipped": False, "reason": "", "exit": r.returncode, "lines": lines}
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def apply_check_report(exe, conn_args, extension, extra_args):
|
||||
"""Проверить и напечатать. True, если платформа расширение не применит — вызывающий решает,
|
||||
поднимать ли код возврата (строгий режим)."""
|
||||
ac = run_apply_check(exe, conn_args, extension, extra_args)
|
||||
if ac["skipped"]:
|
||||
print(f"[note] applicability check skipped: {ac['reason']}")
|
||||
return False
|
||||
if ac["exit"] != 0 or ac["lines"]:
|
||||
print("[warning] the extension is loaded, but the platform will not apply it:")
|
||||
for line in ac["lines"]:
|
||||
print(f" {line}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def apply_check_enabled(disabled):
|
||||
"""Проверять ли применимость: -NoApplyCheck сильнее настройки проекта."""
|
||||
if disabled:
|
||||
return False
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if pf:
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
if proj.get("extensionApplyCheck") is not None:
|
||||
return bool(proj.get("extensionApplyCheck"))
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
"""Run an ibcmd command non-interactively.
|
||||
|
||||
@@ -330,7 +512,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -387,20 +569,26 @@ def main():
|
||||
parser.add_argument("-InputFile", required=True)
|
||||
parser.add_argument("-Extension", default="")
|
||||
parser.add_argument("-AllExtensions", action="store_true")
|
||||
# Ключ для регрессов и верификации снапшотов, не для повседневного вызова: в SKILL.md
|
||||
# намеренно не выносится. Поднимает код возврата, если платформа отчиталась об успехе,
|
||||
# но расширение при этом неприменимо.
|
||||
parser.add_argument("-StrictLog", action="store_true")
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
parser.add_argument("-NoApplyCheck", action="store_true")
|
||||
parser.add_argument("-AdditionalV8Arguments", nargs="*", default=[],
|
||||
help="Extra 1cv8 arguments, e.g. /UseHwLicenses+")
|
||||
parser.add_argument("-AdditionalIbcmdArguments", nargs="*", default=[],
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
assert_infobase_exists(args.InfoBasePath)
|
||||
args.InputFile = clean_path(args.InputFile, "-InputFile")
|
||||
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -418,21 +606,21 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate input file ---
|
||||
if not os.path.isfile(args.InputFile):
|
||||
print(f"Error: input file not found: {args.InputFile}", file=sys.stderr)
|
||||
print(f"Error: input file not found: {args.InputFile}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- ibcmd branch (file infobase only) ---
|
||||
if engine == "ibcmd":
|
||||
if args.AllExtensions:
|
||||
print("Error: ibcmd config load does not support -AllExtensions (use -Extension)", file=sys.stderr)
|
||||
print("Error: ibcmd config load does not support -AllExtensions (use -Extension)")
|
||||
sys.exit(1)
|
||||
arguments = ["infobase", "config", "load", f"--db-path={args.InfoBasePath}"]
|
||||
if args.Extension:
|
||||
@@ -451,7 +639,19 @@ def main():
|
||||
if result.returncode == 0:
|
||||
print(f"Configuration loaded successfully from: {args.InputFile}")
|
||||
else:
|
||||
print(f"Error loading configuration (code: {result.returncode}){describe_exit(result.returncode)}", file=sys.stderr)
|
||||
print(f"Error loading configuration (code: {result.returncode}){describe_exit(result.returncode)}")
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
exit_code = result.returncode
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
ac_conn = ["/F", f'"{args.InfoBasePath}"']
|
||||
if args.UserName:
|
||||
ac_conn.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
ac_conn.append(f'/P"{args.Password}"')
|
||||
if apply_check_report(v8path, ac_conn, args.Extension, []) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
sys.exit(result.returncode)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -460,17 +660,20 @@ def main():
|
||||
|
||||
try:
|
||||
# --- Build arguments ---
|
||||
arguments = ["DESIGNER"]
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт проверка применимости.
|
||||
conn_args = []
|
||||
|
||||
if args.InfoBaseServer and args.InfoBaseRef:
|
||||
arguments.extend(["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"'])
|
||||
conn_args.extend(["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"'])
|
||||
else:
|
||||
arguments.extend(["/F", f'"{args.InfoBasePath}"'])
|
||||
conn_args.extend(["/F", f'"{args.InfoBasePath}"'])
|
||||
|
||||
if args.UserName:
|
||||
arguments.append(f'/N"{args.UserName}"')
|
||||
conn_args.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
arguments.append(f'/P"{args.Password}"')
|
||||
conn_args.append(f'/P"{args.Password}"')
|
||||
|
||||
arguments = ["DESIGNER"] + conn_args
|
||||
|
||||
arguments.extend(["/LoadCfg", f'"{args.InputFile}"'])
|
||||
|
||||
@@ -495,7 +698,7 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Configuration loaded successfully from: {args.InputFile}")
|
||||
else:
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -508,6 +711,12 @@ def main():
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Расширение могло загрузиться «успешно» и остаться неприменимым — спрашиваем платформу.
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
if apply_check_report(v8path, conn_args, args.Extension, extra_args) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
print_platform_output(result)
|
||||
sys.exit(exit_code)
|
||||
|
||||
@@ -40,19 +40,19 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-dt.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-dt/scripts/db-load-dt.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -82,10 +82,10 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-dt.ps1" <п
|
||||
|
||||
```powershell
|
||||
# Файловая база
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\base.dt"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-dt/scripts/db-load-dt.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\base.dt"
|
||||
|
||||
# Серверная база с ускорением загрузки
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "base.dt" -JobsCount 4
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-dt/scripts/db-load-dt.ps1" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "base.dt" -JobsCount 4
|
||||
```
|
||||
|
||||
## Связанные навыки
|
||||
+65
-2
@@ -1,4 +1,4 @@
|
||||
# db-load-dt v1.12 — Load 1C information base from DT file
|
||||
# db-load-dt v1.17 — Load 1C information base from DT file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -46,7 +46,7 @@
|
||||
.\db-load-dt.ps1 -InfoBasePath "C:\Bases\MyDB" -InputFile "backup.dt"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -118,6 +118,17 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
@@ -168,6 +179,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -267,8 +286,52 @@ function Assert-InfoBaseExists {
|
||||
|
||||
Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
+133
-22
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-load-dt v1.12 — Load 1C information base from DT file
|
||||
# db-load-dt v1.17 — Load 1C information base from DT file
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,85 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,6 +121,17 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
@@ -98,15 +185,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +267,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +297,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +314,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +352,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +369,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +388,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -330,7 +441,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -393,14 +504,14 @@ def main():
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
assert_infobase_exists(args.InfoBasePath)
|
||||
args.InputFile = clean_path(args.InputFile, "-InputFile")
|
||||
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -418,15 +529,15 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate input file ---
|
||||
if not os.path.isfile(args.InputFile):
|
||||
print(f"Error: input file not found: {args.InputFile}", file=sys.stderr)
|
||||
print(f"Error: input file not found: {args.InputFile}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- ibcmd branch (file infobase only) ---
|
||||
@@ -448,7 +559,7 @@ def main():
|
||||
if result.returncode == 0:
|
||||
print(f"Information base restored successfully from: {args.InputFile}")
|
||||
else:
|
||||
print(f"Error restoring information base (code: {result.returncode}){describe_exit(result.returncode)}", file=sys.stderr)
|
||||
print(f"Error restoring information base (code: {result.returncode}){describe_exit(result.returncode)}")
|
||||
sys.exit(result.returncode)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -490,7 +601,7 @@ def main():
|
||||
if exit_code == 0:
|
||||
print(f"Information base restored successfully from: {args.InputFile}")
|
||||
else:
|
||||
print(f"Error restoring information base (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error restoring information base (code: {exit_code}){describe_exit(exit_code)}")
|
||||
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
@@ -25,12 +25,12 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
Если в записи базы указан `configSrc` — используй как каталог конфигурации.
|
||||
@@ -38,7 +38,7 @@ allowed-tools:
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-git.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-git/scripts/db-load-git.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -55,6 +55,7 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-git.ps1" <
|
||||
| `-Source <источник>` | нет | `All` (по умолч.) / `Staged` / `Unstaged` / `Commit` |
|
||||
| `-CommitRange <range>` | для Commit | Диапазон коммитов (напр. `HEAD~3..HEAD`) |
|
||||
| `-Extension <имя>` | нет | Загрузить в расширение |
|
||||
| `-NoApplyCheck` | нет | Не проверять применимость расширения после загрузки |
|
||||
| `-AllExtensions` | нет | Загрузить все расширения |
|
||||
| `-Format <формат>` | нет | `Hierarchical` (по умолч.) / `Plain` |
|
||||
| `-DryRun` | нет | Только показать что будет загружено (без загрузки) |
|
||||
@@ -72,8 +73,8 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-git.ps1" <
|
||||
|
||||
```powershell
|
||||
# Все незафиксированные изменения
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-git.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source All -UpdateDB
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-git/scripts/db-load-git.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source All -UpdateDB
|
||||
|
||||
# Из диапазона коммитов
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-git.ps1" -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source Commit -CommitRange "HEAD~3..HEAD"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-git/scripts/db-load-git.ps1" -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source Commit -CommitRange "HEAD~3..HEAD"
|
||||
```
|
||||
+296
-10
@@ -1,4 +1,4 @@
|
||||
# db-load-git v1.18 — Load Git changes into 1C database
|
||||
# db-load-git v1.27 — Load Git changes into 1C database
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -64,7 +64,7 @@
|
||||
.\db-load-git.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -DryRun
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -110,6 +110,25 @@ param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$UpdateDB,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
# Ключ для регрессов и верификации снапшотов, не для повседневного вызова: в SKILL.md
|
||||
# намеренно не выносится. Поднимает код возврата, если платформа отчиталась об успехе,
|
||||
# но в логе есть отбраковка.
|
||||
[switch]$StrictLog,
|
||||
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$NoApplyCheck,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPath,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryUser,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPassword,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string[]]$AdditionalV8Arguments = @(),
|
||||
|
||||
@@ -120,6 +139,116 @@ param(
|
||||
$OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Resolve-RepositorySettings {
|
||||
# Возвращает @{ Path; User; Password; FromRegistry }. Явные -Repository* всегда сильнее реестра.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
$rec = $null
|
||||
if ($dbRec) {
|
||||
if ($Extension) {
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
if ($dbRec.extensions) {
|
||||
foreach ($ext in $dbRec.extensions) {
|
||||
if ($ext.name -and $ext.name.Equals($Extension, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
$rec = $ext.repository
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$rec = $dbRec.repository
|
||||
}
|
||||
}
|
||||
$path = if ($RepositoryPath) { $RepositoryPath } elseif ($rec -and $rec.path) { [string]$rec.path } else { $null }
|
||||
$user = if ($RepositoryUser) { $RepositoryUser } elseif ($rec -and $rec.user) { [string]$rec.user } else { $null }
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
$pwd = if ($RepositoryPassword) { $RepositoryPassword } elseif ($rec -and $rec.password) { [string]$rec.password } else { $null }
|
||||
return @{
|
||||
Path = if ($path) { $path.Trim().Trim('"') } else { $null }
|
||||
User = $user
|
||||
Password = $pwd
|
||||
FromRegistry = [bool]($rec -and $rec.path)
|
||||
DbRecord = $dbRec
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RepositoryArgs {
|
||||
# Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P.
|
||||
param([hashtable]$Repo)
|
||||
$a = @()
|
||||
if (-not $Repo -or -not $Repo.Path) { return $a }
|
||||
$a += "/ConfigurationRepositoryF`"$($Repo.Path)`""
|
||||
if ($Repo.User) { $a += "/ConfigurationRepositoryN`"$($Repo.User)`"" }
|
||||
if ($Repo.Password) { $a += "/ConfigurationRepositoryP`"$($Repo.Password)`"" }
|
||||
return $a
|
||||
}
|
||||
|
||||
# Сообщения платформы про хранилище конфигурации называют причину, но не действие. Действие
|
||||
# дописываем сами: без него модель упирается в отказ и не знает, чем его лечить.
|
||||
function Write-RepositoryHints {
|
||||
param([string]$LogText)
|
||||
if (-not $LogText) { return }
|
||||
if ($LogText -match 'текущая конфигурация помещена в хранилище') {
|
||||
Write-Host "[hint] полная загрузка в базу, подключённую к хранилищу, невозможна." -ForegroundColor Yellow
|
||||
Write-Host " Используйте -Mode Partial, предварительно захватив объекты: /db-repo lock" -ForegroundColor Yellow
|
||||
}
|
||||
foreach ($m in [regex]::Matches($LogText, 'объект метаданных ([^\s]+) не захвачен в хранилище')) {
|
||||
$obj = $m.Groups[1].Value
|
||||
if ($obj -eq 'Configuration') {
|
||||
Write-Host "[hint] не захвачен корень конфигурации — он нужен, чтобы добавить или удалить объект:" -ForegroundColor Yellow
|
||||
Write-Host " /db-repo lock <база> -Objects `"Конфигурация`"" -ForegroundColor Yellow
|
||||
} else {
|
||||
Write-Host "[hint] объект не захвачен в хранилище: /db-repo lock <база> -Objects `"$obj`"" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
if ($LogText -match 'Соединение с хранилищем конфигурации не установлено') {
|
||||
Write-Host "[hint] соединение с хранилищем не установлено. Две причины:" -ForegroundColor Yellow
|
||||
Write-Host " реквизиты неизвестны — добавьте `"repository`" в запись базы в .v8-project.json (см. /db-list);" -ForegroundColor Yellow
|
||||
Write-Host " либо хранилище недоступно — для сетевого проверьте сервер хранилища и порт." -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
function Protect-Secrets {
|
||||
# Redact literal secret values from a display string (String.Replace is literal, not regex).
|
||||
param([string]$Text, [string[]]$Secrets)
|
||||
@@ -136,12 +265,23 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
'--user', '--password'
|
||||
)
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP')
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP', '/ConfigurationRepositoryP')
|
||||
$script:IbcmdSecretKeys = @('--password', '--token', '--db-pwd')
|
||||
|
||||
function Test-ArgKeyMatch {
|
||||
@@ -186,6 +326,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -280,6 +428,10 @@ function Get-ObjectXmlFromSubFile {
|
||||
# --- Resolve V8Path (skip if DryRun) ---
|
||||
if (-not $DryRun) {
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
@@ -394,8 +546,110 @@ function Write-PlatformOutput {
|
||||
Write-Host "--- End ---"
|
||||
}
|
||||
|
||||
# Строки лога, о которых платформа сообщает, НЕ поднимая код возврата: метаданные отброшены или
|
||||
# конфигурация нерабочая, а операция при этом «успешна». Возвращает подошедшие строки.
|
||||
#
|
||||
# Копия этой функции есть в каждом навыке, который читает /Out-лог загрузки (навыки автономны).
|
||||
# Держать копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
function Find-SilentRejections {
|
||||
param([string]$LogText)
|
||||
$patterns = @(
|
||||
'Неверное свойство объекта метаданных',
|
||||
'не входит в состав объекта метаданных',
|
||||
'Неизвестное имя типа',
|
||||
'Неизвестный объект метаданных',
|
||||
'Ни один из документов не является регистратором для регистра',
|
||||
'Неверное значение перечисления',
|
||||
'не может быть приведен к типу',
|
||||
# Режим совместимости выше платформы: объекты в базу не попадают, отказ приходит в рантайме.
|
||||
# Обрезано до инвариантной части — конкретная версия в сообщении меняется.
|
||||
'Для работы с конфигурацией необходима версия платформы не меньше'
|
||||
)
|
||||
$found = @()
|
||||
if ($LogText) {
|
||||
foreach ($line in ($LogText -split "`r?`n")) {
|
||||
foreach ($pat in $patterns) {
|
||||
if ($line -match [regex]::Escape($pat)) {
|
||||
$found += $line.Trim()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# Возвращаем массив БЕЗ запятой-обёртки: вызывающий берёт результат в @(), а `return ,$found`
|
||||
# дал бы массив из одного пустого массива — фантомное срабатывание на чистом логе.
|
||||
return $found
|
||||
}
|
||||
|
||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
||||
|
||||
# Постусловие применимости расширения: платформа отчитывается успехом и о расширении, которое
|
||||
# не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал регистрации.
|
||||
#
|
||||
# Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной командной
|
||||
# строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча отбрасывает —
|
||||
# проверено на 8.3.24, /LoadConfigFromFiles вместе с /CheckCanApplyConfigurationExtensions
|
||||
# завершились кодом 0 с пустым логом, и загрузка не состоялась.
|
||||
#
|
||||
# Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний исполняемый файл.
|
||||
function Invoke-ApplyCheck {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$exeDir = Split-Path $Exe -Parent
|
||||
$exeLeaf = Split-Path $Exe -Leaf
|
||||
$v8 = if ($exeLeaf -match '^ibcmd') { Join-Path $exeDir ("1cv8" + [System.IO.Path]::GetExtension($Exe)) } else { $Exe }
|
||||
if (-not (Test-Path $v8)) { return @{ Skipped = $true; Reason = "1cv8 not found at $v8"; ExitCode = 0; Lines = @() } }
|
||||
$dir = Join-Path $env:TEMP "apply_check_$(Get-Random)"
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
try {
|
||||
$a = @("DESIGNER") + $ConnArgs + @("/CheckCanApplyConfigurationExtensions")
|
||||
if ($Extension) { $a += "-Extension", "`"$Extension`"" }
|
||||
$outFile = Join-Path $dir "check_log.txt"
|
||||
$a += "/Out", "`"$outFile`"", "/DisableStartupDialogs"
|
||||
$a += $ExtraArgs
|
||||
$res = Invoke-PlatformProcess $v8 $a -PreQuoted
|
||||
$lines = @()
|
||||
if (Test-Path $outFile) {
|
||||
$raw = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||
if ($raw) { $lines = @($raw -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) }
|
||||
}
|
||||
return @{ Skipped = $false; Reason = ''; ExitCode = $res.ExitCode; Lines = $lines }
|
||||
} finally {
|
||||
if (Test-Path $dir) { Remove-Item -Path $dir -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
# Проверить и напечатать. $true, если платформа расширение не применит — вызывающий решает,
|
||||
# поднимать ли код возврата (строгий режим).
|
||||
function Invoke-ApplyCheckReport {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$ac = Invoke-ApplyCheck $Exe $ConnArgs $Extension $ExtraArgs
|
||||
if ($ac.Skipped) {
|
||||
Write-Host "[note] applicability check skipped: $($ac.Reason)" -ForegroundColor Yellow
|
||||
return $false
|
||||
}
|
||||
if ($ac.ExitCode -ne 0 -or $ac.Lines.Count -gt 0) {
|
||||
Write-Host "[warning] the extension is loaded, but the platform will not apply it:" -ForegroundColor Yellow
|
||||
foreach ($l in $ac.Lines) { Write-Host " $l" -ForegroundColor Yellow }
|
||||
return $true
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# Проверять ли применимость: -NoApplyCheck сильнее настройки проекта.
|
||||
function Get-ApplyCheckEnabled {
|
||||
param([switch]$Disabled)
|
||||
if ($Disabled) { return $false }
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if ($pf) {
|
||||
try {
|
||||
$proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if ($null -ne $proj.extensionApplyCheck) { return [bool]$proj.extensionApplyCheck }
|
||||
} catch {}
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
|
||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
||||
if ($engine -eq "ibcmd") {
|
||||
if (-not $InfoBasePath) {
|
||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
||||
@@ -604,6 +858,13 @@ try {
|
||||
} else {
|
||||
Write-Host "Error updating database configuration (code: $exitCode)$(Get-ExitAnnotation $exitCode)" -ForegroundColor Red
|
||||
}
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
$acConn = @("/F", "`"$InfoBasePath`"")
|
||||
if ($UserName) { $acConn += "/N`"$UserName`"" }
|
||||
if ($Password) { $acConn += "/P`"$Password`"" }
|
||||
if ((Invoke-ApplyCheckReport $V8Path $acConn $Extension @()) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
Write-PlatformOutput $applyOut
|
||||
}
|
||||
exit $exitCode
|
||||
@@ -616,16 +877,24 @@ try {
|
||||
[System.IO.File]::WriteAllLines($listFile, $configFiles, $utf8Bom)
|
||||
|
||||
# --- Build arguments ---
|
||||
$arguments = @("DESIGNER")
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт запуск проверки применимости.
|
||||
$connArgs = @()
|
||||
|
||||
if ($InfoBaseServer -and $InfoBaseRef) {
|
||||
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
$connArgs += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
} else {
|
||||
$arguments += "/F", "`"$InfoBasePath`""
|
||||
$connArgs += "/F", "`"$InfoBasePath`""
|
||||
}
|
||||
|
||||
if ($UserName) { $arguments += "/N`"$UserName`"" }
|
||||
if ($Password) { $arguments += "/P`"$Password`"" }
|
||||
if ($UserName) { $connArgs += "/N`"$UserName`"" }
|
||||
if ($Password) { $connArgs += "/P`"$Password`"" }
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
$__repo = Resolve-RepositorySettings
|
||||
$connArgs += Get-RepositoryArgs $__repo
|
||||
|
||||
$arguments = @("DESIGNER") + $connArgs
|
||||
|
||||
$arguments += "/LoadConfigFromFiles", "`"$ConfigDir`""
|
||||
$arguments += "-listFile", "`"$listFile`""
|
||||
@@ -654,7 +923,7 @@ try {
|
||||
# --- Execute ---
|
||||
Write-Host ""
|
||||
Write-Host "Executing partial configuration load..."
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName))"
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName, $__repo.Password))"
|
||||
|
||||
$__v8 = Invoke-PlatformProcess $V8Path $arguments -PreQuoted
|
||||
$exitCode = $__v8.ExitCode
|
||||
@@ -667,6 +936,7 @@ try {
|
||||
Write-Host "Error loading configuration (code: $exitCode)$(Get-ExitAnnotation $exitCode)" -ForegroundColor Red
|
||||
}
|
||||
|
||||
$logContent = $null
|
||||
if (Test-Path $outFile) {
|
||||
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||
if ($logContent) {
|
||||
@@ -676,6 +946,22 @@ try {
|
||||
}
|
||||
}
|
||||
Write-PlatformOutput $__v8.Output
|
||||
Write-RepositoryHints $logContent
|
||||
|
||||
# Причину не называем: строки лога печатаются следом и говорят за себя, а класс проблемы
|
||||
# разный — от отброшенного свойства до нерабочей на этой платформе конфигурации. Подсказку
|
||||
# про -StrictLog не даём: операция уже выполнена, повторять её ради того же текста незачем.
|
||||
$silentFailures = @(Find-SilentRejections $logContent)
|
||||
if ($silentFailures.Count -gt 0) {
|
||||
Write-Host "[warning] platform reported success, but the log contains $($silentFailures.Count) problem(s):" -ForegroundColor Yellow
|
||||
foreach ($f in $silentFailures) { Write-Host " $f" -ForegroundColor Yellow }
|
||||
if ($StrictLog -and $exitCode -eq 0) { $exitCode = 1 }
|
||||
}
|
||||
|
||||
# Расширение могло загрузиться «успешно» и остаться неприменимым — спрашиваем платформу.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
if ((Invoke-ApplyCheckReport $V8Path $connArgs $Extension $extraArgs) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
|
||||
+361
-37
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-load-git v1.18 — Load Git changes into 1C database
|
||||
# db-load-git v1.27 — Load Git changes into 1C database
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,38 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,15 +74,133 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
"--user", "--password",
|
||||
]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP"]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP", "/ConfigurationRepositoryP"]
|
||||
IBCMD_SECRET_KEYS = ["--password", "--token", "--db-pwd"]
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def resolve_repository_settings(args):
|
||||
"""Возвращает dict path/user/password/from_registry. Явные -Repository* сильнее реестра."""
|
||||
db_rec = find_project_database(args)
|
||||
rec = None
|
||||
if db_rec:
|
||||
if args.Extension:
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
for ext in db_rec.get("extensions") or []:
|
||||
if (ext.get("name") or "").lower() == args.Extension.lower():
|
||||
rec = ext.get("repository")
|
||||
break
|
||||
else:
|
||||
rec = db_rec.get("repository")
|
||||
path = args.RepositoryPath or ((rec or {}).get("path") or None)
|
||||
user = args.RepositoryUser or ((rec or {}).get("user") or None)
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
pwd = args.RepositoryPassword or ((rec or {}).get("password") or None)
|
||||
return {
|
||||
"path": path.strip().strip('"') if path else None,
|
||||
"user": user,
|
||||
"password": pwd,
|
||||
"from_registry": bool(rec and rec.get("path")),
|
||||
}
|
||||
|
||||
|
||||
def repository_args(repo):
|
||||
"""Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P."""
|
||||
a = []
|
||||
if not repo or not repo.get("path"):
|
||||
return a
|
||||
a.append('/ConfigurationRepositoryF"%s"' % repo["path"])
|
||||
if repo.get("user"):
|
||||
a.append('/ConfigurationRepositoryN"%s"' % repo["user"])
|
||||
if repo.get("password"):
|
||||
a.append('/ConfigurationRepositoryP"%s"' % repo["password"])
|
||||
return a
|
||||
|
||||
|
||||
# Сообщения платформы про хранилище конфигурации называют причину, но не действие. Действие
|
||||
# дописываем сами: без него модель упирается в отказ и не знает, чем его лечить.
|
||||
def write_repository_hints(log_text):
|
||||
if not log_text:
|
||||
return
|
||||
if "текущая конфигурация помещена в хранилище" in log_text:
|
||||
print("[hint] полная загрузка в базу, подключённую к хранилищу, невозможна.")
|
||||
print(" Используйте -Mode Partial, предварительно захватив объекты: /db-repo lock")
|
||||
for m in re.finditer(r"объект метаданных (\S+) не захвачен в хранилище", log_text):
|
||||
obj = m.group(1)
|
||||
if obj == "Configuration":
|
||||
print("[hint] не захвачен корень конфигурации — он нужен, чтобы добавить или удалить объект:")
|
||||
print(' /db-repo lock <база> -Objects "Конфигурация"')
|
||||
else:
|
||||
print('[hint] объект не захвачен в хранилище: /db-repo lock <база> -Objects "%s"' % obj)
|
||||
if "Соединение с хранилищем конфигурации не установлено" in log_text:
|
||||
print("[hint] соединение с хранилищем не установлено. Две причины:")
|
||||
print(' реквизиты неизвестны — добавьте "repository" в запись базы в .v8-project.json (см. /db-list);')
|
||||
print(" либо хранилище недоступно — для сетевого проверьте сервер хранилища и порт.")
|
||||
|
||||
|
||||
def arg_key_match(token, key):
|
||||
"""Token matches a key when it equals it, or starts with it and the next character
|
||||
is not a letter — catches glued /N"user" and --password=x, while keeping
|
||||
@@ -98,15 +245,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +327,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +357,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +374,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +412,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +429,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +448,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -322,6 +493,108 @@ def print_platform_output(result):
|
||||
print("--- End ---")
|
||||
|
||||
|
||||
def find_silent_rejections(log_text):
|
||||
"""Строки лога, о которых платформа сообщает, НЕ поднимая код возврата.
|
||||
|
||||
Метаданные отброшены или конфигурация нерабочая, а операция при этом «успешна».
|
||||
Возвращает подошедшие строки.
|
||||
|
||||
Копия этой функции есть в каждом навыке, который читает /Out-лог загрузки (навыки
|
||||
автономны). Держать копии одинаковыми — сознательно: разошедшиеся копии сводят на нет
|
||||
весь смысл.
|
||||
"""
|
||||
patterns = [
|
||||
"Неверное свойство объекта метаданных",
|
||||
"не входит в состав объекта метаданных",
|
||||
"Неизвестное имя типа",
|
||||
"Неизвестный объект метаданных",
|
||||
"Ни один из документов не является регистратором для регистра",
|
||||
"Неверное значение перечисления",
|
||||
"не может быть приведен к типу",
|
||||
# Режим совместимости выше платформы: объекты в базу не попадают, отказ приходит в
|
||||
# рантайме. Обрезано до инвариантной части — конкретная версия в сообщении меняется.
|
||||
"Для работы с конфигурацией необходима версия платформы не меньше",
|
||||
]
|
||||
found = []
|
||||
if log_text:
|
||||
for line in log_text.splitlines():
|
||||
for pat in patterns:
|
||||
if pat in line:
|
||||
found.append(line.strip())
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def run_apply_check(exe, conn_args, extension, extra_args):
|
||||
"""Постусловие применимости расширения: платформа отчитывается успехом и о расширении,
|
||||
которое не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал
|
||||
регистрации.
|
||||
|
||||
Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной
|
||||
командной строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча
|
||||
отбрасывает — проверено на 8.3.24, /LoadConfigFromFiles вместе с
|
||||
/CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка не
|
||||
состоялась.
|
||||
|
||||
Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний файл.
|
||||
"""
|
||||
exe_dir = os.path.dirname(exe)
|
||||
leaf = os.path.basename(exe)
|
||||
if leaf.lower().startswith("ibcmd"):
|
||||
v8 = os.path.join(exe_dir, "1cv8" + os.path.splitext(leaf)[1])
|
||||
else:
|
||||
v8 = exe
|
||||
if not os.path.isfile(v8):
|
||||
return {"skipped": True, "reason": f"1cv8 not found at {v8}", "exit": 0, "lines": []}
|
||||
temp_dir = tempfile.mkdtemp(prefix="apply_check_")
|
||||
try:
|
||||
a = ["DESIGNER"] + list(conn_args) + ["/CheckCanApplyConfigurationExtensions"]
|
||||
if extension:
|
||||
a += ["-Extension", f'"{extension}"']
|
||||
out_file = os.path.join(temp_dir, "check_log.txt")
|
||||
a += ["/Out", f'"{out_file}"', "/DisableStartupDialogs"]
|
||||
a += list(extra_args)
|
||||
r = run_v8(v8, a)
|
||||
lines = []
|
||||
if os.path.isfile(out_file):
|
||||
with open(out_file, encoding="utf-8-sig", errors="replace") as f:
|
||||
lines = [x.strip() for x in f.read().splitlines() if x.strip()]
|
||||
return {"skipped": False, "reason": "", "exit": r.returncode, "lines": lines}
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def apply_check_report(exe, conn_args, extension, extra_args):
|
||||
"""Проверить и напечатать. True, если платформа расширение не применит — вызывающий решает,
|
||||
поднимать ли код возврата (строгий режим)."""
|
||||
ac = run_apply_check(exe, conn_args, extension, extra_args)
|
||||
if ac["skipped"]:
|
||||
print(f"[note] applicability check skipped: {ac['reason']}")
|
||||
return False
|
||||
if ac["exit"] != 0 or ac["lines"]:
|
||||
print("[warning] the extension is loaded, but the platform will not apply it:")
|
||||
for line in ac["lines"]:
|
||||
print(f" {line}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def apply_check_enabled(disabled):
|
||||
"""Проверять ли применимость: -NoApplyCheck сильнее настройки проекта."""
|
||||
if disabled:
|
||||
return False
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if pf:
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
if proj.get("extensionApplyCheck") is not None:
|
||||
return bool(proj.get("extensionApplyCheck"))
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
"""Run an ibcmd command non-interactively.
|
||||
|
||||
@@ -330,7 +603,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -406,6 +679,9 @@ def main():
|
||||
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
|
||||
parser.add_argument("-UserName", default="", help="1C user name")
|
||||
parser.add_argument("-Password", default="", help="1C user password")
|
||||
parser.add_argument("-RepositoryPath", default="")
|
||||
parser.add_argument("-RepositoryUser", default="")
|
||||
parser.add_argument("-RepositoryPassword", default="")
|
||||
parser.add_argument("-ConfigDir", required=True, help="Directory with XML configuration (git repo)")
|
||||
parser.add_argument(
|
||||
"-Source",
|
||||
@@ -424,13 +700,19 @@ def main():
|
||||
)
|
||||
parser.add_argument("-DryRun", action="store_true", help="Only show what would be loaded (no actual load)")
|
||||
parser.add_argument("-UpdateDB", action="store_true", help="Also update database configuration after load")
|
||||
# Ключ для регрессов и верификации снапшотов, не для повседневного вызова: в SKILL.md
|
||||
# намеренно не выносится. Поднимает код возврата, если платформа отчиталась об успехе,
|
||||
# но в логе есть отбраковка.
|
||||
parser.add_argument("-StrictLog", action="store_true")
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
parser.add_argument("-NoApplyCheck", action="store_true")
|
||||
parser.add_argument("-AdditionalV8Arguments", nargs="*", default=[],
|
||||
help="Extra 1cv8 arguments, e.g. /UseHwLicenses+")
|
||||
parser.add_argument("-AdditionalIbcmdArguments", nargs="*", default=[],
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
@@ -440,7 +722,7 @@ def main():
|
||||
# --- Resolve V8Path (skip if DryRun) ---
|
||||
v8path = None
|
||||
if not args.DryRun:
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
|
||||
# --- Detect engine + validate connection (skip if DryRun) ---
|
||||
engine = "1cv8"
|
||||
@@ -448,10 +730,10 @@ def main():
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Resolve additional arguments for the selected engine ---
|
||||
@@ -468,19 +750,19 @@ def main():
|
||||
|
||||
# --- Validate config dir ---
|
||||
if not os.path.exists(args.ConfigDir):
|
||||
print(f"Error: config directory not found: {args.ConfigDir}", file=sys.stderr)
|
||||
print(f"Error: config directory not found: {args.ConfigDir}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate Commit mode ---
|
||||
if args.Source == "Commit" and not args.CommitRange:
|
||||
print("Error: -CommitRange required for Source=Commit", file=sys.stderr)
|
||||
print("Error: -CommitRange required for Source=Commit")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Check git ---
|
||||
try:
|
||||
subprocess.run(["git", "--version"], capture_output=True, text=True, check=True)
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
print("Error: git not found in PATH", file=sys.stderr)
|
||||
print("Error: git not found in PATH")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Get changed files from Git ---
|
||||
@@ -559,10 +841,10 @@ def main():
|
||||
config_files.append(rel_path)
|
||||
|
||||
if support_skipped:
|
||||
print("[ВНИМАНИЕ] Состояние поддержки изменено в коммите, но частично не загружается (исключено):", file=sys.stderr)
|
||||
print("[ВНИМАНИЕ] Состояние поддержки изменено в коммите, но частично не загружается (исключено):")
|
||||
for sf in support_skipped:
|
||||
print(f" - {sf}", file=sys.stderr)
|
||||
print(" Смена состояния поддержки применяется только полной загрузкой (db-load-xml -Mode Full).", file=sys.stderr)
|
||||
print(f" - {sf}")
|
||||
print(" Смена состояния поддержки применяется только полной загрузкой (db-load-xml -Mode Full).")
|
||||
|
||||
if len(config_files) == 0:
|
||||
print("No configuration files found in changes")
|
||||
@@ -586,10 +868,10 @@ def main():
|
||||
if engine == "ibcmd":
|
||||
# --- ibcmd branch (file infobase only; import specific files) ---
|
||||
if args.Format == "Plain":
|
||||
print("Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
|
||||
print("Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)")
|
||||
sys.exit(1)
|
||||
if args.AllExtensions:
|
||||
print("Error: ibcmd config import does not support -AllExtensions (use -Extension or 1cv8)", file=sys.stderr)
|
||||
print("Error: ibcmd config import does not support -AllExtensions (use -Extension or 1cv8)")
|
||||
sys.exit(1)
|
||||
arguments = ["infobase", "config", "import", "files"] + config_files
|
||||
arguments += [f"--base-dir={args.ConfigDir}", f"--db-path={args.InfoBasePath}"]
|
||||
@@ -606,7 +888,7 @@ def main():
|
||||
print(f"Running: ibcmd {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName)}")
|
||||
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
|
||||
if result.returncode != 0:
|
||||
print(f"Error loading changes (code: {result.returncode}){describe_exit(result.returncode)}", file=sys.stderr)
|
||||
print(f"Error loading changes (code: {result.returncode}){describe_exit(result.returncode)}")
|
||||
sys.exit(result.returncode)
|
||||
print(f"Changes loaded successfully ({len(config_files)} files)")
|
||||
exit_code = 0
|
||||
@@ -624,8 +906,19 @@ def main():
|
||||
if exit_code == 0:
|
||||
print("Database configuration updated successfully")
|
||||
else:
|
||||
print(f"Error updating database configuration (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error updating database configuration (code: {exit_code}){describe_exit(exit_code)}")
|
||||
print_platform_output(ar)
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
ac_conn = ["/F", f'"{args.InfoBasePath}"']
|
||||
if args.UserName:
|
||||
ac_conn.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
ac_conn.append(f'/P"{args.Password}"')
|
||||
if apply_check_report(v8path, ac_conn, args.Extension, []) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
sys.exit(exit_code)
|
||||
|
||||
# --- Write list file (UTF-8 with BOM) ---
|
||||
@@ -634,17 +927,25 @@ def main():
|
||||
f.write("\n".join(config_files))
|
||||
|
||||
# --- Build arguments ---
|
||||
arguments = ["DESIGNER"]
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт проверка применимости.
|
||||
conn_args = []
|
||||
|
||||
if args.InfoBaseServer and args.InfoBaseRef:
|
||||
arguments += ["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"']
|
||||
conn_args += ["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"']
|
||||
else:
|
||||
arguments += ["/F", f'"{args.InfoBasePath}"']
|
||||
conn_args += ["/F", f'"{args.InfoBasePath}"']
|
||||
|
||||
if args.UserName:
|
||||
arguments.append(f'/N"{args.UserName}"')
|
||||
conn_args.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
arguments.append(f'/P"{args.Password}"')
|
||||
conn_args.append(f'/P"{args.Password}"')
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
repo = resolve_repository_settings(args)
|
||||
conn_args.extend(repository_args(repo))
|
||||
|
||||
arguments = ["DESIGNER"] + conn_args
|
||||
|
||||
arguments += ["/LoadConfigFromFiles", f'"{args.ConfigDir}"']
|
||||
arguments += ["-listFile", f'"{list_file}"']
|
||||
@@ -671,7 +972,7 @@ def main():
|
||||
# --- Execute ---
|
||||
print("")
|
||||
print("Executing partial configuration load...")
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName)}")
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName, repo['password'])}")
|
||||
|
||||
result = run_v8(v8path, arguments)
|
||||
exit_code = result.returncode
|
||||
@@ -681,8 +982,9 @@ def main():
|
||||
if exit_code == 0:
|
||||
print("Load completed successfully")
|
||||
else:
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}")
|
||||
|
||||
log_content = ""
|
||||
if os.path.isfile(out_file):
|
||||
try:
|
||||
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||
@@ -695,6 +997,28 @@ def main():
|
||||
pass
|
||||
|
||||
print_platform_output(result)
|
||||
write_repository_hints(log_content)
|
||||
|
||||
# Причину не называем: строки лога печатаются следом и говорят за себя, а класс проблемы
|
||||
# разный — от отброшенного свойства до нерабочей на этой платформе конфигурации. Подсказку
|
||||
# про -StrictLog не даём: операция уже выполнена, повторять её ради того же текста незачем.
|
||||
silent_failures = find_silent_rejections(log_content)
|
||||
if silent_failures:
|
||||
print(
|
||||
f"[warning] platform reported success, but the log contains "
|
||||
f"{len(silent_failures)} problem(s):"
|
||||
)
|
||||
for line in silent_failures:
|
||||
print(f" {line}")
|
||||
if args.StrictLog and exit_code == 0:
|
||||
exit_code = 1
|
||||
|
||||
# Расширение могло загрузиться «успешно» и остаться неприменимым — спрашиваем платформу.
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
if apply_check_report(v8path, conn_args, args.Extension, extra_args) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
sys.exit(exit_code)
|
||||
|
||||
finally:
|
||||
@@ -25,20 +25,21 @@ allowed-tools:
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта. Возьми `v8path` (путь к платформе) и разреши базу:
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения (путь, сервер) — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
Если файла нет — предложи `/db-list add`.
|
||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||
Если в записи базы указан `configSrc` — используй как каталог загрузки по умолчанию.
|
||||
Для `-Extension` каталог берётся из `extensions[].src` записи базы, если он там указан.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" <параметры>
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-xml/scripts/db-load-xml.ps1" <параметры>
|
||||
```
|
||||
|
||||
### Параметры скрипта
|
||||
@@ -57,6 +58,7 @@ powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" <
|
||||
| `-ListFile <путь>` | для Partial | Путь к файлу со списком (альтернатива `-Files`) |
|
||||
| `-Extension <имя>` | нет | Загрузить в расширение |
|
||||
| `-AllExtensions` | нет | Загрузить все расширения |
|
||||
| `-NoApplyCheck` | нет | Не проверять применимость расширения после загрузки |
|
||||
| `-Format <формат>` | нет | `Hierarchical` (по умолч.) / `Plain` |
|
||||
| `-UpdateDB` | нет | После загрузки сразу обновить конфигурацию БД (`/UpdateDBCfg`) |
|
||||
| `-AdditionalV8Arguments <список>` | нет | Доп. аргументы запуска `1cv8.exe` через запятую, напр. `/UseHwLicenses+` |
|
||||
@@ -90,14 +92,14 @@ Documents/Заказ/Forms/ФормаДокумента.xml
|
||||
|
||||
```powershell
|
||||
# Полная загрузка
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-xml/scripts/db-load-xml.ps1" -V8Path "C:\Program Files\1cv8\8.3.25.1257\bin" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||
|
||||
# Частичная загрузка конкретных файлов
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-xml/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
|
||||
|
||||
# Загрузка расширения
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-xml/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||
|
||||
# Загрузка + обновление БД в одном запуске
|
||||
powershell.exe -NoProfile -File "${CLAUDE_SKILL_DIR}/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full -UpdateDB
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-load-xml/scripts/db-load-xml.ps1" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full -UpdateDB
|
||||
```
|
||||
+298
-37
@@ -1,4 +1,4 @@
|
||||
# db-load-xml v1.19 — Load 1C configuration from XML files
|
||||
# db-load-xml v1.29 — Load 1C configuration from XML files
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
||||
<#
|
||||
@@ -61,7 +61,7 @@
|
||||
.\db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[CmdletBinding(PositionalBinding=$false)]
|
||||
param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$V8Path,
|
||||
@@ -85,8 +85,10 @@ param(
|
||||
[string]$ConfigDir,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[ValidateSet("Full", "Partial")]
|
||||
[string]$Mode = "Full",
|
||||
# Пустое значение = режим не задан. Прежнее умолчание Full подставляется ниже, после того
|
||||
# как станет видно, перечислены ли файлы.
|
||||
[ValidateSet("", "Full", "Partial")]
|
||||
[string]$Mode = "",
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$Files,
|
||||
@@ -110,6 +112,19 @@ param(
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$StrictLog,
|
||||
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$NoApplyCheck,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPath,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryUser,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string]$RepositoryPassword,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[string[]]$AdditionalV8Arguments = @(),
|
||||
|
||||
@@ -120,6 +135,116 @@ param(
|
||||
$OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.ps1 (сопоставление по configSrc).
|
||||
function Find-V8Project([string]$startDir) {
|
||||
$d = $startDir
|
||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
||||
$pj = Join-Path $d ".v8-project.json"
|
||||
if (Test-Path $pj) { return $pj }
|
||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
||||
if ($parent -eq $d) { break }
|
||||
$d = $parent
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Test-SamePath {
|
||||
param([string]$A, [string]$B)
|
||||
if (-not $A -or -not $B) { return $false }
|
||||
try {
|
||||
$na = [System.IO.Path]::GetFullPath($A).TrimEnd('\', '/')
|
||||
$nb = [System.IO.Path]::GetFullPath($B).TrimEnd('\', '/')
|
||||
return $na.Equals($nb, [System.StringComparison]::OrdinalIgnoreCase)
|
||||
} catch { return $false }
|
||||
}
|
||||
|
||||
function Find-ProjectDatabase {
|
||||
# Запись базы в реестре, соответствующая переданному соединению. $null, если не найдена.
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if (-not $pf) { return $null }
|
||||
try { $proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json } catch { return $null }
|
||||
if (-not $proj.databases) { return $null }
|
||||
foreach ($db in $proj.databases) {
|
||||
if ($InfoBasePath -and $db.path -and (Test-SamePath $db.path $InfoBasePath)) { return $db }
|
||||
if ($InfoBaseServer -and $InfoBaseRef -and $db.server -and $db.ref) {
|
||||
if ($db.server.Equals($InfoBaseServer, [System.StringComparison]::OrdinalIgnoreCase) -and
|
||||
$db.ref.Equals($InfoBaseRef, [System.StringComparison]::OrdinalIgnoreCase)) { return $db }
|
||||
}
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Resolve-RepositorySettings {
|
||||
# Возвращает @{ Path; User; Password; FromRegistry }. Явные -Repository* всегда сильнее реестра.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
$rec = $null
|
||||
if ($dbRec) {
|
||||
if ($Extension) {
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
if ($dbRec.extensions) {
|
||||
foreach ($ext in $dbRec.extensions) {
|
||||
if ($ext.name -and $ext.name.Equals($Extension, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
$rec = $ext.repository
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$rec = $dbRec.repository
|
||||
}
|
||||
}
|
||||
$path = if ($RepositoryPath) { $RepositoryPath } elseif ($rec -and $rec.path) { [string]$rec.path } else { $null }
|
||||
$user = if ($RepositoryUser) { $RepositoryUser } elseif ($rec -and $rec.user) { [string]$rec.user } else { $null }
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
$pwd = if ($RepositoryPassword) { $RepositoryPassword } elseif ($rec -and $rec.password) { [string]$rec.password } else { $null }
|
||||
return @{
|
||||
Path = if ($path) { $path.Trim().Trim('"') } else { $null }
|
||||
User = $user
|
||||
Password = $pwd
|
||||
FromRegistry = [bool]($rec -and $rec.path)
|
||||
DbRecord = $dbRec
|
||||
}
|
||||
}
|
||||
|
||||
function Get-RepositoryArgs {
|
||||
# Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P.
|
||||
param([hashtable]$Repo)
|
||||
$a = @()
|
||||
if (-not $Repo -or -not $Repo.Path) { return $a }
|
||||
$a += "/ConfigurationRepositoryF`"$($Repo.Path)`""
|
||||
if ($Repo.User) { $a += "/ConfigurationRepositoryN`"$($Repo.User)`"" }
|
||||
if ($Repo.Password) { $a += "/ConfigurationRepositoryP`"$($Repo.Password)`"" }
|
||||
return $a
|
||||
}
|
||||
|
||||
# Сообщения платформы про хранилище конфигурации называют причину, но не действие. Действие
|
||||
# дописываем сами: без него модель упирается в отказ и не знает, чем его лечить.
|
||||
function Write-RepositoryHints {
|
||||
param([string]$LogText)
|
||||
if (-not $LogText) { return }
|
||||
if ($LogText -match 'текущая конфигурация помещена в хранилище') {
|
||||
Write-Host "[hint] полная загрузка в базу, подключённую к хранилищу, невозможна." -ForegroundColor Yellow
|
||||
Write-Host " Используйте -Mode Partial, предварительно захватив объекты: /db-repo lock" -ForegroundColor Yellow
|
||||
}
|
||||
foreach ($m in [regex]::Matches($LogText, 'объект метаданных ([^\s]+) не захвачен в хранилище')) {
|
||||
$obj = $m.Groups[1].Value
|
||||
if ($obj -eq 'Configuration') {
|
||||
Write-Host "[hint] не захвачен корень конфигурации — он нужен, чтобы добавить или удалить объект:" -ForegroundColor Yellow
|
||||
Write-Host " /db-repo lock <база> -Objects `"Конфигурация`"" -ForegroundColor Yellow
|
||||
} else {
|
||||
Write-Host "[hint] объект не захвачен в хранилище: /db-repo lock <база> -Objects `"$obj`"" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
if ($LogText -match 'Соединение с хранилищем конфигурации не установлено') {
|
||||
Write-Host "[hint] соединение с хранилищем не установлено. Две причины:" -ForegroundColor Yellow
|
||||
Write-Host " реквизиты неизвестны — добавьте `"repository`" в запись базы в .v8-project.json (см. /db-list);" -ForegroundColor Yellow
|
||||
Write-Host " либо хранилище недоступно — для сетевого проверьте сервер хранилища и порт." -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
function Protect-Secrets {
|
||||
# Redact literal secret values from a display string (String.Replace is literal, not regex).
|
||||
param([string]$Text, [string[]]$Secrets)
|
||||
@@ -153,12 +278,23 @@ $script:V8OwnedKeys = @(
|
||||
'/DumpConfigToFiles', '/LoadConfigFromFiles', '/UpdateDBCfg',
|
||||
'/DumpExternalDataProcessorOrReportToFiles', '/LoadExternalDataProcessorOrReportFromFiles'
|
||||
)
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
$script:V8BatchKeys = @(
|
||||
'/CheckConfig', '/CheckModules', '/CheckCanApplyConfigurationExtensions',
|
||||
'/DumpDBCfgList', '/DeleteCfg', '/UpdateCfg', '/CompareCfg', '/MergeCfg',
|
||||
'/ManageCfgSupport', '/RollbackCfg', '/ConvertFiles'
|
||||
)
|
||||
|
||||
$script:IbcmdOwnedKeys = @(
|
||||
'--db-path', '--data', '--out', '--file', '--load', '--restore',
|
||||
'--import', '--export', '--apply', '--force', '--create-database',
|
||||
'--user', '--password'
|
||||
)
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP')
|
||||
$script:V8SecretKeys = @('/P', '/UC', '/WSP', '/AWSP', '/ConfigurationRepositoryP')
|
||||
$script:IbcmdSecretKeys = @('--password', '--token', '--db-pwd')
|
||||
|
||||
function Test-ArgKeyMatch {
|
||||
@@ -203,6 +339,14 @@ function Assert-ExtraArgs {
|
||||
Write-Host "Error: '$tok' is a positional token — pass values as --key=value ($paramName cannot extend the ibcmd command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
if ($Engine -ne 'ibcmd') {
|
||||
foreach ($b in $script:V8BatchKeys) {
|
||||
if (Test-ArgKeyMatch $tok $b) {
|
||||
Write-Host "Error: $b is a batch command; passed via $paramName it would replace the skill's own operation (a command line runs only its last batch command)" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ($k in $owned) {
|
||||
if (Test-ArgKeyMatch $tok $k) {
|
||||
$hint = ''
|
||||
@@ -305,6 +449,10 @@ Assert-InfoBaseExists $InfoBasePath
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
function Find-ProjectV8Path {
|
||||
# v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
# платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
$dbRec = Find-ProjectDatabase
|
||||
if ($dbRec -and $dbRec.v8path) { return [string]$dbRec.v8path }
|
||||
$dir = (Get-Location).Path
|
||||
while ($dir) {
|
||||
$pf = Join-Path $dir ".v8-project.json"
|
||||
@@ -416,6 +564,108 @@ function Write-PlatformOutput {
|
||||
Write-Host "--- End ---"
|
||||
}
|
||||
|
||||
# Строки лога, о которых платформа сообщает, НЕ поднимая код возврата: метаданные отброшены или
|
||||
# конфигурация нерабочая, а операция при этом «успешна». Возвращает подошедшие строки.
|
||||
#
|
||||
# Копия этой функции есть в каждом навыке, который читает /Out-лог загрузки (навыки автономны).
|
||||
# Держать копии одинаковыми — сознательно: разошедшиеся копии сводят на нет весь смысл.
|
||||
function Find-SilentRejections {
|
||||
param([string]$LogText)
|
||||
$patterns = @(
|
||||
'Неверное свойство объекта метаданных',
|
||||
'не входит в состав объекта метаданных',
|
||||
'Неизвестное имя типа',
|
||||
'Неизвестный объект метаданных',
|
||||
'Ни один из документов не является регистратором для регистра',
|
||||
'Неверное значение перечисления',
|
||||
'не может быть приведен к типу',
|
||||
# Режим совместимости выше платформы: объекты в базу не попадают, отказ приходит в рантайме.
|
||||
# Обрезано до инвариантной части — конкретная версия в сообщении меняется.
|
||||
'Для работы с конфигурацией необходима версия платформы не меньше'
|
||||
)
|
||||
$found = @()
|
||||
if ($LogText) {
|
||||
foreach ($line in ($LogText -split "`r?`n")) {
|
||||
foreach ($pat in $patterns) {
|
||||
if ($line -match [regex]::Escape($pat)) {
|
||||
$found += $line.Trim()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
# Возвращаем массив БЕЗ запятой-обёртки: вызывающий берёт результат в @(), а `return ,$found`
|
||||
# дал бы массив из одного пустого массива — фантомное срабатывание на чистом логе.
|
||||
return $found
|
||||
}
|
||||
|
||||
|
||||
# Постусловие применимости расширения: платформа отчитывается успехом и о расширении, которое
|
||||
# не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал регистрации.
|
||||
#
|
||||
# Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной командной
|
||||
# строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча отбрасывает —
|
||||
# проверено на 8.3.24, /LoadConfigFromFiles вместе с /CheckCanApplyConfigurationExtensions
|
||||
# завершились кодом 0 с пустым логом, и загрузка не состоялась.
|
||||
#
|
||||
# Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний исполняемый файл.
|
||||
function Invoke-ApplyCheck {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$exeDir = Split-Path $Exe -Parent
|
||||
$exeLeaf = Split-Path $Exe -Leaf
|
||||
$v8 = if ($exeLeaf -match '^ibcmd') { Join-Path $exeDir ("1cv8" + [System.IO.Path]::GetExtension($Exe)) } else { $Exe }
|
||||
if (-not (Test-Path $v8)) { return @{ Skipped = $true; Reason = "1cv8 not found at $v8"; ExitCode = 0; Lines = @() } }
|
||||
$dir = Join-Path $env:TEMP "apply_check_$(Get-Random)"
|
||||
New-Item -ItemType Directory -Path $dir -Force | Out-Null
|
||||
try {
|
||||
$a = @("DESIGNER") + $ConnArgs + @("/CheckCanApplyConfigurationExtensions")
|
||||
if ($Extension) { $a += "-Extension", "`"$Extension`"" }
|
||||
$outFile = Join-Path $dir "check_log.txt"
|
||||
$a += "/Out", "`"$outFile`"", "/DisableStartupDialogs"
|
||||
$a += $ExtraArgs
|
||||
$res = Invoke-PlatformProcess $v8 $a -PreQuoted
|
||||
$lines = @()
|
||||
if (Test-Path $outFile) {
|
||||
$raw = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||
if ($raw) { $lines = @($raw -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) }
|
||||
}
|
||||
return @{ Skipped = $false; Reason = ''; ExitCode = $res.ExitCode; Lines = $lines }
|
||||
} finally {
|
||||
if (Test-Path $dir) { Remove-Item -Path $dir -Recurse -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
}
|
||||
|
||||
# Проверить и напечатать. $true, если платформа расширение не применит — вызывающий решает,
|
||||
# поднимать ли код возврата (строгий режим).
|
||||
function Invoke-ApplyCheckReport {
|
||||
param([string]$Exe, [string[]]$ConnArgs, [string]$Extension, [string[]]$ExtraArgs)
|
||||
$ac = Invoke-ApplyCheck $Exe $ConnArgs $Extension $ExtraArgs
|
||||
if ($ac.Skipped) {
|
||||
Write-Host "[note] applicability check skipped: $($ac.Reason)" -ForegroundColor Yellow
|
||||
return $false
|
||||
}
|
||||
if ($ac.ExitCode -ne 0 -or $ac.Lines.Count -gt 0) {
|
||||
Write-Host "[warning] the extension is loaded, but the platform will not apply it:" -ForegroundColor Yellow
|
||||
foreach ($l in $ac.Lines) { Write-Host " $l" -ForegroundColor Yellow }
|
||||
return $true
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
# Проверять ли применимость: -NoApplyCheck сильнее настройки проекта.
|
||||
function Get-ApplyCheckEnabled {
|
||||
param([switch]$Disabled)
|
||||
if ($Disabled) { return $false }
|
||||
$pf = Find-V8Project (Get-Location).Path
|
||||
if ($pf) {
|
||||
try {
|
||||
$proj = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
||||
if ($null -ne $proj.extensionApplyCheck) { return [bool]$proj.extensionApplyCheck }
|
||||
} catch {}
|
||||
}
|
||||
return $true
|
||||
}
|
||||
|
||||
|
||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
||||
|
||||
@@ -440,6 +690,16 @@ if (-not (Test-Path $ConfigDir)) {
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Перечислены файлы — загрузка частичная. Иначе список молча игнорировался бы, а умолчание Full
|
||||
# заменило бы всю конфигурацию базы.
|
||||
if ($Files -or $ListFile) {
|
||||
if ($Mode -eq "Full") {
|
||||
Write-Host "[note] перечислены файлы — загружаются только они; -Mode Full не применён" -ForegroundColor Yellow
|
||||
}
|
||||
$Mode = "Partial"
|
||||
}
|
||||
if (-not $Mode) { $Mode = "Full" }
|
||||
|
||||
# --- Validate Partial mode ---
|
||||
if ($Mode -eq "Partial" -and -not $Files -and -not $ListFile) {
|
||||
Write-Host "Error: -Files or -ListFile required for Partial mode" -ForegroundColor Red
|
||||
@@ -459,7 +719,7 @@ try {
|
||||
}
|
||||
if ($AllExtensions) {
|
||||
$arguments = @("infobase", "config", "import", "all-extensions", "$ConfigDir", "--db-path=$InfoBasePath")
|
||||
} elseif ($Mode -eq "Partial" -or $Files -or $ListFile) {
|
||||
} elseif ($Mode -eq "Partial") {
|
||||
# partial: import specific files (relative to ConfigDir)
|
||||
$fileList = @()
|
||||
if ($ListFile) {
|
||||
@@ -516,21 +776,36 @@ try {
|
||||
}
|
||||
Write-PlatformOutput $applyOut
|
||||
}
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
$acConn = @("/F", "`"$InfoBasePath`"")
|
||||
if ($UserName) { $acConn += "/N`"$UserName`"" }
|
||||
if ($Password) { $acConn += "/P`"$Password`"" }
|
||||
if ((Invoke-ApplyCheckReport $V8Path $acConn $Extension @()) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
exit $exitCode
|
||||
}
|
||||
|
||||
# --- 1cv8 branch ---
|
||||
# --- Build arguments ---
|
||||
$arguments = @("DESIGNER")
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт запуск проверки применимости.
|
||||
$connArgs = @()
|
||||
|
||||
if ($InfoBaseServer -and $InfoBaseRef) {
|
||||
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
$connArgs += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||
} else {
|
||||
$arguments += "/F", "`"$InfoBasePath`""
|
||||
$connArgs += "/F", "`"$InfoBasePath`""
|
||||
}
|
||||
|
||||
if ($UserName) { $arguments += "/N`"$UserName`"" }
|
||||
if ($Password) { $arguments += "/P`"$Password`"" }
|
||||
if ($UserName) { $connArgs += "/N`"$UserName`"" }
|
||||
if ($Password) { $connArgs += "/P`"$Password`"" }
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
$__repo = Resolve-RepositorySettings
|
||||
$connArgs += Get-RepositoryArgs $__repo
|
||||
|
||||
$arguments = @("DESIGNER") + $connArgs
|
||||
|
||||
$arguments += "/LoadConfigFromFiles", "`"$ConfigDir`""
|
||||
|
||||
@@ -596,7 +871,7 @@ try {
|
||||
$arguments += $extraArgs
|
||||
|
||||
# --- Execute ---
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName))"
|
||||
Write-Host "Running: 1cv8.exe $(Protect-Secrets ((Format-ArgsForDisplay $arguments $engine) -join ' ') @($Password, $UserName, $__repo.Password))"
|
||||
$__v8 = Invoke-PlatformProcess $V8Path $arguments -PreQuoted
|
||||
$exitCode = $__v8.ExitCode
|
||||
|
||||
@@ -607,28 +882,7 @@ try {
|
||||
}
|
||||
|
||||
# --- Scan log for silent rejections ---
|
||||
# Platform often writes load-time rejections into /Out but exits with code 0.
|
||||
# These patterns flag cases where metadata was dropped or rejected silently.
|
||||
$fatalLogPatterns = @(
|
||||
'Неверное свойство объекта метаданных',
|
||||
'не входит в состав объекта метаданных',
|
||||
'Неизвестное имя типа',
|
||||
'Неизвестный объект метаданных',
|
||||
'Ни один из документов не является регистратором для регистра',
|
||||
'Неверное значение перечисления',
|
||||
'не может быть приведен к типу'
|
||||
)
|
||||
$silentFailures = @()
|
||||
if ($logContent) {
|
||||
foreach ($line in ($logContent -split "`r?`n")) {
|
||||
foreach ($pat in $fatalLogPatterns) {
|
||||
if ($line -match [regex]::Escape($pat)) {
|
||||
$silentFailures += $line.Trim()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$silentFailures = @(Find-SilentRejections $logContent)
|
||||
|
||||
# --- Result ---
|
||||
# Default: mirror platform's verdict via exit code. Log content (including any
|
||||
@@ -646,15 +900,22 @@ try {
|
||||
Write-Host "--- End ---"
|
||||
}
|
||||
Write-PlatformOutput $__v8.Output
|
||||
Write-RepositoryHints $logContent
|
||||
|
||||
# Причину не называем: строки лога печатаются следом и говорят за себя, а класс проблемы
|
||||
# разный — от отброшенного свойства до нерабочей на этой платформе конфигурации. Подсказку
|
||||
# про -StrictLog не даём: загрузка уже выполнена, повторять её ради того же текста незачем.
|
||||
if ($silentFailures.Count -gt 0) {
|
||||
$msg = "[warning] log contains $($silentFailures.Count) rejection(s) — platform loaded config but dropped properties/refs"
|
||||
if (-not $StrictLog) { $msg += " (pass -StrictLog to treat as error)" }
|
||||
Write-Host $msg -ForegroundColor Yellow
|
||||
Write-Host "[warning] platform reported success, but the log contains $($silentFailures.Count) problem(s):" -ForegroundColor Yellow
|
||||
foreach ($f in $silentFailures) { Write-Host " $f" -ForegroundColor Yellow }
|
||||
if ($StrictLog -and $exitCode -eq 0) { $exitCode = 1 }
|
||||
}
|
||||
|
||||
# Расширение могло загрузиться «успешно» и при этом остаться неприменимым — спрашиваем платформу.
|
||||
if ($exitCode -eq 0 -and ($Extension -or $AllExtensions) -and (Get-ApplyCheckEnabled -Disabled:$NoApplyCheck)) {
|
||||
if ((Invoke-ApplyCheckReport $V8Path $connArgs $Extension $extraArgs) -and $StrictLog) { $exitCode = 1 }
|
||||
}
|
||||
|
||||
exit $exitCode
|
||||
|
||||
} finally {
|
||||
+364
-63
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
# db-load-xml v1.19 — Load 1C configuration from XML files
|
||||
# db-load-xml v1.29 — Load 1C configuration from XML files
|
||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||
|
||||
import argparse
|
||||
@@ -14,9 +14,38 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
# Регистронезависимый ввод — паритет с PS1: в PowerShell имена параметров и [ValidateSet]
|
||||
# регистр не различают, в argparse совпадение точное.
|
||||
def ci_parse_args(parser, argv=None):
|
||||
"""parse_args по правилам PS: имена параметров и значения choices регистронезависимы."""
|
||||
argv = list(sys.argv[1:] if argv is None else argv)
|
||||
names = {s.lower(): s for a in parser._actions for s in a.option_strings}
|
||||
for i, tok in enumerate(argv):
|
||||
if tok.startswith('-') and tok.lower() in names:
|
||||
argv[i] = names[tok.lower()]
|
||||
# choices — зеркало [ValidateSet]; канонизируем ДО разбора, иначе argparse отвергнет регистр
|
||||
choice_map = {}
|
||||
for a in parser._actions:
|
||||
if a.choices:
|
||||
for s in a.option_strings:
|
||||
choice_map[s] = {str(c).lower(): c for c in a.choices}
|
||||
for i in range(len(argv) - 1):
|
||||
m = choice_map.get(argv[i])
|
||||
if m and argv[i + 1].lower() in m:
|
||||
argv[i + 1] = m[argv[i + 1].lower()]
|
||||
return parser.parse_args(argv)
|
||||
|
||||
def _find_project_v8path():
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
||||
|
||||
|
||||
def _find_project_v8path(args):
|
||||
"""Walk up from CWD to find .v8-project.json and read its v8path.
|
||||
|
||||
v8path записи базы сильнее корневого: в одном проекте базы живут на разных версиях
|
||||
платформы, а версию формата выгрузки задаёт та платформа, которая выгружает.
|
||||
"""
|
||||
db = find_project_database(args)
|
||||
if db and db.get("v8path"):
|
||||
return db["v8path"]
|
||||
d = os.getcwd()
|
||||
while True:
|
||||
pf = os.path.join(d, ".v8-project.json")
|
||||
@@ -45,15 +74,133 @@ V8_OWNED_KEYS = [
|
||||
"/DumpConfigToFiles", "/LoadConfigFromFiles", "/UpdateDBCfg",
|
||||
"/DumpExternalDataProcessorOrReportToFiles", "/LoadExternalDataProcessorOrReportFromFiles",
|
||||
]
|
||||
# Пакетные команды платформы. В одной командной строке DESIGNER выполняет ТОЛЬКО ПОСЛЕДНЮЮ,
|
||||
# остальные молча отбрасывает (проверено на 8.3.24: /LoadConfigFromFiles вместе с
|
||||
# /CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка НЕ
|
||||
# состоялась). Такая команда в дополнительных аргументах подменяет собой операцию навыка, а навык
|
||||
# отчитывается успехом. Дополнительные аргументы — это опции, а не режимы.
|
||||
V8_BATCH_KEYS = [
|
||||
"/CheckConfig", "/CheckModules", "/CheckCanApplyConfigurationExtensions",
|
||||
"/DumpDBCfgList", "/DeleteCfg", "/UpdateCfg", "/CompareCfg", "/MergeCfg",
|
||||
"/ManageCfgSupport", "/RollbackCfg", "/ConvertFiles",
|
||||
]
|
||||
|
||||
IBCMD_OWNED_KEYS = [
|
||||
"--db-path", "--data", "--out", "--file", "--load", "--restore",
|
||||
"--import", "--export", "--apply", "--force", "--create-database",
|
||||
"--user", "--password",
|
||||
]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP"]
|
||||
V8_SECRET_KEYS = ["/P", "/UC", "/WSP", "/AWSP", "/ConfigurationRepositoryP"]
|
||||
IBCMD_SECRET_KEYS = ["--password", "--token", "--db-pwd"]
|
||||
|
||||
|
||||
# --- Запись базы в .v8-project.json ---
|
||||
# Модель не передаёт ни путь к платформе конкретной базы, ни реквизиты хранилища: скрипт
|
||||
# сопоставляет параметры соединения с записью в databases[] и берёт их оттуда. Тот же приём,
|
||||
# что в cf-edit.py (сопоставление по configSrc).
|
||||
def _sg_find_v8project(start_dir):
|
||||
d = start_dir
|
||||
for _ in range(20):
|
||||
if not d:
|
||||
break
|
||||
pj = os.path.join(d, ".v8-project.json")
|
||||
if os.path.isfile(pj):
|
||||
return pj
|
||||
parent = os.path.dirname(d)
|
||||
if parent == d:
|
||||
break
|
||||
d = parent
|
||||
return None
|
||||
|
||||
def same_path(a, b):
|
||||
if not a or not b:
|
||||
return False
|
||||
try:
|
||||
return os.path.abspath(a).rstrip("\\/").lower() == os.path.abspath(b).rstrip("\\/").lower()
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def find_project_database(args):
|
||||
"""Запись базы в реестре, соответствующая переданному соединению. None, если не найдена."""
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if not pf:
|
||||
return None
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
except Exception:
|
||||
return None
|
||||
for db in proj.get("databases") or []:
|
||||
if args.InfoBasePath and db.get("path") and same_path(db["path"], args.InfoBasePath):
|
||||
return db
|
||||
if args.InfoBaseServer and args.InfoBaseRef and db.get("server") and db.get("ref"):
|
||||
if (db["server"].lower() == args.InfoBaseServer.lower()
|
||||
and db["ref"].lower() == args.InfoBaseRef.lower()):
|
||||
return db
|
||||
return None
|
||||
|
||||
|
||||
def resolve_repository_settings(args):
|
||||
"""Возвращает dict path/user/password/from_registry. Явные -Repository* сильнее реестра."""
|
||||
db_rec = find_project_database(args)
|
||||
rec = None
|
||||
if db_rec:
|
||||
if args.Extension:
|
||||
# У расширения СВОЁ хранилище со своим путём (проверено): выбирается парой
|
||||
# /ConfigurationRepositoryF"<путь расширения>" + -Extension "<Имя>".
|
||||
for ext in db_rec.get("extensions") or []:
|
||||
if (ext.get("name") or "").lower() == args.Extension.lower():
|
||||
rec = ext.get("repository")
|
||||
break
|
||||
else:
|
||||
rec = db_rec.get("repository")
|
||||
path = args.RepositoryPath or ((rec or {}).get("path") or None)
|
||||
user = args.RepositoryUser or ((rec or {}).get("user") or None)
|
||||
# Пустой пароль = отсутствующий: 1С требует опускать ключ целиком, а не передавать пустое значение.
|
||||
pwd = args.RepositoryPassword or ((rec or {}).get("password") or None)
|
||||
return {
|
||||
"path": path.strip().strip('"') if path else None,
|
||||
"user": user,
|
||||
"password": pwd,
|
||||
"from_registry": bool(rec and rec.get("path")),
|
||||
}
|
||||
|
||||
|
||||
def repository_args(repo):
|
||||
"""Ключи доступа к хранилищу. Форма — кавычки ВНУТРИ токена, как у /N и /P."""
|
||||
a = []
|
||||
if not repo or not repo.get("path"):
|
||||
return a
|
||||
a.append('/ConfigurationRepositoryF"%s"' % repo["path"])
|
||||
if repo.get("user"):
|
||||
a.append('/ConfigurationRepositoryN"%s"' % repo["user"])
|
||||
if repo.get("password"):
|
||||
a.append('/ConfigurationRepositoryP"%s"' % repo["password"])
|
||||
return a
|
||||
|
||||
|
||||
# Сообщения платформы про хранилище конфигурации называют причину, но не действие. Действие
|
||||
# дописываем сами: без него модель упирается в отказ и не знает, чем его лечить.
|
||||
def write_repository_hints(log_text):
|
||||
if not log_text:
|
||||
return
|
||||
if "текущая конфигурация помещена в хранилище" in log_text:
|
||||
print("[hint] полная загрузка в базу, подключённую к хранилищу, невозможна.")
|
||||
print(" Используйте -Mode Partial, предварительно захватив объекты: /db-repo lock")
|
||||
for m in re.finditer(r"объект метаданных (\S+) не захвачен в хранилище", log_text):
|
||||
obj = m.group(1)
|
||||
if obj == "Configuration":
|
||||
print("[hint] не захвачен корень конфигурации — он нужен, чтобы добавить или удалить объект:")
|
||||
print(' /db-repo lock <база> -Objects "Конфигурация"')
|
||||
else:
|
||||
print('[hint] объект не захвачен в хранилище: /db-repo lock <база> -Objects "%s"' % obj)
|
||||
if "Соединение с хранилищем конфигурации не установлено" in log_text:
|
||||
print("[hint] соединение с хранилищем не установлено. Две причины:")
|
||||
print(' реквизиты неизвестны — добавьте "repository" в запись базы в .v8-project.json (см. /db-list);')
|
||||
print(" либо хранилище недоступно — для сетевого проверьте сервер хранилища и порт.")
|
||||
|
||||
|
||||
def arg_key_match(token, key):
|
||||
"""Token matches a key when it equals it, or starts with it and the next character
|
||||
is not a letter — catches glued /N"user" and --password=x, while keeping
|
||||
@@ -98,15 +245,21 @@ def assert_extra_args(extra, engine, hints):
|
||||
print(
|
||||
f"Error: '{tok}' is a positional token — pass values as --key=value "
|
||||
f"({param} cannot extend the ibcmd command)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd":
|
||||
for b in V8_BATCH_KEYS:
|
||||
if arg_key_match(tok, b):
|
||||
print(
|
||||
f"Error: {b} is a batch command; passed via {param} it would replace "
|
||||
f"the skill's own operation (a command line runs only its last batch command)",
|
||||
)
|
||||
sys.exit(1)
|
||||
for k in owned:
|
||||
if arg_key_match(tok, k):
|
||||
hint = f" (use {hints[k]})" if hints and k in hints else ""
|
||||
print(
|
||||
f"Error: {k} is controlled by the skill and cannot be passed via {param}{hint}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
@@ -174,14 +327,12 @@ def resolve_extra_args(engine, v8_extra, ibcmd_extra, hints):
|
||||
print(
|
||||
"Error: -AdditionalV8Arguments applies to 1cv8 only; the selected engine is ibcmd "
|
||||
"(use -AdditionalIbcmdArguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine != "ibcmd" and ibcmd_extra:
|
||||
print(
|
||||
"Error: -AdditionalIbcmdArguments applies to ibcmd only; the selected engine is 1cv8 "
|
||||
"(use -AdditionalV8Arguments)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if engine == "ibcmd":
|
||||
@@ -206,10 +357,10 @@ def _version_key(p):
|
||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
||||
|
||||
|
||||
def resolve_v8path(v8path):
|
||||
def resolve_v8path(v8path, args):
|
||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
||||
if not v8path:
|
||||
v8path = _find_project_v8path()
|
||||
v8path = _find_project_v8path(args)
|
||||
if not v8path:
|
||||
if os.name == "nt":
|
||||
candidates = (
|
||||
@@ -223,14 +374,14 @@ def resolve_v8path(v8path):
|
||||
v8path = max(candidates, key=_version_key)
|
||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
||||
else:
|
||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
||||
print("Error: 1C executable not found. Specify -V8Path")
|
||||
sys.exit(1)
|
||||
if os.path.isdir(v8path):
|
||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
||||
v8path = os.path.join(v8path, exe)
|
||||
if not os.path.isfile(v8path):
|
||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
||||
print(f"Error: 1C executable not found at {v8path}")
|
||||
sys.exit(1)
|
||||
return v8path
|
||||
|
||||
@@ -261,7 +412,7 @@ def assert_infobase_exists(path):
|
||||
if not path:
|
||||
return
|
||||
if not os.path.isfile(os.path.join(path, "1Cv8.1CD")):
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)", file=sys.stderr)
|
||||
print(f"Error: information base not found at {path} (no 1Cv8.1CD)")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
@@ -278,7 +429,7 @@ def clean_path(value, param=""):
|
||||
if len(v) > 3 and v[-1] in "\\/":
|
||||
v = v[:-1]
|
||||
if '"' in v:
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}", file=sys.stderr)
|
||||
print(f"Error: {param or 'path'} contains a quote character: {value}")
|
||||
sys.exit(1)
|
||||
return v
|
||||
|
||||
@@ -297,11 +448,31 @@ def run_v8(v8path, arguments):
|
||||
The arguments carry their own quotes inside the value (File="C:\\a b") — that is where
|
||||
1C's parser expects them, on Windows and on *nix alike. Windows list2cmdline would
|
||||
escape those quotes, so there the command line is handed over ready-made.
|
||||
|
||||
На POSIX аргументы уходят СПИСКОМ, и кавычки, нужные для склейки на Windows, стали бы
|
||||
частью значения: путь с пробелом платформа не находит («Неопределена информационная
|
||||
база»), многословный -comment теряет молча. Поэтому здесь снимается ОДИН слой
|
||||
обрамляющих кавычек. Склеенные ключи (/N"user", /ConfigurationRepositoryF"путь",
|
||||
File="…") не задеты: у них кавычки внутри токена, а не по краям.
|
||||
"""
|
||||
if os.name == "nt":
|
||||
cmd = '"' + v8path + '" ' + " ".join(arguments)
|
||||
else:
|
||||
cmd = [v8path] + arguments
|
||||
def strip_framing_quotes(a):
|
||||
# Кавычки, которыми мы обрамляем значения ради склейки на Windows, на POSIX
|
||||
# становятся ЧАСТЬЮ значения. Проверено на darwin: путь с пробелом отдельным
|
||||
# токеном даёт «Неопределена информационная база», а склеенный
|
||||
# /ConfigurationRepositoryF"путь с пробелом" — «завершилось с ошибкой»;
|
||||
# без кавычек обе формы работают.
|
||||
if len(a) > 1 and a[0] == '"' and a[-1] == '"':
|
||||
return a[1:-1] # "значение" отдельным токеном
|
||||
if a[0:1] == "/" and a[-1:] == '"' and '"' in a[:-1]:
|
||||
i = a.index('"')
|
||||
return a[:i] + a[i + 1:-1] # /N"имя" -> /Nимя
|
||||
return a # File="…" не трогаем: там кавычки —
|
||||
# часть синтаксиса строки соединения,
|
||||
# и с ними на POSIX всё работает
|
||||
cmd = [v8path] + [strip_framing_quotes(a) for a in arguments]
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
r.stderr = decode_platform_bytes(r.stderr)
|
||||
@@ -322,6 +493,108 @@ def print_platform_output(result):
|
||||
print("--- End ---")
|
||||
|
||||
|
||||
def find_silent_rejections(log_text):
|
||||
"""Строки лога, о которых платформа сообщает, НЕ поднимая код возврата.
|
||||
|
||||
Метаданные отброшены или конфигурация нерабочая, а операция при этом «успешна».
|
||||
Возвращает подошедшие строки.
|
||||
|
||||
Копия этой функции есть в каждом навыке, который читает /Out-лог загрузки (навыки
|
||||
автономны). Держать копии одинаковыми — сознательно: разошедшиеся копии сводят на нет
|
||||
весь смысл.
|
||||
"""
|
||||
patterns = [
|
||||
"Неверное свойство объекта метаданных",
|
||||
"не входит в состав объекта метаданных",
|
||||
"Неизвестное имя типа",
|
||||
"Неизвестный объект метаданных",
|
||||
"Ни один из документов не является регистратором для регистра",
|
||||
"Неверное значение перечисления",
|
||||
"не может быть приведен к типу",
|
||||
# Режим совместимости выше платформы: объекты в базу не попадают, отказ приходит в
|
||||
# рантайме. Обрезано до инвариантной части — конкретная версия в сообщении меняется.
|
||||
"Для работы с конфигурацией необходима версия платформы не меньше",
|
||||
]
|
||||
found = []
|
||||
if log_text:
|
||||
for line in log_text.splitlines():
|
||||
for pat in patterns:
|
||||
if pat in line:
|
||||
found.append(line.strip())
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def run_apply_check(exe, conn_args, extension, extra_args):
|
||||
"""Постусловие применимости расширения: платформа отчитывается успехом и о расширении,
|
||||
которое не применит — отказ всплывает лениво, при первом вызове метода, записью в журнал
|
||||
регистрации.
|
||||
|
||||
Запуск ОБЯЗАТЕЛЬНО отдельный. Дописать эту команду в строку операции нельзя: в одной
|
||||
командной строке DESIGNER выполняет только ПОСЛЕДНЮЮ пакетную команду, остальные молча
|
||||
отбрасывает — проверено на 8.3.24, /LoadConfigFromFiles вместе с
|
||||
/CheckCanApplyConfigurationExtensions завершились кодом 0 с пустым логом, и загрузка не
|
||||
состоялась.
|
||||
|
||||
Проверку умеет только 1cv8; если навык работал через ibcmd, берём соседний файл.
|
||||
"""
|
||||
exe_dir = os.path.dirname(exe)
|
||||
leaf = os.path.basename(exe)
|
||||
if leaf.lower().startswith("ibcmd"):
|
||||
v8 = os.path.join(exe_dir, "1cv8" + os.path.splitext(leaf)[1])
|
||||
else:
|
||||
v8 = exe
|
||||
if not os.path.isfile(v8):
|
||||
return {"skipped": True, "reason": f"1cv8 not found at {v8}", "exit": 0, "lines": []}
|
||||
temp_dir = tempfile.mkdtemp(prefix="apply_check_")
|
||||
try:
|
||||
a = ["DESIGNER"] + list(conn_args) + ["/CheckCanApplyConfigurationExtensions"]
|
||||
if extension:
|
||||
a += ["-Extension", f'"{extension}"']
|
||||
out_file = os.path.join(temp_dir, "check_log.txt")
|
||||
a += ["/Out", f'"{out_file}"', "/DisableStartupDialogs"]
|
||||
a += list(extra_args)
|
||||
r = run_v8(v8, a)
|
||||
lines = []
|
||||
if os.path.isfile(out_file):
|
||||
with open(out_file, encoding="utf-8-sig", errors="replace") as f:
|
||||
lines = [x.strip() for x in f.read().splitlines() if x.strip()]
|
||||
return {"skipped": False, "reason": "", "exit": r.returncode, "lines": lines}
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def apply_check_report(exe, conn_args, extension, extra_args):
|
||||
"""Проверить и напечатать. True, если платформа расширение не применит — вызывающий решает,
|
||||
поднимать ли код возврата (строгий режим)."""
|
||||
ac = run_apply_check(exe, conn_args, extension, extra_args)
|
||||
if ac["skipped"]:
|
||||
print(f"[note] applicability check skipped: {ac['reason']}")
|
||||
return False
|
||||
if ac["exit"] != 0 or ac["lines"]:
|
||||
print("[warning] the extension is loaded, but the platform will not apply it:")
|
||||
for line in ac["lines"]:
|
||||
print(f" {line}")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def apply_check_enabled(disabled):
|
||||
"""Проверять ли применимость: -NoApplyCheck сильнее настройки проекта."""
|
||||
if disabled:
|
||||
return False
|
||||
pf = _sg_find_v8project(os.getcwd())
|
||||
if pf:
|
||||
try:
|
||||
with open(pf, encoding="utf-8-sig") as f:
|
||||
proj = json.load(f)
|
||||
if proj.get("extensionApplyCheck") is not None:
|
||||
return bool(proj.get("extensionApplyCheck"))
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
"""Run an ibcmd command non-interactively.
|
||||
|
||||
@@ -330,7 +603,7 @@ def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
||||
that residual case is flagged via IBCMD_NOUSER_HINT (model-facing).
|
||||
"""
|
||||
if warn_no_user and os.name == "nt" and not has_username:
|
||||
sys.stderr.write(IBCMD_NOUSER_HINT)
|
||||
sys.stdout.write(IBCMD_NOUSER_HINT)
|
||||
sys.stderr.flush()
|
||||
r = subprocess.run(cmd, input=b"", capture_output=True)
|
||||
r.stdout = decode_platform_bytes(r.stdout)
|
||||
@@ -384,11 +657,14 @@ def main():
|
||||
parser.add_argument("-InfoBaseRef", default="", help="Infobase name on server")
|
||||
parser.add_argument("-UserName", default="", help="1C user name")
|
||||
parser.add_argument("-Password", default="", help="1C user password")
|
||||
parser.add_argument("-RepositoryPath", default="")
|
||||
parser.add_argument("-RepositoryUser", default="")
|
||||
parser.add_argument("-RepositoryPassword", default="")
|
||||
parser.add_argument("-ConfigDir", required=True, help="Directory with XML configuration sources")
|
||||
parser.add_argument(
|
||||
"-Mode",
|
||||
default="Full",
|
||||
choices=["Full", "Partial"],
|
||||
default="",
|
||||
choices=["", "Full", "Partial"],
|
||||
help="Load mode (default: Full)",
|
||||
)
|
||||
parser.add_argument("-Files", default="", help="Comma-separated relative file paths (for Partial mode)")
|
||||
@@ -407,13 +683,15 @@ def main():
|
||||
action="store_true",
|
||||
help="Treat silent rejection warnings in the log as errors (elevate exit code to 1)",
|
||||
)
|
||||
# Пропустить проверку применимости расширения после загрузки.
|
||||
parser.add_argument("-NoApplyCheck", action="store_true")
|
||||
parser.add_argument("-AdditionalV8Arguments", nargs="*", default=[],
|
||||
help="Extra 1cv8 arguments, e.g. /UseHwLicenses+")
|
||||
parser.add_argument("-AdditionalIbcmdArguments", nargs="*", default=[],
|
||||
help="Extra ibcmd arguments in --key=value form")
|
||||
known_opts = {s.lower() for a in parser._actions for s in a.option_strings}
|
||||
argv, v8_extra, ibcmd_extra = extract_extra_args(sys.argv[1:], known_opts)
|
||||
args = parser.parse_args(argv)
|
||||
args = ci_parse_args(parser, argv)
|
||||
|
||||
args.V8Path = clean_path(args.V8Path, "-V8Path")
|
||||
args.InfoBasePath = clean_path(args.InfoBasePath, "-InfoBasePath")
|
||||
@@ -422,7 +700,7 @@ def main():
|
||||
args.ListFile = clean_path(args.ListFile, "-ListFile")
|
||||
|
||||
# --- Resolve V8Path ---
|
||||
v8path = resolve_v8path(args.V8Path)
|
||||
v8path = resolve_v8path(args.V8Path, args)
|
||||
|
||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
||||
|
||||
@@ -441,34 +719,42 @@ def main():
|
||||
# --- Validate connection ---
|
||||
if engine == "ibcmd":
|
||||
if not args.InfoBasePath:
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)")
|
||||
sys.exit(1)
|
||||
elif not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate config dir ---
|
||||
if not os.path.exists(args.ConfigDir):
|
||||
print(f"Error: config directory not found: {args.ConfigDir}", file=sys.stderr)
|
||||
print(f"Error: config directory not found: {args.ConfigDir}")
|
||||
sys.exit(1)
|
||||
|
||||
# --- Validate Partial mode ---
|
||||
# Перечислены файлы — загрузка частичная. Иначе список молча игнорировался бы, а умолчание
|
||||
# Full заменило бы всю конфигурацию базы.
|
||||
if args.Files or args.ListFile:
|
||||
if args.Mode == "Full":
|
||||
print("[note] перечислены файлы — загружаются только они; -Mode Full не применён")
|
||||
args.Mode = "Partial"
|
||||
if not args.Mode:
|
||||
args.Mode = "Full"
|
||||
if args.Mode == "Partial" and not args.Files and not args.ListFile:
|
||||
print("Error: -Files or -ListFile required for Partial mode", file=sys.stderr)
|
||||
print("Error: -Files or -ListFile required for Partial mode")
|
||||
sys.exit(1)
|
||||
|
||||
# --- ibcmd branch (file infobase only; hierarchical full-directory import) ---
|
||||
if engine == "ibcmd":
|
||||
if args.Format == "Plain":
|
||||
print("Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)", file=sys.stderr)
|
||||
print("Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)")
|
||||
sys.exit(1)
|
||||
if args.AllExtensions:
|
||||
arguments = ["infobase", "config", "import", "all-extensions", args.ConfigDir, f"--db-path={args.InfoBasePath}"]
|
||||
elif args.Mode == "Partial" or args.Files or args.ListFile:
|
||||
elif args.Mode == "Partial":
|
||||
# partial: import specific files (relative to ConfigDir)
|
||||
if args.ListFile:
|
||||
if not os.path.isfile(args.ListFile):
|
||||
print(f"Error: list file not found: {args.ListFile}", file=sys.stderr)
|
||||
print(f"Error: list file not found: {args.ListFile}")
|
||||
sys.exit(1)
|
||||
with open(args.ListFile, encoding="utf-8-sig") as f:
|
||||
file_list = [ln.strip() for ln in f if ln.strip()]
|
||||
@@ -477,7 +763,7 @@ def main():
|
||||
else:
|
||||
file_list = []
|
||||
if not file_list:
|
||||
print("Error: -Files or -ListFile required for partial import", file=sys.stderr)
|
||||
print("Error: -Files or -ListFile required for partial import")
|
||||
sys.exit(1)
|
||||
arguments = ["infobase", "config", "import", "files"] + file_list
|
||||
arguments += [f"--base-dir={args.ConfigDir}", f"--db-path={args.InfoBasePath}"]
|
||||
@@ -499,7 +785,7 @@ def main():
|
||||
print(f"Running: ibcmd {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName)}")
|
||||
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
|
||||
if result.returncode != 0:
|
||||
print(f"Error loading configuration from files (code: {result.returncode}){describe_exit(result.returncode)}", file=sys.stderr)
|
||||
print(f"Error loading configuration from files (code: {result.returncode}){describe_exit(result.returncode)}")
|
||||
sys.exit(result.returncode)
|
||||
print(f"Configuration loaded successfully from: {args.ConfigDir}")
|
||||
exit_code = 0
|
||||
@@ -517,8 +803,19 @@ def main():
|
||||
if exit_code == 0:
|
||||
print("Database configuration updated successfully")
|
||||
else:
|
||||
print(f"Error updating database configuration (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error updating database configuration (code: {exit_code}){describe_exit(exit_code)}")
|
||||
print_platform_output(ar)
|
||||
# Проверку применимости умеет только 1cv8 — соединение для неё собираем в его форме.
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
ac_conn = ["/F", f'"{args.InfoBasePath}"']
|
||||
if args.UserName:
|
||||
ac_conn.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
ac_conn.append(f'/P"{args.Password}"')
|
||||
if apply_check_report(v8path, ac_conn, args.Extension, []) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
sys.exit(exit_code)
|
||||
|
||||
# --- Temp dir ---
|
||||
@@ -527,17 +824,25 @@ def main():
|
||||
|
||||
try:
|
||||
# --- Build arguments ---
|
||||
arguments = ["DESIGNER"]
|
||||
# Аргументы соединения собираем отдельно: тем же набором пойдёт проверка применимости.
|
||||
conn_args = []
|
||||
|
||||
if args.InfoBaseServer and args.InfoBaseRef:
|
||||
arguments += ["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"']
|
||||
conn_args += ["/S", f'"{args.InfoBaseServer}/{args.InfoBaseRef}"']
|
||||
else:
|
||||
arguments += ["/F", f'"{args.InfoBasePath}"']
|
||||
conn_args += ["/F", f'"{args.InfoBasePath}"']
|
||||
|
||||
if args.UserName:
|
||||
arguments.append(f'/N"{args.UserName}"')
|
||||
conn_args.append(f'/N"{args.UserName}"')
|
||||
if args.Password:
|
||||
arguments.append(f'/P"{args.Password}"')
|
||||
conn_args.append(f'/P"{args.Password}"')
|
||||
|
||||
# База под хранилищем не примет НИ ОДНОЙ операции конфигуратора без этих реквизитов, а для
|
||||
# базы вне хранилища они безвредны — поэтому подставляем всегда, когда они известны.
|
||||
repo = resolve_repository_settings(args)
|
||||
conn_args.extend(repository_args(repo))
|
||||
|
||||
arguments = ["DESIGNER"] + conn_args
|
||||
|
||||
arguments += ["/LoadConfigFromFiles", f'"{args.ConfigDir}"']
|
||||
|
||||
@@ -549,7 +854,7 @@ def main():
|
||||
# Build list file
|
||||
if args.ListFile:
|
||||
if not os.path.isfile(args.ListFile):
|
||||
print(f"Error: list file not found: {args.ListFile}", file=sys.stderr)
|
||||
print(f"Error: list file not found: {args.ListFile}")
|
||||
sys.exit(1)
|
||||
with open(args.ListFile, encoding="utf-8-sig") as f:
|
||||
raw_list = [ln.strip() for ln in f if ln.strip()]
|
||||
@@ -561,12 +866,12 @@ def main():
|
||||
support_files = [x for x in raw_list if support_re.search(x)]
|
||||
file_list = [x for x in raw_list if not support_re.search(x)]
|
||||
if support_files:
|
||||
print("[ВНИМАНИЕ] Служебные файлы состояния поддержки исключены из частичной загрузки (частично не грузятся):", file=sys.stderr)
|
||||
print("[ВНИМАНИЕ] Служебные файлы состояния поддержки исключены из частичной загрузки (частично не грузятся):")
|
||||
for sf in support_files:
|
||||
print(f" - {sf}", file=sys.stderr)
|
||||
print(" Смена состояния поддержки применяется только полной загрузкой: -Mode Full.", file=sys.stderr)
|
||||
print(f" - {sf}")
|
||||
print(" Смена состояния поддержки применяется только полной загрузкой: -Mode Full.")
|
||||
if not file_list:
|
||||
print("Error: после исключения служебных файлов поддержки загружать нечего. Для смены поддержки используйте -Mode Full.", file=sys.stderr)
|
||||
print("Error: после исключения служебных файлов поддержки загружать нечего. Для смены поддержки используйте -Mode Full.")
|
||||
sys.exit(1)
|
||||
generated_list_file = os.path.join(temp_dir, "load_list.txt")
|
||||
with open(generated_list_file, "w", encoding="utf-8-sig") as f:
|
||||
@@ -598,7 +903,7 @@ def main():
|
||||
arguments.extend(quote_if_needed(a) for a in extra_args)
|
||||
|
||||
# --- Execute ---
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName)}")
|
||||
print(f"Running: 1cv8.exe {_redact(' '.join(format_args_for_display(arguments, engine)), args.Password, args.UserName, repo['password'])}")
|
||||
result = run_v8(v8path, arguments)
|
||||
exit_code = result.returncode
|
||||
|
||||
@@ -614,22 +919,7 @@ def main():
|
||||
# --- Scan log for silent rejections ---
|
||||
# Platform often writes load-time rejections into /Out but exits with code 0.
|
||||
# These patterns flag cases where metadata was dropped or rejected silently.
|
||||
fatal_log_patterns = [
|
||||
"Неверное свойство объекта метаданных",
|
||||
"не входит в состав объекта метаданных",
|
||||
"Неизвестное имя типа",
|
||||
"Неизвестный объект метаданных",
|
||||
"Ни один из документов не является регистратором для регистра",
|
||||
"Неверное значение перечисления",
|
||||
"не может быть приведен к типу",
|
||||
]
|
||||
silent_failures = []
|
||||
if log_content:
|
||||
for line in log_content.splitlines():
|
||||
for pat in fatal_log_patterns:
|
||||
if pat in line:
|
||||
silent_failures.append(line.strip())
|
||||
break
|
||||
silent_failures = find_silent_rejections(log_content)
|
||||
|
||||
# --- Result ---
|
||||
# Default: mirror platform's verdict via exit code. Log content (including any
|
||||
@@ -638,7 +928,7 @@ def main():
|
||||
if exit_code == 0:
|
||||
print("Load completed successfully")
|
||||
else:
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}", file=sys.stderr)
|
||||
print(f"Error loading configuration (code: {exit_code}){describe_exit(exit_code)}")
|
||||
|
||||
if log_content:
|
||||
print("--- Log ---")
|
||||
@@ -646,18 +936,29 @@ def main():
|
||||
print("--- End ---")
|
||||
|
||||
print_platform_output(result)
|
||||
write_repository_hints(log_content)
|
||||
# Причину не называем: строки лога печатаются следом и говорят за себя, а класс проблемы
|
||||
# разный — от отброшенного свойства до нерабочей на этой платформе конфигурации. Подсказку
|
||||
# про -StrictLog не даём: загрузка уже выполнена, повторять её ради того же текста незачем.
|
||||
# Поток — stdout, как у PS1-порта: предупреждение относится к содержимому загрузки, а не к
|
||||
# отказу навыка, и при code 0 остаётся предупреждением. Раньше py писал его в stderr —
|
||||
# наблюдаемое поведение портов расходилось, и один кейс не мог проверить оба.
|
||||
if silent_failures:
|
||||
suffix = "" if args.StrictLog else " (pass -StrictLog to treat as error)"
|
||||
print(
|
||||
f"[warning] log contains {len(silent_failures)} rejection(s) — "
|
||||
f"platform loaded config but dropped properties/refs{suffix}",
|
||||
file=sys.stderr,
|
||||
f"[warning] platform reported success, but the log contains "
|
||||
f"{len(silent_failures)} problem(s):"
|
||||
)
|
||||
for f in silent_failures:
|
||||
print(f" {f}", file=sys.stderr)
|
||||
print(f" {f}")
|
||||
if args.StrictLog and exit_code == 0:
|
||||
exit_code = 1
|
||||
|
||||
# Расширение могло загрузиться «успешно» и остаться неприменимым — спрашиваем платформу.
|
||||
if (exit_code == 0 and (args.Extension or args.AllExtensions)
|
||||
and apply_check_enabled(args.NoApplyCheck)):
|
||||
if apply_check_report(v8path, conn_args, args.Extension, extra_args) and args.StrictLog:
|
||||
exit_code = 1
|
||||
|
||||
sys.exit(exit_code)
|
||||
|
||||
finally:
|
||||
@@ -0,0 +1,202 @@
|
||||
---
|
||||
name: db-repo
|
||||
description: Работа с хранилищем конфигурации 1С. Используй когда нужно захватить объекты, поместить изменения в хранилище конфигурации, получить изменения из него, подключить базу к хранилищу
|
||||
argument-hint: <lock|unlock|commit|update> [database] -Objects "<объекты>"
|
||||
allowed-tools:
|
||||
- Bash
|
||||
- Read
|
||||
- Glob
|
||||
- AskUserQuestion
|
||||
---
|
||||
|
||||
# /db-repo — Хранилище конфигурации 1С
|
||||
|
||||
Захват и помещение объектов, получение изменений, подключение базы, история версий,
|
||||
администрирование хранилища.
|
||||
|
||||
> Хранилище конфигурации 1С, а не Git-репозиторий.
|
||||
|
||||
## Usage
|
||||
|
||||
```
|
||||
/db-repo lock [database] -Objects "Справочник.Номенклатура"
|
||||
/db-repo commit [database] -Objects "Справочник.Номенклатура" -Comment "Добавлен Артикул"
|
||||
/db-repo unlock [database] -Objects "Справочник.Номенклатура"
|
||||
/db-repo update [database]
|
||||
```
|
||||
|
||||
## Порядок работы
|
||||
|
||||
В базу, подключённую к хранилищу, исходники грузятся **только частично** и **только по захваченным**
|
||||
объектам. Выполняй строго по шагам:
|
||||
|
||||
```
|
||||
0. /db-repo update <база> — начать с актуального состояния
|
||||
1. /db-repo lock <база> -Objects "Справочник.Номенклатура"
|
||||
2. если шаг 0 или 1 напечатал «локальная конфигурация изменена, получено объектов из хранилища: N» —
|
||||
выгрузи названные объекты: /db-dump-xml <база> <каталог> -Mode Partial -ObjectsFile "<файл из вывода>"
|
||||
3. правки в исходниках: /meta-edit, /form-edit, /skd-edit, /meta-compile и т. д.
|
||||
4. /db-load-xml <каталог> <база> -Mode Partial -Files "Catalogs/Номенклатура.xml,…" -UpdateDB
|
||||
5. /db-repo commit <база> -Objects "Справочник.Номенклатура" -Comment "…"
|
||||
```
|
||||
|
||||
Шаг 0 стоит делать всегда, когда работа не продолжается сразу после предыдущего цикла: правки
|
||||
должны опираться на актуальное состояние — в том числе тех объектов, которые ты не меняешь, но
|
||||
используешь.
|
||||
|
||||
Шаг 2 пропускать нельзя: захват и обновление подтягивают из хранилища свежие версии, и загрузка
|
||||
исходников, снятых раньше, откатит чужие изменения — молча, без ошибки.
|
||||
|
||||
**Что вообще захватывается.** Отдельные объекты хранилища — сам объект, а также его **формы,
|
||||
макеты и команды**. Реквизиты, табличные части, измерения и ресурсы отдельными объектами **не
|
||||
являются**: они правятся в составе владельца.
|
||||
|
||||
| Что правишь | Что захватывать |
|
||||
|-------------|-----------------|
|
||||
| Реквизит, табличную часть, измерение, ресурс, модуль объекта | сам объект: `Справочник.Контрагенты` |
|
||||
| Существующую форму, макет, команду | её саму: `Справочник.Контрагенты.Форма.ФормаЭлемента` |
|
||||
| Добавляешь новую форму, макет, команду | объект-владельца; при помещении назови и новый объект |
|
||||
| Добавляешь новый объект конфигурации | только корень: `Конфигурация`. Самого объекта ещё нет — захватить его нельзя; при помещении назови и его |
|
||||
|
||||
Захватывай минимум того, что правишь: чем шире захват, тем больше конфликтов с коллегами.
|
||||
Захват объекта его формы и макеты не захватывает — для этого есть `-WithChildren`.
|
||||
|
||||
## Параметры подключения
|
||||
|
||||
Прочитай `.v8-project.json` из корня проекта и разреши базу:
|
||||
1. Если пользователь указал параметры подключения — используй напрямую
|
||||
2. Если указал базу по имени — ищи по id / alias / name
|
||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||
4. Если ветка не совпала — используй `default`
|
||||
|
||||
Платформа — `v8path` найденной записи базы, иначе корневой `v8path`. Не задан ни там, ни там — `-V8Path` не передавай.
|
||||
|
||||
Реквизиты хранилища передавать не нужно: запись базы находится по переданным параметрам
|
||||
соединения (`-InfoBasePath` либо `-InfoBaseServer` + `-InfoBaseRef`), реквизиты берутся из её
|
||||
`repository`. Задать их явно можно параметрами `-Repository*`.
|
||||
|
||||
## Команда
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command <подкоманда> <параметры>
|
||||
```
|
||||
|
||||
### Рабочий цикл
|
||||
|
||||
| Подкоманда | Что делает |
|
||||
|------------|------------|
|
||||
| `lock` | Захватить объекты |
|
||||
| `unlock` | Отменить захват |
|
||||
| `commit` | Поместить изменения в хранилище |
|
||||
| `update` | Получить изменения из хранилища |
|
||||
|
||||
### Параметры
|
||||
|
||||
| Параметр | Обязательный | Описание |
|
||||
|----------|:------------:|----------|
|
||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С |
|
||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||
| `-UserName <имя>` | нет | Пользователь базы |
|
||||
| `-Password <пароль>` | нет | Пароль пользователя базы |
|
||||
| `-Objects <список>` | усл. | Объекты через запятую. Для `lock`, `unlock`, `commit` обязателен, если не задан `-All` |
|
||||
| `-ObjectsFile <путь>` | нет | Файл со списком объектов, одно имя на строку |
|
||||
| `-All` | нет | Операция над всей конфигурацией — вместо `-Objects`, а не вместе с ним |
|
||||
| `-WithChildren` | нет | Вместе с подчинёнными объектами на полную глубину |
|
||||
| `-Comment <текст>` | нет | Комментарий к помещению (`commit`). Многострочный — как есть, с переводами строк |
|
||||
| `-KeepLocked` | нет | Оставить объекты захваченными после помещения |
|
||||
| `-Revised` | нет | Получать захваченные объекты, если потребуется |
|
||||
| `-Force` | нет | Разное по подкомандам — см. ниже |
|
||||
| `-Extension <имя>` | нет | Работать с хранилищем расширения |
|
||||
| `-RepositoryPath <путь>` | нет | Хранилище явно, вместо реестра |
|
||||
| `-RepositoryUser <имя>` | нет | Пользователь хранилища явно |
|
||||
| `-RepositoryPassword <пароль>` | нет | Пароль пользователя хранилища явно |
|
||||
| `-AdditionalV8Arguments <список>` | нет | Доп. аргументы `1cv8.exe` через запятую |
|
||||
|
||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||
|
||||
### `-Force`
|
||||
|
||||
| Подкоманда | Что делает |
|
||||
|------------|------------|
|
||||
| `unlock` | **Теряет локальные правки**: объекты перезаписываются версией из хранилища |
|
||||
| `commit` | Пытается очистить ссылки на удалённые объекты вместо ошибки |
|
||||
| `update` | Подтверждает добавление и удаление объектов конфигурации |
|
||||
|
||||
### Имена объектов
|
||||
|
||||
Объект — `Справочник.Номенклатура`. Форма, макет, команда — полным путём:
|
||||
`Документ.ЗаказПокупателя.Форма.ФормаДокумента`, `Справочник.Номенклатура.Макет.Печать`.
|
||||
Корень конфигурации — `Конфигурация`.
|
||||
|
||||
Если объект «не найден», это не всегда опечатка: он мог появиться в хранилище позже, чем
|
||||
обновлялась база (`/db-repo update`), либо это вовсе не объект хранилища — реквизит или
|
||||
табличная часть.
|
||||
|
||||
## Результат
|
||||
|
||||
Нулевой код не означает, что что-то изменилось. Под нулём приходят «уже захвачено», «обновлять
|
||||
нечего», «помещать нечего» и частичный захват — когда часть объектов занята другими, а остальное
|
||||
захвачено и его можно править.
|
||||
|
||||
**Читай текст вывода, а не только код.** Там же приходит список полученных из хранилища объектов,
|
||||
который требует перевыгрузки перед правкой.
|
||||
|
||||
## Требуют подтверждения пользователя
|
||||
|
||||
Перед этими операциями **спроси подтверждение**:
|
||||
|
||||
| Операция | Почему |
|
||||
|----------|--------|
|
||||
| `lock -All` | Захватывает **всю конфигурацию**: на большой базе идёт долго и блокирует работу всей команде |
|
||||
| `unlock -Force` | Теряются локальные правки захваченных объектов |
|
||||
| `disconnect` | Теряется подключение базы к хранилищу, в том числе на стороне хранилища |
|
||||
| `connect -ForceReplaceCfg` | Конфигурация базы заменяется конфигурацией из хранилища |
|
||||
|
||||
`update` не выполнится, если у базы в реестре не объявлено `repository`, а реквизиты не заданы
|
||||
явно: на неподключённой к хранилищу базе эта команда заменяет всю конфигурацию его содержимым и
|
||||
рапортует успех.
|
||||
|
||||
## Расширения
|
||||
|
||||
У расширения своё хранилище со своим путём. Укажи `-Extension "<Имя>"` — реквизиты возьмутся из
|
||||
`extensions[].repository` записи базы. Подкоманды работают одинаково для основной конфигурации и
|
||||
для расширения.
|
||||
|
||||
## Остальные задачи
|
||||
|
||||
| Файл | Про что |
|
||||
|------|---------|
|
||||
| [connect.md](references/connect.md) | Подключение и отключение базы от хранилища |
|
||||
| [history.md](references/history.md) | История версий, отчёт, выгрузка версии в CF |
|
||||
| [admin.md](references/admin.md) | Создание хранилища, пользователи и права |
|
||||
| [service.md](references/service.md) | Метки версий, оптимизация, очистка кеша |
|
||||
|
||||
## Примеры
|
||||
|
||||
```powershell
|
||||
# Захватить справочник вместе с подчинёнными объектами
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command lock -InfoBasePath "C:\Bases\MyDB" -Objects "Справочник.Номенклатура" -WithChildren
|
||||
|
||||
# Захватить корень — он нужен, чтобы добавить или удалить объект конфигурации
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command lock -InfoBasePath "C:\Bases\MyDB" -Objects "Конфигурация"
|
||||
|
||||
# Поместить новый объект: он уже существует, поэтому называется вместе с корнем
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command commit -InfoBasePath "C:\Bases\MyDB" -Objects "Конфигурация,Справочник.Склады" -Comment "Добавлен справочник Склады"
|
||||
|
||||
# Поместить с комментарием, оставив захват
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command commit -InfoBasePath "C:\Bases\MyDB" -Objects "Справочник.Номенклатура" -Comment "Добавлен реквизит Артикул" -KeepLocked
|
||||
|
||||
# Получить изменения из хранилища
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command update -InfoBasePath "C:\Bases\MyDB"
|
||||
|
||||
# Серверная база, расширение
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command lock -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Extension "МоёРасширение" -Objects "Справочник.Номенклатура"
|
||||
```
|
||||
|
||||
## После выполнения
|
||||
|
||||
- `lock` или `update` сообщил о полученных объектах — выполни `/db-dump-xml -Mode Partial` с
|
||||
указанным в выводе файлом, и только потом правь исходники
|
||||
- после `lock` правки идут через `/db-load-xml -Mode Partial` и `/db-update`
|
||||
- изменения готовы — предложи `/db-repo commit` с комментарием
|
||||
@@ -0,0 +1,45 @@
|
||||
# Администрирование хранилища
|
||||
|
||||
## create — создать хранилище
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command create -InfoBasePath "C:\Bases\MyDB" -RepositoryPath "C:\Repo\MyApp" -RepositoryUser "Admin" -RepositoryPassword "…"
|
||||
```
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `-NoBind` | Не подключать базу к созданному хранилищу |
|
||||
| `-AllowConfigurationChanges` | Включить возможность изменения, если конфигурация на поддержке без неё |
|
||||
| `-ChangesAllowedRule <правило>` | Правило для объектов, изменения которых разрешены поставщиком |
|
||||
| `-ChangesNotRecommendedRule <правило>` | То же для «изменения не рекомендуются» |
|
||||
|
||||
Правила: `ObjectNotEditable`, `ObjectIsEditableSupportEnabled`, `ObjectNotSupported`.
|
||||
|
||||
Без `-NoBind` база сразу подключается к созданному хранилищу. Создание — это версия 1.
|
||||
|
||||
Для расширения: `-Extension "<Имя>"` и отдельный путь — у расширения своё хранилище.
|
||||
|
||||
## add-user — создать пользователя
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command add-user -InfoBasePath "C:\Bases\MyDB" -NewUser "Ivanov" -NewUserPassword "…" -Rights LockObjects
|
||||
```
|
||||
|
||||
| Право | Что даёт |
|
||||
|-------|----------|
|
||||
| `ReadOnly` | Просмотр |
|
||||
| `LockObjects` | Захват объектов |
|
||||
| `ManageConfigurationVersions` | Изменение состава версий |
|
||||
| `Administration` | Административные функции |
|
||||
|
||||
`-RestoreDeletedUser` — восстановить одноимённого удалённого. Если пользователь с таким именем
|
||||
существует, он **не** будет добавлен. Выполняющий должен иметь административные права.
|
||||
|
||||
## copy-users — скопировать пользователей из другого хранилища
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command copy-users -InfoBasePath "C:\Bases\MyDB" -SourcePath "\\srv01\repo\Other" -SourceUser "Admin" -SourcePassword "…"
|
||||
```
|
||||
|
||||
`-SourcePath`, `-SourceUser`, `-SourcePassword` описывают хранилище-**источник**. Удалённые пользователи
|
||||
не копируются; существующие не перезаписываются.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Подключение базы к хранилищу
|
||||
|
||||
## connect — подключить
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command connect -InfoBasePath "C:\Bases\MyDB" -RepositoryPath "\\srv01\repo\MyApp" -RepositoryUser "Ivanov" -RepositoryPassword "…"
|
||||
```
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `-ForceReplaceCfg` | Конфигурация базы непустая — подтвердить замену её конфигурацией из хранилища. **Спроси подтверждение у пользователя** |
|
||||
| `-ForceBindAlreadyBindedUser` | Подключить, даже если у этого пользователя уже есть конфигурация, связанная с хранилищем |
|
||||
|
||||
На пустой базе `-ForceReplaceCfg` не нужен.
|
||||
|
||||
**Переподключение** базы, которая уже была подключена, требует обоих флагов: конфигурация в базе
|
||||
не пустая (`-ForceReplaceCfg`), а за пользователем хранилища всё ещё числится эта база
|
||||
(`-ForceBindAlreadyBindedUser`).
|
||||
|
||||
После подключения добавь `repository` в запись базы в `.v8-project.json` — иначе остальные
|
||||
подкоманды придётся каждый раз звать с явными реквизитами, а `update` откажется работать.
|
||||
|
||||
## disconnect — отключить
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command disconnect -InfoBasePath "C:\Bases\MyDB"
|
||||
```
|
||||
|
||||
**Спроси подтверждение у пользователя.** Отключение снимает связь и на стороне самого хранилища:
|
||||
запись о подключении удаляется. Подключить базу обратно можно, но это уже не рядовая операция —
|
||||
понадобятся оба флага `connect` из раздела выше.
|
||||
|
||||
Если в базе есть захваченные и изменённые объекты, операция не выполнится. `-Force` выполняет её
|
||||
всё равно, и эти изменения теряются.
|
||||
|
||||
## Расширения
|
||||
|
||||
У расширения своё хранилище: `-Extension "<Имя>"` указывай вместе с путём именно к нему, а не
|
||||
к хранилищу основной конфигурации.
|
||||
@@ -0,0 +1,31 @@
|
||||
# История версий хранилища
|
||||
|
||||
## report — отчёт по версиям
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command report -InfoBasePath "C:\Bases\MyDB" -OutputFile "C:\tmp\repo.txt"
|
||||
```
|
||||
|
||||
| Параметр | Описание |
|
||||
|----------|----------|
|
||||
| `-OutputFile <путь>` | Куда сохранить отчёт. Необязателен |
|
||||
| `-NBegin <номер>` | С какой версии. `-1` — только последняя |
|
||||
| `-NEnd <номер>` | По какую версию |
|
||||
| `-DateBegin` / `-DateEnd` | Границы по датам |
|
||||
| `-GroupByObject` | Группировать по объектам |
|
||||
| `-GroupByComment` | Группировать по комментарию |
|
||||
| `-ReportFormat <txt\|mxl>` | По умолчанию `txt` |
|
||||
|
||||
`txt` — с разделителем-табуляцией, разбирается построчно.
|
||||
|
||||
> На боевом хранилище полный отчёт строить не надо — тысячи версий. Нужна головная
|
||||
> версия — `-NBegin -1`. Длинный отчёт в вывод не печатается: сузьте выборку
|
||||
> параметрами ниже.
|
||||
|
||||
## dump-cfg — выгрузить версию в CF
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command dump-cfg -InfoBasePath "C:\Bases\MyDB" -OutputFile "C:\tmp\v120.cf" -Version 120
|
||||
```
|
||||
|
||||
Без `-Version` (или при `-1`) выгружается последняя версия.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Сервисные операции
|
||||
|
||||
## set-label — метка на версию
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command set-label -InfoBasePath "C:\Bases\MyDB" -Label "Релиз 1.2" -Version 120 -Comment "Передано в тест"
|
||||
```
|
||||
|
||||
Без `-Version` метка ставится на последнюю версию. Несуществующая версия — ошибка.
|
||||
|
||||
## optimize — оптимизация хранения
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command optimize -InfoBasePath "C:\Bases\MyDB"
|
||||
```
|
||||
|
||||
Оптимизирует хранение данных в хранилище. Операция долгая.
|
||||
|
||||
## clear-cache — очистка кеша
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -File ".kilocode/skills/db-repo/scripts/db-repo.ps1" -Command clear-cache -InfoBasePath "C:\Bases\MyDB" -CacheScope local
|
||||
```
|
||||
|
||||
| `-CacheScope` | Что чистит |
|
||||
|---------------|------------|
|
||||
| `local` (по умолчанию) | Локальный кеш версий конфигурации |
|
||||
| `global` | Глобальный кеш версий |
|
||||
| `db` | Локальную базу данных хранилища |
|
||||
|
||||
Пригождается, когда хранилище ведёт себя странно после сбоя сети или отката версии.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user