mirror of
https://github.com/Nikolay-Shirokov/cc-1c-skills.git
synced 2026-07-06 11:18:56 +03:00
Compare commits
457 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6c01f3a261 | |||
| 506f0b84df | |||
| f5c02144cb | |||
| d982c5082a | |||
| cce00a4def | |||
| bc4ee63986 | |||
| a314ec32fc | |||
| baefeaa05b | |||
| 2d88cdc864 | |||
| f7695a9534 | |||
| 252105396b | |||
| 42df4cd6b1 | |||
| b9a04b235f | |||
| 9bc0240e95 | |||
| 4cfcaaaa1c | |||
| f9c3792528 | |||
| 9090a81e43 | |||
| f037324ee9 | |||
| 6f36e36166 | |||
| ca0dac2693 | |||
| ab7d82ba20 | |||
| 669b5f42f2 | |||
| 5b6fcc7c74 | |||
| df47128994 | |||
| ea453e5c97 | |||
| 14b0782904 | |||
| b7e3bd876d | |||
| b68f4145ce | |||
| dc2056a5d5 | |||
| bef4a13ba9 | |||
| c280e52932 | |||
| c86bf8779f | |||
| a4e0faaeb3 | |||
| 9d6ceae4f1 | |||
| 18ad662378 | |||
| 05fc7eba27 | |||
| ffa3189442 | |||
| bb02c1b0bd | |||
| 46f0e6be8c | |||
| 38ccded7d9 | |||
| 4e0ce5ba0f | |||
| e948d39adb | |||
| d9e7d9c107 | |||
| 1da43109fc | |||
| 21a0e360ef | |||
| 9f5e244f68 | |||
| 18a198d12b | |||
| 8fca42193a | |||
| b603c7e3fa | |||
| b00289e62c | |||
| 97820111d5 | |||
| 0a2a36dbc6 | |||
| b36232ae19 | |||
| 1479f944f5 | |||
| 9cffa81bcc | |||
| 6667ab38ee | |||
| 26c5e849a5 | |||
| ca681676b4 | |||
| e3a9be0036 | |||
| 361354cdd4 | |||
| 2ce7b12c4c | |||
| f244d5e507 | |||
| 6cb54a8f96 | |||
| 75f56603b6 | |||
| 55ab172ba4 | |||
| e9e00c906d | |||
| 31792a8a2d | |||
| fa2e3dd3e7 | |||
| 3e8a0a792f | |||
| d5e4bc3f21 | |||
| 7a6e63078d | |||
| 55b0ffa4fd | |||
| d06ecb940f | |||
| 21de2a4749 | |||
| 07be2bcafd | |||
| 24a48b4a9f | |||
| 91b5204ab2 | |||
| f2bd42c54c | |||
| 7e56cd79db | |||
| 1abc44334c | |||
| 0ca2faa6a6 | |||
| 767b9fcaf0 | |||
| 598e223288 | |||
| f7a27e750d | |||
| 15840ed1ca | |||
| 733418e630 | |||
| b15fb999cf | |||
| 5414ac373e | |||
| 0c4addaedc | |||
| cc0d577fc5 | |||
| 160a845bd8 | |||
| 184e4773a4 | |||
| 97105486b5 | |||
| 23f4cc0bbd | |||
| c5c67600b3 | |||
| 85191dc759 | |||
| 064e42842e | |||
| 4507d9b59c | |||
| 17be0ca009 | |||
| 8f59d3bc66 | |||
| f93a1560a5 | |||
| 298589d7cc | |||
| c6a84e2f91 | |||
| de7e943de1 | |||
| 4855cd1e01 | |||
| 7abe26afee | |||
| 512562ca50 | |||
| 84d078bd05 | |||
| 8584021446 | |||
| e7e6c885c7 | |||
| b5a779bd5d | |||
| 6df64ae1c1 | |||
| 007b4ec69c | |||
| cf5eae6428 | |||
| c72f2210b5 | |||
| 06584c29b2 | |||
| d94ffdea99 | |||
| 9f370dd499 | |||
| 903f1f2750 | |||
| 29b124f3fd | |||
| ffdee04a95 | |||
| b2a2534b5a | |||
| 422e397381 | |||
| 191706b984 | |||
| 93e4130ff2 | |||
| 3f091b209c | |||
| 5d4ee6c58c | |||
| 86c8440531 | |||
| 42cc7acdbe | |||
| 72a4015a8d | |||
| 843916642c | |||
| 84f3662c02 | |||
| 4cdd3377ae | |||
| 730daf1089 | |||
| c0255c71d0 | |||
| cf1cd1a711 | |||
| 5a1974be4e | |||
| 589091510b | |||
| 19667caccb | |||
| 97fc6dbd7f | |||
| 49108f72dc | |||
| dbb39b7a3e | |||
| 87dc18b120 | |||
| ca328e3e8f | |||
| c2b90a97ef | |||
| e717d4a57f | |||
| 6051972391 | |||
| 24751a59de | |||
| b824759a05 | |||
| fb23cbda56 | |||
| 69c89d3d70 | |||
| dee85e19d5 | |||
| 87348ec73c | |||
| dd81c85366 | |||
| c6f499a099 | |||
| b5826a61c4 | |||
| 3097811dde | |||
| f01f9d6ae8 | |||
| 0a1f8888dc | |||
| 66eb0b19ec | |||
| 872675652f | |||
| fde6d346d7 | |||
| 4490aeb533 | |||
| 6958cc558b | |||
| 8a286d7191 | |||
| a5fa730747 | |||
| 53219cae6c | |||
| b1187865ec | |||
| 22bf17ee00 | |||
| 2e0dcb773b | |||
| c958f3f818 | |||
| 684e97e518 | |||
| ce5651a5d7 | |||
| e706aca958 | |||
| 90b3d5d2e9 | |||
| 1b37bad331 | |||
| 8b0664b18d | |||
| 2af73d25bf | |||
| 449e2f667e | |||
| e032143157 | |||
| 09fc3a7f43 | |||
| 01315839fb | |||
| 6505fb1986 | |||
| 9e022c60f9 | |||
| e23a235ffa | |||
| 5bccca2475 | |||
| a8d8007846 | |||
| 37d2a5ee15 | |||
| 050d42a457 | |||
| 5acb586bbf | |||
| 7f6ea32533 | |||
| e9b53505ac | |||
| 6ce36f7d9b | |||
| a13f16e49d | |||
| 8f130f2e83 | |||
| 26ea09e2ff | |||
| 98c416b5a7 | |||
| 98ece6206e | |||
| 0c0a1aea49 | |||
| 5870fa200f | |||
| 7c10e5e4b1 | |||
| 665d5579d2 | |||
| 0fec18bbc4 | |||
| cc751a344e | |||
| f956749e1e | |||
| 2a6f4b1d5f | |||
| 9318d05535 | |||
| bb07bfae14 | |||
| 38c82f4a2f | |||
| d5fa5349d4 | |||
| ebc63c0264 | |||
| 99a5c7168a | |||
| 751a6a8f12 | |||
| 43a2691d6a | |||
| e6da514b67 | |||
| 1e5c42fa56 | |||
| 59627b0699 | |||
| 7b69228d23 | |||
| da0cedf256 | |||
| cc6b170488 | |||
| f9439dce6d | |||
| 336466ae82 | |||
| 59d223d72b | |||
| f56f5dc849 | |||
| 1fd3d8ffb8 | |||
| d6befb0dc8 | |||
| 5120b135f5 | |||
| 5d18bf4501 | |||
| 366378c4b5 | |||
| 56203e2b71 | |||
| ff14880871 | |||
| a17a81fe98 | |||
| e58f5c1f82 | |||
| 0fbdd298ca | |||
| 68fd9bb4a7 | |||
| e18e8cd284 | |||
| 5ea6414585 | |||
| 75558fe46c | |||
| 90ca2a7c4a | |||
| 500e05703e | |||
| ebda3e6608 | |||
| 328cb60f18 | |||
| 5061d83282 | |||
| b10802d4d7 | |||
| ae0c3e3278 | |||
| 00ec14aed3 | |||
| 102a7b8849 | |||
| 68e346d645 | |||
| c8f58b5461 | |||
| ba963739d8 | |||
| afe760af4b | |||
| c6eae770f5 | |||
| d28bea8f0a | |||
| 475b6d9544 | |||
| 2d69ecf709 | |||
| 88f74e96f0 | |||
| bce2d7c85c | |||
| 8f3bde5cfc | |||
| 85cdea925e | |||
| 679f6bae94 | |||
| c5abfc3a4f | |||
| d9ce7b03cc | |||
| d6abb2b651 | |||
| 86a959a354 | |||
| 8e7125d850 | |||
| fa9fae49c2 | |||
| c0e18ed428 | |||
| 64453ebe08 | |||
| c91ad0a158 | |||
| 6b5992de34 | |||
| 9d5cbaab9f | |||
| fe8fa4bc3f | |||
| 028c5292d7 | |||
| 31debfb61b | |||
| a110c17066 | |||
| b535dff609 | |||
| 96b400ddb9 | |||
| b68013b2f2 | |||
| e2f765fcc0 | |||
| a3e9e3c907 | |||
| bc4778d6cc | |||
| 2a0b896f5d | |||
| bc9087957f | |||
| 78e252af1e | |||
| 4c5e10a958 | |||
| 7d0d2dbf3d | |||
| 89d1ad3a12 | |||
| 9c75e9392e | |||
| 5f7ee6fcae | |||
| 6f32e18e37 | |||
| 3565e1c97f | |||
| 28b967f591 | |||
| 9c1985b710 | |||
| 99d37fb494 | |||
| 48de4cdc2a | |||
| 544893b781 | |||
| 8ecc5764ed | |||
| 329d94dc55 | |||
| 7268b169d8 | |||
| 2a4d2bf8df | |||
| 6e7284fc79 | |||
| c9e991e1e8 | |||
| 2a0fff1416 | |||
| 1364f22df3 | |||
| 4b0304d0c8 | |||
| cfcc633257 | |||
| d7f012b307 | |||
| 27bb08d127 | |||
| 151ded9bae | |||
| d84a2fb4cf | |||
| 05362aeb96 | |||
| 01d02065a3 | |||
| a711f05acc | |||
| 7003a46ad0 | |||
| e29c184f8e | |||
| 38c0ce11a9 | |||
| fcc85c9c6e | |||
| 9331aa7825 | |||
| d6ad1eacdb | |||
| 52875b4dea | |||
| 2698a2b80b | |||
| 8e8660c52b | |||
| 5d3eccc8eb | |||
| b8e3107d14 | |||
| aae69664c5 | |||
| bd947f2c0b | |||
| 1b6ab2f144 | |||
| a6a708d14d | |||
| 3ec2d2594c | |||
| 08d29c0341 | |||
| 37ecb77256 | |||
| 9cfb62c5b1 | |||
| fff77d97ca | |||
| 484ee44387 | |||
| 47174ee236 | |||
| d02ca602a4 | |||
| f3b3f26af9 | |||
| be47935973 | |||
| 1312cd7db4 | |||
| a81c26afda | |||
| 7044f125ed | |||
| 989f4e49d9 | |||
| cb4b5ec935 | |||
| 7c5700e40f | |||
| a6bf6520ce | |||
| ed45f54594 | |||
| 099de2d850 | |||
| 2d79c0b0ee | |||
| acee4bd188 | |||
| 01b20426fa | |||
| 04e5360e52 | |||
| 33fa6dbe9a | |||
| 11152d2443 | |||
| daea0a72d1 | |||
| b4905fc3e3 | |||
| 23555b513f | |||
| 8aef749471 | |||
| bd30e48dae | |||
| 92dc00e152 | |||
| 45c2587e4a | |||
| 08722ff285 | |||
| 89c0775c65 | |||
| 5c0a55e090 | |||
| 2f2ecca88b | |||
| acb7a4eadc | |||
| 28b8061d64 | |||
| 703c3e6f80 | |||
| 2d0835ba17 | |||
| a9b7a90672 | |||
| 69213930b3 | |||
| 151d1d77cb | |||
| 70bb5074c8 | |||
| 91d254b718 | |||
| 1382194201 | |||
| 7e587b9a3e | |||
| 4594c74d21 | |||
| 2650b1a063 | |||
| f23a3e5536 | |||
| eb6f8379e6 | |||
| 91e4e1948f | |||
| f4d60d67bf | |||
| b67f4b21e6 | |||
| d573f84c9d | |||
| c306d18648 | |||
| d72dd1678e | |||
| 0ca6d3f089 | |||
| dddb9e3dac | |||
| f211ffa2f0 | |||
| 21dded4d1c | |||
| 941fa73803 | |||
| 24358f212f | |||
| d210d21079 | |||
| 2949682ce8 | |||
| e86620dbd7 | |||
| 9922f118d1 | |||
| 8c833f042c | |||
| 1d593af63a | |||
| be216cd064 | |||
| 55b1ef4e06 | |||
| e229fc4873 | |||
| 3a4c1905f4 | |||
| 7aaa9fc070 | |||
| 8b8bc1225a | |||
| dc10422f10 | |||
| 65afdf2e55 | |||
| f87c94e832 | |||
| 6681758121 | |||
| 89f0788585 | |||
| d27dfbf8e1 | |||
| fc24524c75 | |||
| 2c96c90d45 | |||
| 8fc30c9b9a | |||
| ecfb473827 | |||
| dc9e1fe3db | |||
| 5c07dec82c | |||
| c5fa794cf3 | |||
| 7e0e30730c | |||
| ad412dffa2 | |||
| c665800916 | |||
| d05199d048 | |||
| a9e59265dd | |||
| 99f57a5ff2 | |||
| a813c7fd46 | |||
| cc2595b57a | |||
| 580124a971 | |||
| 044bc18974 | |||
| 3819a5f7af | |||
| 56b1458545 | |||
| bca022fba8 | |||
| 0e680d151d | |||
| 8092015807 | |||
| 03a6820f69 | |||
| bfbef3c361 | |||
| 298d503c64 | |||
| 1ed5d783e8 | |||
| f0bb8c860f | |||
| 2f260ddb7f | |||
| 2771424c71 | |||
| 96890598f9 | |||
| 50dc9ceec9 | |||
| 455c12e6b6 | |||
| 1a79e84598 | |||
| 76a0dd80be | |||
| fdf661192d | |||
| be3a31ea94 | |||
| 061c73b23d | |||
| 9f9a022659 | |||
| 215319382a | |||
| d6660a4d00 | |||
| 4bc86decf8 | |||
| 34e88d2914 | |||
| b3dac25729 | |||
| c2348b6b68 | |||
| aaa4f65be1 | |||
| d34cbf7272 | |||
| e3daaf233d | |||
| 43333f1481 |
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: cf-edit
|
name: cf-edit
|
||||||
description: Точечное редактирование конфигурации 1С. Используй когда нужно изменить свойства конфигурации, добавить или удалить объект из состава, настроить роли по умолчанию, поменять раскладку панелей, настроить начальную страницу
|
description: Точечное редактирование конфигурации 1С. Используй когда нужно изменить свойства конфигурации, добавить или удалить объект из состава, настроить роли по умолчанию
|
||||||
argument-hint: -ConfigPath <path> -Operation <op> -Value <value>
|
argument-hint: -ConfigPath <path> -Operation <op> -Value <value>
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -24,7 +24,7 @@ allowed-tools:
|
|||||||
| `NoValidate` | Пропустить авто-валидацию |
|
| `NoValidate` | Пропустить авто-валидацию |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cf-edit/scripts/cf-edit.py" -ConfigPath '<path>' -Operation modify-property -Value 'Version=1.0.0.1'
|
powershell.exe -NoProfile -File .claude/skills/cf-edit/scripts/cf-edit.ps1 -ConfigPath '<path>' -Operation modify-property -Value 'Version=1.0.0.1'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Операции
|
## Операции
|
||||||
@@ -32,29 +32,27 @@ python ".opencode/skills/cf-edit/scripts/cf-edit.py" -ConfigPath '<path>' -Opera
|
|||||||
| Операция | Формат Value | Описание |
|
| Операция | Формат Value | Описание |
|
||||||
|----------|-------------|----------|
|
|----------|-------------|----------|
|
||||||
| `modify-property` | `Ключ=Значение` (batch `;;`) | Изменить свойство |
|
| `modify-property` | `Ключ=Значение` (batch `;;`) | Изменить свойство |
|
||||||
| `add-childObject` | `Type.Name` (batch `;;`) | Зарегистрировать уже существующий файл объекта в ChildObjects. Для создания нового объекта используй `/meta-compile`, `/role-compile`, `/subsystem-compile` — они регистрируют автоматически |
|
| `add-childObject` | `Type.Name` (batch `;;`) | Добавить объект в ChildObjects |
|
||||||
| `remove-childObject` | `Type.Name` (batch `;;`) | Удалить объект из ChildObjects |
|
| `remove-childObject` | `Type.Name` (batch `;;`) | Удалить объект из ChildObjects |
|
||||||
| `add-defaultRole` | `Role.Name` или `Name` | Добавить роль по умолчанию |
|
| `add-defaultRole` | `Role.Name` или `Name` | Добавить роль по умолчанию |
|
||||||
| `remove-defaultRole` | `Role.Name` или `Name` | Удалить роль по умолчанию |
|
| `remove-defaultRole` | `Role.Name` или `Name` | Удалить роль по умолчанию |
|
||||||
| `set-defaultRoles` | Имена через `;;` | Заменить список ролей по умолчанию |
|
| `set-defaultRoles` | Имена через `;;` | Заменить список ролей по умолчанию |
|
||||||
| `set-panels` | JSON-объект (см. [reference.md](reference.md)) | Перезаписать `Ext/ClientApplicationInterface.xml` (раскладка панелей) |
|
|
||||||
| `set-home-page` | JSON-объект (см. [reference.md](reference.md)) | Перезаписать `Ext/HomePageWorkArea.xml` (начальная страница) |
|
|
||||||
|
|
||||||
Допустимые значения свойств, формат DefinitionFile (JSON), каноничный порядок: [reference.md](reference.md)
|
Подробнее: `reference.md` в каталоге навыка.
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Изменить версию и поставщика
|
# Изменить версию и поставщика
|
||||||
... -ConfigPath src -Operation modify-property -Value "Version=1.0.0.1 ;; Vendor=Фирма 1С"
|
... -ConfigPath test-tmp/cf -Operation modify-property -Value "Version=1.0.0.1 ;; Vendor=Фирма 1С"
|
||||||
|
|
||||||
# Добавить объекты
|
# Добавить объекты
|
||||||
... -ConfigPath src -Operation add-childObject -Value "Catalog.Товары ;; Document.Заказ"
|
... -ConfigPath test-tmp/cf -Operation add-childObject -Value "Catalog.Товары ;; Document.Заказ"
|
||||||
|
|
||||||
# Удалить объект
|
# Удалить объект
|
||||||
... -ConfigPath src -Operation remove-childObject -Value "Catalog.Устаревший"
|
... -ConfigPath test-tmp/cf -Operation remove-childObject -Value "Catalog.Устаревший"
|
||||||
|
|
||||||
# Роли по умолчанию
|
# Роли по умолчанию
|
||||||
... -ConfigPath src -Operation add-defaultRole -Value "ПолныеПрава"
|
... -ConfigPath test-tmp/cf -Operation add-defaultRole -Value "ПолныеПрава"
|
||||||
... -ConfigPath src -Operation set-defaultRoles -Value "ПолныеПрава ;; Администратор"
|
... -ConfigPath test-tmp/cf -Operation set-defaultRoles -Value "ПолныеПрава ;; Администратор"
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# cf-edit — справочник операций
|
||||||
|
|
||||||
|
## modify-property
|
||||||
|
|
||||||
|
Свойства для редактирования:
|
||||||
|
|
||||||
|
### Скалярные
|
||||||
|
`Name`, `Version`, `Vendor`, `Comment`, `NamePrefix`, `UpdateCatalogAddress`
|
||||||
|
|
||||||
|
### LocalString (многоязычные)
|
||||||
|
`Synonym`, `BriefInformation`, `DetailedInformation`, `Copyright`, `VendorInformationAddress`, `ConfigurationInformationAddress`
|
||||||
|
|
||||||
|
### Enum
|
||||||
|
| Свойство | Допустимые значения |
|
||||||
|
|----------|---------------------|
|
||||||
|
| `CompatibilityMode` | `Version8_3_20` ... `Version8_3_27`, `DontUse` |
|
||||||
|
| `ConfigurationExtensionCompatibilityMode` | то же |
|
||||||
|
| `DefaultRunMode` | `ManagedApplication`, `OrdinaryApplication`, `Auto` |
|
||||||
|
| `ScriptVariant` | `Russian`, `English` |
|
||||||
|
| `DataLockControlMode` | `Managed`, `Automatic`, `AutomaticAndManaged` |
|
||||||
|
| `ObjectAutonumerationMode` | `NotAutoFree`, `AutoFree` |
|
||||||
|
| `ModalityUseMode` | `DontUse`, `Use`, `UseWithWarnings` |
|
||||||
|
| `SynchronousPlatformExtensionAndAddInCallUseMode` | `DontUse`, `Use`, `UseWithWarnings` |
|
||||||
|
| `InterfaceCompatibilityMode` | `Taxi`, `TaxiEnableVersion8_2`, `Version8_2` |
|
||||||
|
| `DatabaseTablespacesUseMode` | `DontUse`, `Use` |
|
||||||
|
| `MainClientApplicationWindowMode` | `Normal`, `Fullscreen`, `Kiosk` |
|
||||||
|
|
||||||
|
### Ref
|
||||||
|
`DefaultLanguage` — значение вида `Language.Русский`
|
||||||
|
|
||||||
|
### Формат batch
|
||||||
|
`"Version=1.0.0.1 ;; Vendor=Фирма 1С ;; Synonym=Тестовая конфигурация"`
|
||||||
|
|
||||||
|
## add-childObject / remove-childObject
|
||||||
|
|
||||||
|
Формат: `Type.Name` — XML-тип и имя объекта через точку.
|
||||||
|
|
||||||
|
При добавлении объект вставляется в каноническую позицию:
|
||||||
|
1. Находит последний элемент того же типа → вставляет после
|
||||||
|
2. Если тип отсутствует → находит последний элемент предшествующего типа → вставляет после
|
||||||
|
3. Внутри одного типа — алфавитный порядок
|
||||||
|
|
||||||
|
Batch: `"Catalog.Товары ;; Document.Заказ ;; Enum.ВидыОплат"`
|
||||||
|
|
||||||
|
## add-defaultRole / remove-defaultRole / set-defaultRoles
|
||||||
|
|
||||||
|
Имя роли: `ПолныеПрава` или `Role.ПолныеПрава` (префикс `Role.` добавляется автоматически).
|
||||||
|
|
||||||
|
`set-defaultRoles` полностью заменяет список ролей.
|
||||||
|
|
||||||
|
## DefinitionFile (JSON)
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{ "operation": "modify-property", "value": "Version=2.0.0.1 ;; Vendor=Test" },
|
||||||
|
{ "operation": "add-childObject", "value": "Catalog.Товары ;; Document.Заказ" },
|
||||||
|
{ "operation": "add-defaultRole", "value": "ПолныеПрава" }
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Авто-валидация
|
||||||
|
|
||||||
|
После сохранения автоматически запускается `cf-validate` (если не указан `-NoValidate`).
|
||||||
@@ -0,0 +1,523 @@
|
|||||||
|
# cf-edit v1.0 — Edit 1C configuration root (Configuration.xml)
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory)][string]$ConfigPath,
|
||||||
|
[string]$DefinitionFile,
|
||||||
|
[ValidateSet("modify-property","add-childObject","remove-childObject","add-defaultRole","remove-defaultRole","set-defaultRoles")]
|
||||||
|
[string]$Operation,
|
||||||
|
[string]$Value,
|
||||||
|
[switch]$NoValidate
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
|
# --- Mode validation ---
|
||||||
|
if ($DefinitionFile -and $Operation) { Write-Error "Cannot use both -DefinitionFile and -Operation"; exit 1 }
|
||||||
|
if (-not $DefinitionFile -and -not $Operation) { Write-Error "Either -DefinitionFile or -Operation is required"; exit 1 }
|
||||||
|
|
||||||
|
# --- Resolve path ---
|
||||||
|
if (-not [System.IO.Path]::IsPathRooted($ConfigPath)) {
|
||||||
|
$ConfigPath = Join-Path (Get-Location).Path $ConfigPath
|
||||||
|
}
|
||||||
|
if (Test-Path $ConfigPath -PathType Container) {
|
||||||
|
$candidate = Join-Path $ConfigPath "Configuration.xml"
|
||||||
|
if (Test-Path $candidate) { $ConfigPath = $candidate }
|
||||||
|
else { Write-Error "No Configuration.xml in directory"; exit 1 }
|
||||||
|
}
|
||||||
|
if (-not (Test-Path $ConfigPath)) { Write-Error "File not found: $ConfigPath"; exit 1 }
|
||||||
|
$resolvedPath = (Resolve-Path $ConfigPath).Path
|
||||||
|
|
||||||
|
# --- Load XML with PreserveWhitespace ---
|
||||||
|
$script:xmlDoc = New-Object System.Xml.XmlDocument
|
||||||
|
$script:xmlDoc.PreserveWhitespace = $true
|
||||||
|
$script:xmlDoc.Load($resolvedPath)
|
||||||
|
|
||||||
|
$script:addCount = 0
|
||||||
|
$script:removeCount = 0
|
||||||
|
$script:modifyCount = 0
|
||||||
|
|
||||||
|
function Info([string]$msg) { Write-Host "[INFO] $msg" }
|
||||||
|
function Warn([string]$msg) { Write-Host "[WARN] $msg" }
|
||||||
|
|
||||||
|
# --- Detect structure ---
|
||||||
|
$root = $script:xmlDoc.DocumentElement
|
||||||
|
$script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
|
||||||
|
$script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
|
||||||
|
$script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
$script:v8Ns = "http://v8.1c.ru/8.1/data/core"
|
||||||
|
|
||||||
|
$script:cfgEl = $null
|
||||||
|
foreach ($child in $root.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Configuration") {
|
||||||
|
$script:cfgEl = $child; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $script:cfgEl) { Write-Error "No <Configuration> element found"; exit 1 }
|
||||||
|
|
||||||
|
$script:propsEl = $null
|
||||||
|
$script:childObjsEl = $null
|
||||||
|
foreach ($child in $script:cfgEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -ne 'Element') { continue }
|
||||||
|
if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
|
||||||
|
if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
|
||||||
|
}
|
||||||
|
|
||||||
|
$script:objName = ""
|
||||||
|
foreach ($child in $script:propsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Name") {
|
||||||
|
$script:objName = $child.InnerText.Trim(); break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Info "Configuration: $($script:objName)"
|
||||||
|
|
||||||
|
# --- Canonical type order for ChildObjects (44 types) ---
|
||||||
|
$script:typeOrder = @(
|
||||||
|
"Language","Subsystem","StyleItem","Style",
|
||||||
|
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||||
|
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||||
|
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||||
|
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||||
|
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||||
|
"Constant","CommonForm","Catalog","Document",
|
||||||
|
"DocumentNumerator","Sequence","DocumentJournal","Enum",
|
||||||
|
"Report","DataProcessor","InformationRegister","AccumulationRegister",
|
||||||
|
"ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
|
||||||
|
"ChartOfCalculationTypes","CalculationRegister",
|
||||||
|
"BusinessProcess","Task","IntegrationService"
|
||||||
|
)
|
||||||
|
|
||||||
|
# --- XML manipulation helpers (from subsystem-edit pattern) ---
|
||||||
|
function Get-ChildIndent($container) {
|
||||||
|
foreach ($child in $container.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
|
||||||
|
if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
|
||||||
|
if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$depth = 0; $current = $container
|
||||||
|
while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
|
||||||
|
return "`t" * ($depth + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
|
||||||
|
$ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
|
||||||
|
if ($refNode) {
|
||||||
|
$container.InsertBefore($ws, $refNode) | Out-Null
|
||||||
|
$container.InsertBefore($newNode, $ws) | Out-Null
|
||||||
|
} else {
|
||||||
|
$trailing = $container.LastChild
|
||||||
|
if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
|
||||||
|
$container.InsertBefore($ws, $trailing) | Out-Null
|
||||||
|
$container.InsertBefore($newNode, $trailing) | Out-Null
|
||||||
|
} else {
|
||||||
|
$container.AppendChild($ws) | Out-Null
|
||||||
|
$container.AppendChild($newNode) | Out-Null
|
||||||
|
$parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
|
||||||
|
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
|
||||||
|
$container.AppendChild($closeWs) | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Remove-NodeWithWhitespace($node) {
|
||||||
|
$parent = $node.ParentNode
|
||||||
|
$prev = $node.PreviousSibling
|
||||||
|
$next = $node.NextSibling
|
||||||
|
if ($prev -and ($prev.NodeType -eq 'Whitespace' -or $prev.NodeType -eq 'SignificantWhitespace')) {
|
||||||
|
$parent.RemoveChild($prev) | Out-Null
|
||||||
|
} elseif ($next -and ($next.NodeType -eq 'Whitespace' -or $next.NodeType -eq 'SignificantWhitespace')) {
|
||||||
|
$parent.RemoveChild($next) | Out-Null
|
||||||
|
}
|
||||||
|
$parent.RemoveChild($node) | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
function Expand-SelfClosingElement($container, $parentIndent) {
|
||||||
|
if (-not $container.HasChildNodes -or $container.IsEmpty) {
|
||||||
|
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
|
||||||
|
$container.AppendChild($closeWs) | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Import-Fragment([string]$xmlString) {
|
||||||
|
$wrapper = "<_W xmlns=`"$($script:mdNs)`" xmlns:xsi=`"$($script:xsiNs)`" xmlns:v8=`"$($script:v8Ns)`" xmlns:xr=`"$($script:xrNs)`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`">$xmlString</_W>"
|
||||||
|
$frag = New-Object System.Xml.XmlDocument
|
||||||
|
$frag.PreserveWhitespace = $true
|
||||||
|
$frag.LoadXml($wrapper)
|
||||||
|
$nodes = @()
|
||||||
|
foreach ($child in $frag.DocumentElement.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element') {
|
||||||
|
$nodes += $script:xmlDoc.ImportNode($child, $true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ,$nodes
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Parse batch value (split by ;;) ---
|
||||||
|
function Parse-BatchValue([string]$val) {
|
||||||
|
$items = @()
|
||||||
|
foreach ($part in $val.Split(";;")) {
|
||||||
|
$trimmed = $part.Trim()
|
||||||
|
if ($trimmed) { $items += $trimmed }
|
||||||
|
}
|
||||||
|
return ,$items
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- LocalString properties ---
|
||||||
|
$mlProps = @("Synonym","BriefInformation","DetailedInformation","Copyright","VendorInformationAddress","ConfigurationInformationAddress")
|
||||||
|
# Scalar properties
|
||||||
|
$scalarProps = @("Name","Version","Vendor","Comment","NamePrefix","UpdateCatalogAddress")
|
||||||
|
# Ref properties
|
||||||
|
$refProps = @("DefaultLanguage")
|
||||||
|
|
||||||
|
# --- Operation: modify-property ---
|
||||||
|
function Do-ModifyProperty([string]$batchVal) {
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$eqIdx = $item.IndexOf("=")
|
||||||
|
if ($eqIdx -lt 1) {
|
||||||
|
Write-Error "Invalid property format '$item', expected 'Key=Value'"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$propName = $item.Substring(0, $eqIdx).Trim()
|
||||||
|
$propValue = $item.Substring($eqIdx + 1).Trim()
|
||||||
|
|
||||||
|
# Find property element
|
||||||
|
$propEl = $null
|
||||||
|
foreach ($child in $script:propsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $propName) {
|
||||||
|
$propEl = $child; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $propEl) {
|
||||||
|
Write-Error "Property '$propName' not found in Properties"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($mlProps -contains $propName) {
|
||||||
|
# LocalString
|
||||||
|
if (-not $propValue) {
|
||||||
|
$propEl.InnerXml = ""
|
||||||
|
} else {
|
||||||
|
$indent = Get-ChildIndent $script:propsEl
|
||||||
|
$escaped = [System.Security.SecurityElement]::Escape($propValue)
|
||||||
|
$mlXml = "`r`n$indent`t<v8:item>`r`n$indent`t`t<v8:lang>ru</v8:lang>`r`n$indent`t`t<v8:content>$escaped</v8:content>`r`n$indent`t</v8:item>`r`n$indent"
|
||||||
|
$propEl.InnerXml = $mlXml
|
||||||
|
}
|
||||||
|
} elseif ($scalarProps -contains $propName -or $refProps -contains $propName) {
|
||||||
|
# Simple text
|
||||||
|
if (-not $propValue) { $propEl.InnerXml = "" }
|
||||||
|
else { $propEl.InnerText = $propValue }
|
||||||
|
} else {
|
||||||
|
# Enum or other — just set text
|
||||||
|
$propEl.InnerText = $propValue
|
||||||
|
}
|
||||||
|
|
||||||
|
$script:modifyCount++
|
||||||
|
Info "Set $propName = `"$propValue`""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Operation: add-childObject ---
|
||||||
|
function Do-AddChildObject([string]$batchVal) {
|
||||||
|
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
|
||||||
|
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
$cfgIndent = Get-ChildIndent $script:cfgEl
|
||||||
|
|
||||||
|
# Expand self-closing if needed
|
||||||
|
if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
|
||||||
|
Expand-SelfClosingElement $script:childObjsEl $cfgIndent
|
||||||
|
}
|
||||||
|
$childIndent = Get-ChildIndent $script:childObjsEl
|
||||||
|
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$dotIdx = $item.IndexOf(".")
|
||||||
|
if ($dotIdx -lt 1) {
|
||||||
|
Write-Error "Invalid format '$item', expected 'Type.Name'"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$typeName = $item.Substring(0, $dotIdx)
|
||||||
|
$objNameVal = $item.Substring($dotIdx + 1)
|
||||||
|
|
||||||
|
# Check type is valid
|
||||||
|
$typeIdx = $script:typeOrder.IndexOf($typeName)
|
||||||
|
if ($typeIdx -lt 0) {
|
||||||
|
Write-Error "Unknown type '$typeName'"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Dedup check
|
||||||
|
$existing = $false
|
||||||
|
foreach ($child in $script:childObjsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objNameVal) {
|
||||||
|
$existing = $true; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($existing) {
|
||||||
|
Warn "Already exists: $typeName.$objNameVal"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
# Find insertion point: after last element of same type, or after last element of preceding type
|
||||||
|
$insertBefore = $null
|
||||||
|
$lastSameType = $null
|
||||||
|
$lastPrecedingType = $null
|
||||||
|
$currentTypeIdx = -1
|
||||||
|
|
||||||
|
foreach ($child in $script:childObjsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -ne 'Element') { continue }
|
||||||
|
$childTypeIdx = $script:typeOrder.IndexOf($child.LocalName)
|
||||||
|
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)
|
||||||
|
$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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create element
|
||||||
|
$newEl = $script:xmlDoc.CreateElement($typeName, $script:mdNs)
|
||||||
|
$newEl.InnerText = $objNameVal
|
||||||
|
|
||||||
|
if ($insertBefore) {
|
||||||
|
Insert-BeforeElement $script:childObjsEl $newEl $insertBefore $childIndent
|
||||||
|
} else {
|
||||||
|
# Append at end (or after last same/preceding type)
|
||||||
|
Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
|
||||||
|
}
|
||||||
|
|
||||||
|
$script:addCount++
|
||||||
|
Info "Added: $typeName.$objNameVal"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Operation: remove-childObject ---
|
||||||
|
function Do-RemoveChildObject([string]$batchVal) {
|
||||||
|
if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found"; exit 1 }
|
||||||
|
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$dotIdx = $item.IndexOf(".")
|
||||||
|
if ($dotIdx -lt 1) {
|
||||||
|
Write-Error "Invalid format '$item', expected 'Type.Name'"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$typeName = $item.Substring(0, $dotIdx)
|
||||||
|
$objNameVal = $item.Substring($dotIdx + 1)
|
||||||
|
|
||||||
|
$found = $false
|
||||||
|
foreach ($child in @($script:childObjsEl.ChildNodes)) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objNameVal) {
|
||||||
|
Remove-NodeWithWhitespace $child
|
||||||
|
$script:removeCount++
|
||||||
|
Info "Removed: $typeName.$objNameVal"
|
||||||
|
$found = $true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $found) { Warn "Not found: $typeName.$objNameVal" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Operation: add-defaultRole ---
|
||||||
|
function Do-AddDefaultRole([string]$batchVal) {
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
|
||||||
|
# Find DefaultRoles element
|
||||||
|
$rolesEl = $null
|
||||||
|
foreach ($child in $script:propsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
|
||||||
|
$rolesEl = $child; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found in Properties"; exit 1 }
|
||||||
|
|
||||||
|
$propsIndent = Get-ChildIndent $script:propsEl
|
||||||
|
if (-not $rolesEl.HasChildNodes -or $rolesEl.IsEmpty) {
|
||||||
|
Expand-SelfClosingElement $rolesEl $propsIndent
|
||||||
|
}
|
||||||
|
$roleIndent = Get-ChildIndent $rolesEl
|
||||||
|
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$roleName = $item
|
||||||
|
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
|
||||||
|
|
||||||
|
# Dedup
|
||||||
|
$existing = $false
|
||||||
|
foreach ($child in $rolesEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.InnerText.Trim() -eq $roleName) {
|
||||||
|
$existing = $true; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ($existing) {
|
||||||
|
Warn "DefaultRole already exists: $roleName"
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
$fragXml = "<xr:Item xsi:type=`"xr:MDObjectRef`">$roleName</xr:Item>"
|
||||||
|
$nodes = Import-Fragment $fragXml
|
||||||
|
if ($nodes.Count -gt 0) {
|
||||||
|
Insert-BeforeElement $rolesEl $nodes[0] $null $roleIndent
|
||||||
|
$script:addCount++
|
||||||
|
Info "Added DefaultRole: $roleName"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Operation: remove-defaultRole ---
|
||||||
|
function Do-RemoveDefaultRole([string]$batchVal) {
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
|
||||||
|
$rolesEl = $null
|
||||||
|
foreach ($child in $script:propsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
|
||||||
|
$rolesEl = $child; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found"; exit 1 }
|
||||||
|
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$roleName = $item
|
||||||
|
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
|
||||||
|
|
||||||
|
$found = $false
|
||||||
|
foreach ($child in @($rolesEl.ChildNodes)) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.InnerText.Trim() -eq $roleName) {
|
||||||
|
Remove-NodeWithWhitespace $child
|
||||||
|
$script:removeCount++
|
||||||
|
Info "Removed DefaultRole: $roleName"
|
||||||
|
$found = $true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $found) { Warn "DefaultRole not found: $roleName" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Operation: set-defaultRoles ---
|
||||||
|
function Do-SetDefaultRoles([string]$batchVal) {
|
||||||
|
$items = Parse-BatchValue $batchVal
|
||||||
|
|
||||||
|
$rolesEl = $null
|
||||||
|
foreach ($child in $script:propsEl.ChildNodes) {
|
||||||
|
if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "DefaultRoles") {
|
||||||
|
$rolesEl = $child; break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $rolesEl) { Write-Error "No <DefaultRoles> element found"; exit 1 }
|
||||||
|
|
||||||
|
# Clear all existing children
|
||||||
|
while ($rolesEl.HasChildNodes) {
|
||||||
|
$rolesEl.RemoveChild($rolesEl.FirstChild) | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($items.Count -eq 0) {
|
||||||
|
$script:modifyCount++
|
||||||
|
Info "Cleared DefaultRoles"
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$propsIndent = Get-ChildIndent $script:propsEl
|
||||||
|
$roleIndent = "$propsIndent`t"
|
||||||
|
|
||||||
|
# Add closing whitespace
|
||||||
|
$closeWs = $script:xmlDoc.CreateWhitespace("`r`n$propsIndent")
|
||||||
|
$rolesEl.AppendChild($closeWs) | Out-Null
|
||||||
|
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$roleName = $item
|
||||||
|
if (-not $roleName.StartsWith("Role.")) { $roleName = "Role.$roleName" }
|
||||||
|
|
||||||
|
$fragXml = "<xr:Item xsi:type=`"xr:MDObjectRef`">$roleName</xr:Item>"
|
||||||
|
$nodes = Import-Fragment $fragXml
|
||||||
|
if ($nodes.Count -gt 0) {
|
||||||
|
Insert-BeforeElement $rolesEl $nodes[0] $null $roleIndent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$script:modifyCount++
|
||||||
|
Info "Set DefaultRoles: $($items.Count) roles"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Execute operations ---
|
||||||
|
$operations = @()
|
||||||
|
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
|
||||||
|
if ($ops -is [System.Array]) {
|
||||||
|
foreach ($op in $ops) { $operations += $op }
|
||||||
|
} else {
|
||||||
|
$operations += $ops
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$operations += @{ operation = $Operation; value = $Value }
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($op in $operations) {
|
||||||
|
$opName = if ($op.operation) { "$($op.operation)" } else { "$Operation" }
|
||||||
|
$opValue = if ($op.value) { "$($op.value)" } else { "$Value" }
|
||||||
|
|
||||||
|
switch ($opName) {
|
||||||
|
"modify-property" { Do-ModifyProperty $opValue }
|
||||||
|
"add-childObject" { Do-AddChildObject $opValue }
|
||||||
|
"remove-childObject" { Do-RemoveChildObject $opValue }
|
||||||
|
"add-defaultRole" { Do-AddDefaultRole $opValue }
|
||||||
|
"remove-defaultRole" { Do-RemoveDefaultRole $opValue }
|
||||||
|
"set-defaultRoles" { Do-SetDefaultRoles $opValue }
|
||||||
|
default { Write-Error "Unknown operation: $opName"; exit 1 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Save ---
|
||||||
|
$settings = New-Object System.Xml.XmlWriterSettings
|
||||||
|
$settings.Encoding = New-Object System.Text.UTF8Encoding($true)
|
||||||
|
$settings.Indent = $false
|
||||||
|
$settings.NewLineHandling = [System.Xml.NewLineHandling]::None
|
||||||
|
|
||||||
|
$memStream = New-Object System.IO.MemoryStream
|
||||||
|
$writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
|
||||||
|
$script:xmlDoc.Save($writer)
|
||||||
|
$writer.Flush(); $writer.Close()
|
||||||
|
|
||||||
|
$bytes = $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"')
|
||||||
|
|
||||||
|
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||||
|
[System.IO.File]::WriteAllText($resolvedPath, $text, $utf8Bom)
|
||||||
|
Info "Saved: $resolvedPath"
|
||||||
|
|
||||||
|
# --- Auto-validate ---
|
||||||
|
if (-not $NoValidate) {
|
||||||
|
$validateScript = Join-Path (Join-Path $PSScriptRoot "..\..\cf-validate") "scripts\cf-validate.ps1"
|
||||||
|
$validateScript = [System.IO.Path]::GetFullPath($validateScript)
|
||||||
|
if (Test-Path $validateScript) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "--- Running cf-validate ---"
|
||||||
|
& powershell.exe -NoProfile -File $validateScript -ConfigPath $resolvedPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Summary ---
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "=== cf-edit summary ==="
|
||||||
|
Write-Host " Configuration: $($script:objName)"
|
||||||
|
Write-Host " Added: $($script:addCount)"
|
||||||
|
Write-Host " Removed: $($script:removeCount)"
|
||||||
|
Write-Host " Modified: $($script:modifyCount)"
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,516 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# cf-edit v1.0 — Edit 1C configuration root (Configuration.xml)
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from html import escape as html_escape
|
||||||
|
from lxml import etree
|
||||||
|
|
||||||
|
MD_NS = "http://v8.1c.ru/8.3/MDClasses"
|
||||||
|
XR_NS = "http://v8.1c.ru/8.3/xcf/readable"
|
||||||
|
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)
|
||||||
|
TYPE_ORDER = [
|
||||||
|
"Language", "Subsystem", "StyleItem", "Style",
|
||||||
|
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
||||||
|
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
|
||||||
|
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
||||||
|
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
||||||
|
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
||||||
|
"Constant", "CommonForm", "Catalog", "Document",
|
||||||
|
"DocumentNumerator", "Sequence", "DocumentJournal", "Enum",
|
||||||
|
"Report", "DataProcessor", "InformationRegister", "AccumulationRegister",
|
||||||
|
"ChartOfCharacteristicTypes", "ChartOfAccounts", "AccountingRegister",
|
||||||
|
"ChartOfCalculationTypes", "CalculationRegister",
|
||||||
|
"BusinessProcess", "Task", "IntegrationService",
|
||||||
|
]
|
||||||
|
|
||||||
|
ML_PROPS = ["Synonym", "BriefInformation", "DetailedInformation", "Copyright", "VendorInformationAddress", "ConfigurationInformationAddress"]
|
||||||
|
SCALAR_PROPS = ["Name", "Version", "Vendor", "Comment", "NamePrefix", "UpdateCatalogAddress"]
|
||||||
|
REF_PROPS = ["DefaultLanguage"]
|
||||||
|
|
||||||
|
|
||||||
|
def localname(el):
|
||||||
|
return etree.QName(el.tag).localname
|
||||||
|
|
||||||
|
|
||||||
|
def info(msg):
|
||||||
|
print(f"[INFO] {msg}")
|
||||||
|
|
||||||
|
|
||||||
|
def warn(msg):
|
||||||
|
print(f"[WARN] {msg}")
|
||||||
|
|
||||||
|
|
||||||
|
def get_child_indent(container):
|
||||||
|
if container.text and "\n" in container.text:
|
||||||
|
after_nl = container.text.rsplit("\n", 1)[-1]
|
||||||
|
if after_nl and not after_nl.strip():
|
||||||
|
return after_nl
|
||||||
|
for child in container:
|
||||||
|
if child.tail and "\n" in child.tail:
|
||||||
|
after_nl = child.tail.rsplit("\n", 1)[-1]
|
||||||
|
if after_nl and not after_nl.strip():
|
||||||
|
return after_nl
|
||||||
|
depth = 0
|
||||||
|
current = container
|
||||||
|
while current is not None:
|
||||||
|
depth += 1
|
||||||
|
current = current.getparent()
|
||||||
|
return "\t" * depth
|
||||||
|
|
||||||
|
|
||||||
|
def insert_before_closing(container, new_el, child_indent):
|
||||||
|
children = list(container)
|
||||||
|
if len(children) == 0:
|
||||||
|
parent_indent = child_indent[:-1] if len(child_indent) > 0 else ""
|
||||||
|
container.text = "\r\n" + child_indent
|
||||||
|
new_el.tail = "\r\n" + parent_indent
|
||||||
|
container.append(new_el)
|
||||||
|
else:
|
||||||
|
last = children[-1]
|
||||||
|
new_el.tail = last.tail
|
||||||
|
last.tail = "\r\n" + child_indent
|
||||||
|
container.append(new_el)
|
||||||
|
|
||||||
|
|
||||||
|
def insert_before_ref(container, new_el, ref_el, child_indent):
|
||||||
|
"""Insert new_el before ref_el inside container."""
|
||||||
|
idx = list(container).index(ref_el)
|
||||||
|
prev = ref_el.getprevious()
|
||||||
|
if prev is not None:
|
||||||
|
new_el.tail = prev.tail
|
||||||
|
prev.tail = "\r\n" + child_indent
|
||||||
|
else:
|
||||||
|
new_el.tail = container.text
|
||||||
|
container.text = "\r\n" + child_indent
|
||||||
|
container.insert(idx, new_el)
|
||||||
|
|
||||||
|
|
||||||
|
def remove_with_indent(el):
|
||||||
|
parent = el.getparent()
|
||||||
|
prev = el.getprevious()
|
||||||
|
if prev is not None:
|
||||||
|
if el.tail:
|
||||||
|
prev.tail = el.tail
|
||||||
|
else:
|
||||||
|
if el.tail:
|
||||||
|
parent.text = el.tail
|
||||||
|
parent.remove(el)
|
||||||
|
|
||||||
|
|
||||||
|
def expand_self_closing(container, parent_indent):
|
||||||
|
if len(container) == 0 and not (container.text and container.text.strip()):
|
||||||
|
container.text = "\r\n" + parent_indent
|
||||||
|
|
||||||
|
|
||||||
|
def import_fragment(xml_string):
|
||||||
|
wrapper = (
|
||||||
|
f'<_W xmlns="{MD_NS}" xmlns:xsi="{XSI_NS}" xmlns:v8="{V8_NS}" '
|
||||||
|
f'xmlns:xr="{XR_NS}" xmlns:xs="{XS_NS}">{xml_string}</_W>'
|
||||||
|
)
|
||||||
|
frag = etree.fromstring(wrapper.encode("utf-8"))
|
||||||
|
return list(frag)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_batch_value(val):
|
||||||
|
items = []
|
||||||
|
for part in val.split(";;"):
|
||||||
|
trimmed = part.strip()
|
||||||
|
if trimmed:
|
||||||
|
items.append(trimmed)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def save_xml_bom(tree, path):
|
||||||
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
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="Edit 1C configuration root (Configuration.xml)", allow_abbrev=False)
|
||||||
|
parser.add_argument("-ConfigPath", 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"])
|
||||||
|
parser.add_argument("-Value", default=None)
|
||||||
|
parser.add_argument("-NoValidate", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if args.DefinitionFile and args.Operation:
|
||||||
|
print("Cannot use both -DefinitionFile and -Operation", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if not args.DefinitionFile and not args.Operation:
|
||||||
|
print("Either -DefinitionFile or -Operation is required", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
config_path = args.ConfigPath
|
||||||
|
if not os.path.isabs(config_path):
|
||||||
|
config_path = os.path.join(os.getcwd(), config_path)
|
||||||
|
if os.path.isdir(config_path):
|
||||||
|
candidate = os.path.join(config_path, "Configuration.xml")
|
||||||
|
if os.path.isfile(candidate):
|
||||||
|
config_path = candidate
|
||||||
|
else:
|
||||||
|
print("No Configuration.xml in directory", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
if not os.path.isfile(config_path):
|
||||||
|
print(f"File not found: {config_path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
resolved_path = os.path.abspath(config_path)
|
||||||
|
|
||||||
|
xml_parser = etree.XMLParser(remove_blank_text=False)
|
||||||
|
tree = etree.parse(resolved_path, xml_parser)
|
||||||
|
xml_root = tree.getroot()
|
||||||
|
|
||||||
|
add_count = 0
|
||||||
|
remove_count = 0
|
||||||
|
modify_count = 0
|
||||||
|
|
||||||
|
cfg_el = None
|
||||||
|
for child in xml_root:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == "Configuration":
|
||||||
|
cfg_el = child
|
||||||
|
break
|
||||||
|
if cfg_el is None:
|
||||||
|
print("No <Configuration> element found", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
props_el = None
|
||||||
|
child_objs_el = None
|
||||||
|
for child in cfg_el:
|
||||||
|
if not isinstance(child.tag, str):
|
||||||
|
continue
|
||||||
|
if localname(child) == "Properties":
|
||||||
|
props_el = child
|
||||||
|
if localname(child) == "ChildObjects":
|
||||||
|
child_objs_el = child
|
||||||
|
|
||||||
|
obj_name = ""
|
||||||
|
if props_el is not None:
|
||||||
|
for child in props_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == "Name":
|
||||||
|
obj_name = (child.text or "").strip()
|
||||||
|
break
|
||||||
|
info(f"Configuration: {obj_name}")
|
||||||
|
|
||||||
|
# --- Operations ---
|
||||||
|
def do_modify_property(batch_val):
|
||||||
|
nonlocal modify_count
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
for item in items:
|
||||||
|
eq_idx = item.find("=")
|
||||||
|
if eq_idx < 1:
|
||||||
|
print(f"Invalid property format '{item}', expected 'Key=Value'", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
prop_name = item[:eq_idx].strip()
|
||||||
|
prop_value = item[eq_idx + 1:].strip()
|
||||||
|
|
||||||
|
prop_el = None
|
||||||
|
for child in props_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == prop_name:
|
||||||
|
prop_el = child
|
||||||
|
break
|
||||||
|
if prop_el is None:
|
||||||
|
print(f"Property '{prop_name}' not found in Properties", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if prop_name in ML_PROPS:
|
||||||
|
for ch in list(prop_el):
|
||||||
|
prop_el.remove(ch)
|
||||||
|
if not prop_value:
|
||||||
|
prop_el.text = None
|
||||||
|
else:
|
||||||
|
indent = get_child_indent(props_el)
|
||||||
|
item_el = etree.SubElement(prop_el, f"{{{V8_NS}}}item")
|
||||||
|
lang_el = etree.SubElement(item_el, f"{{{V8_NS}}}lang")
|
||||||
|
lang_el.text = "ru"
|
||||||
|
content_el = etree.SubElement(item_el, f"{{{V8_NS}}}content")
|
||||||
|
content_el.text = prop_value
|
||||||
|
prop_el.text = "\r\n" + indent + "\t"
|
||||||
|
item_el.text = "\r\n" + indent + "\t\t"
|
||||||
|
lang_el.tail = "\r\n" + indent + "\t\t"
|
||||||
|
content_el.tail = "\r\n" + indent + "\t"
|
||||||
|
item_el.tail = "\r\n" + indent
|
||||||
|
elif prop_name in SCALAR_PROPS or prop_name in REF_PROPS:
|
||||||
|
for ch in list(prop_el):
|
||||||
|
prop_el.remove(ch)
|
||||||
|
if not prop_value:
|
||||||
|
prop_el.text = None
|
||||||
|
else:
|
||||||
|
prop_el.text = prop_value
|
||||||
|
else:
|
||||||
|
for ch in list(prop_el):
|
||||||
|
prop_el.remove(ch)
|
||||||
|
prop_el.text = prop_value
|
||||||
|
|
||||||
|
modify_count += 1
|
||||||
|
info(f'Set {prop_name} = "{prop_value}"')
|
||||||
|
|
||||||
|
def do_add_child_object(batch_val):
|
||||||
|
nonlocal add_count
|
||||||
|
if child_objs_el is None:
|
||||||
|
print("No <ChildObjects> element found", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
cfg_indent = get_child_indent(cfg_el)
|
||||||
|
if len(child_objs_el) == 0 and not (child_objs_el.text and child_objs_el.text.strip()):
|
||||||
|
expand_self_closing(child_objs_el, cfg_indent)
|
||||||
|
child_indent = get_child_indent(child_objs_el)
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
dot_idx = item.find(".")
|
||||||
|
if dot_idx < 1:
|
||||||
|
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
type_name = item[:dot_idx]
|
||||||
|
obj_name_val = item[dot_idx + 1:]
|
||||||
|
|
||||||
|
if type_name not in TYPE_ORDER:
|
||||||
|
print(f"Unknown type '{type_name}'", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
type_idx = TYPE_ORDER.index(type_name)
|
||||||
|
|
||||||
|
# Dedup
|
||||||
|
exists = False
|
||||||
|
for child in child_objs_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == type_name and (child.text or "") == obj_name_val:
|
||||||
|
exists = True
|
||||||
|
break
|
||||||
|
if exists:
|
||||||
|
warn(f"Already exists: {type_name}.{obj_name_val}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Find insertion point
|
||||||
|
insert_before = None
|
||||||
|
for child in child_objs_el:
|
||||||
|
if not isinstance(child.tag, str):
|
||||||
|
continue
|
||||||
|
child_type_name = localname(child)
|
||||||
|
if child_type_name not in TYPE_ORDER:
|
||||||
|
continue
|
||||||
|
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:
|
||||||
|
insert_before = child
|
||||||
|
elif child_type_idx > type_idx and insert_before is None:
|
||||||
|
insert_before = child
|
||||||
|
|
||||||
|
new_el = etree.Element(f"{{{MD_NS}}}{type_name}")
|
||||||
|
new_el.text = obj_name_val
|
||||||
|
|
||||||
|
if insert_before is not None:
|
||||||
|
insert_before_ref(child_objs_el, new_el, insert_before, child_indent)
|
||||||
|
else:
|
||||||
|
insert_before_closing(child_objs_el, new_el, child_indent)
|
||||||
|
|
||||||
|
add_count += 1
|
||||||
|
info(f"Added: {type_name}.{obj_name_val}")
|
||||||
|
|
||||||
|
def do_remove_child_object(batch_val):
|
||||||
|
nonlocal remove_count
|
||||||
|
if child_objs_el is None:
|
||||||
|
print("No <ChildObjects> element found", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
for item in items:
|
||||||
|
dot_idx = item.find(".")
|
||||||
|
if dot_idx < 1:
|
||||||
|
print(f"Invalid format '{item}', expected 'Type.Name'", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
type_name = item[:dot_idx]
|
||||||
|
obj_name_val = item[dot_idx + 1:]
|
||||||
|
|
||||||
|
found = False
|
||||||
|
for child in list(child_objs_el):
|
||||||
|
if isinstance(child.tag, str) and localname(child) == type_name and (child.text or "") == obj_name_val:
|
||||||
|
remove_with_indent(child)
|
||||||
|
remove_count += 1
|
||||||
|
info(f"Removed: {type_name}.{obj_name_val}")
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found:
|
||||||
|
warn(f"Not found: {type_name}.{obj_name_val}")
|
||||||
|
|
||||||
|
def do_add_default_role(batch_val):
|
||||||
|
nonlocal add_count
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
|
||||||
|
roles_el = None
|
||||||
|
for child in props_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
|
||||||
|
roles_el = child
|
||||||
|
break
|
||||||
|
if roles_el is None:
|
||||||
|
print("No <DefaultRoles> element found in Properties", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
props_indent = get_child_indent(props_el)
|
||||||
|
if len(roles_el) == 0 and not (roles_el.text and roles_el.text.strip()):
|
||||||
|
expand_self_closing(roles_el, props_indent)
|
||||||
|
role_indent = get_child_indent(roles_el)
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
role_name = item
|
||||||
|
if not role_name.startswith("Role."):
|
||||||
|
role_name = f"Role.{role_name}"
|
||||||
|
|
||||||
|
exists = False
|
||||||
|
for child in roles_el:
|
||||||
|
if isinstance(child.tag, str) and (child.text or "").strip() == role_name:
|
||||||
|
exists = True
|
||||||
|
break
|
||||||
|
if exists:
|
||||||
|
warn(f"DefaultRole already exists: {role_name}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
frag_xml = f'<xr:Item xsi:type="xr:MDObjectRef">{role_name}</xr:Item>'
|
||||||
|
nodes = import_fragment(frag_xml)
|
||||||
|
if nodes:
|
||||||
|
insert_before_closing(roles_el, nodes[0], role_indent)
|
||||||
|
add_count += 1
|
||||||
|
info(f"Added DefaultRole: {role_name}")
|
||||||
|
|
||||||
|
def do_remove_default_role(batch_val):
|
||||||
|
nonlocal remove_count
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
|
||||||
|
roles_el = None
|
||||||
|
for child in props_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
|
||||||
|
roles_el = child
|
||||||
|
break
|
||||||
|
if roles_el is None:
|
||||||
|
print("No <DefaultRoles> element found", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
role_name = item
|
||||||
|
if not role_name.startswith("Role."):
|
||||||
|
role_name = f"Role.{role_name}"
|
||||||
|
|
||||||
|
found = False
|
||||||
|
for child in list(roles_el):
|
||||||
|
if isinstance(child.tag, str) and (child.text or "").strip() == role_name:
|
||||||
|
remove_with_indent(child)
|
||||||
|
remove_count += 1
|
||||||
|
info(f"Removed DefaultRole: {role_name}")
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found:
|
||||||
|
warn(f"DefaultRole not found: {role_name}")
|
||||||
|
|
||||||
|
def do_set_default_roles(batch_val):
|
||||||
|
nonlocal modify_count
|
||||||
|
items = parse_batch_value(batch_val)
|
||||||
|
|
||||||
|
roles_el = None
|
||||||
|
for child in props_el:
|
||||||
|
if isinstance(child.tag, str) and localname(child) == "DefaultRoles":
|
||||||
|
roles_el = child
|
||||||
|
break
|
||||||
|
if roles_el is None:
|
||||||
|
print("No <DefaultRoles> element found", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Clear all existing children
|
||||||
|
for ch in list(roles_el):
|
||||||
|
roles_el.remove(ch)
|
||||||
|
roles_el.text = None
|
||||||
|
|
||||||
|
if not items:
|
||||||
|
modify_count += 1
|
||||||
|
info("Cleared DefaultRoles")
|
||||||
|
return
|
||||||
|
|
||||||
|
props_indent = get_child_indent(props_el)
|
||||||
|
role_indent = props_indent + "\t"
|
||||||
|
|
||||||
|
roles_el.text = "\r\n" + props_indent
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
role_name = item
|
||||||
|
if not role_name.startswith("Role."):
|
||||||
|
role_name = f"Role.{role_name}"
|
||||||
|
|
||||||
|
frag_xml = f'<xr:Item xsi:type="xr:MDObjectRef">{role_name}</xr:Item>'
|
||||||
|
nodes = import_fragment(frag_xml)
|
||||||
|
if nodes:
|
||||||
|
insert_before_closing(roles_el, nodes[0], role_indent)
|
||||||
|
|
||||||
|
modify_count += 1
|
||||||
|
info(f"Set DefaultRoles: {len(items)} roles")
|
||||||
|
|
||||||
|
# --- Execute operations ---
|
||||||
|
operations = []
|
||||||
|
if args.DefinitionFile:
|
||||||
|
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())
|
||||||
|
if isinstance(ops, list):
|
||||||
|
operations = ops
|
||||||
|
else:
|
||||||
|
operations = [ops]
|
||||||
|
else:
|
||||||
|
operations = [{"operation": args.Operation, "value": args.Value or ""}]
|
||||||
|
|
||||||
|
for op in operations:
|
||||||
|
op_name = op.get("operation", args.Operation or "")
|
||||||
|
op_value = op.get("value", args.Value or "")
|
||||||
|
|
||||||
|
if op_name == "modify-property":
|
||||||
|
do_modify_property(op_value)
|
||||||
|
elif op_name == "add-childObject":
|
||||||
|
do_add_child_object(op_value)
|
||||||
|
elif op_name == "remove-childObject":
|
||||||
|
do_remove_child_object(op_value)
|
||||||
|
elif op_name == "add-defaultRole":
|
||||||
|
do_add_default_role(op_value)
|
||||||
|
elif op_name == "remove-defaultRole":
|
||||||
|
do_remove_default_role(op_value)
|
||||||
|
elif op_name == "set-defaultRoles":
|
||||||
|
do_set_default_roles(op_value)
|
||||||
|
else:
|
||||||
|
print(f"Unknown operation: {op_name}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Save ---
|
||||||
|
save_xml_bom(tree, resolved_path)
|
||||||
|
info(f"Saved: {resolved_path}")
|
||||||
|
|
||||||
|
# --- Auto-validate ---
|
||||||
|
if not args.NoValidate:
|
||||||
|
validate_script = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..", "cf-validate", "scripts", "cf-validate.py"))
|
||||||
|
if os.path.isfile(validate_script):
|
||||||
|
print()
|
||||||
|
print("--- Running cf-validate ---")
|
||||||
|
subprocess.run([sys.executable, validate_script, "-ConfigPath", resolved_path])
|
||||||
|
|
||||||
|
# --- Summary ---
|
||||||
|
print()
|
||||||
|
print("=== cf-edit summary ===")
|
||||||
|
print(f" Configuration: {obj_name}")
|
||||||
|
print(f" Added: {add_count}")
|
||||||
|
print(f" Removed: {remove_count}")
|
||||||
|
print(f" Modified: {modify_count}")
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: cf-info
|
name: cf-info
|
||||||
description: Анализ структуры конфигурации 1С — свойства, состав, счётчики объектов. Используй для обзора конфигурации — какие объекты есть, сколько их, какие настройки
|
description: Анализ структуры конфигурации 1С — свойства, состав, счётчики объектов. Используй для обзора конфигурации — какие объекты есть, сколько их, какие настройки
|
||||||
argument-hint: <ConfigPath> [-Mode overview|brief|full] [-Section home-page]
|
argument-hint: <ConfigPath> [-Mode overview|brief|full]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
- Read
|
- Read
|
||||||
@@ -18,12 +18,11 @@ allowed-tools:
|
|||||||
|----------|----------|
|
|----------|----------|
|
||||||
| `ConfigPath` | Путь к Configuration.xml или каталогу выгрузки |
|
| `ConfigPath` | Путь к Configuration.xml или каталогу выгрузки |
|
||||||
| `Mode` | Режим: `overview` (default), `brief`, `full` |
|
| `Mode` | Режим: `overview` (default), `brief`, `full` |
|
||||||
| `Section` | Drill-down по разделу (alias: `Name`). Сейчас: `home-page` |
|
|
||||||
| `Limit` / `Offset` | Пагинация (по умолчанию 150 строк) |
|
| `Limit` / `Offset` | Пагинация (по умолчанию 150 строк) |
|
||||||
| `OutFile` | Записать результат в файл (UTF-8 BOM) |
|
| `OutFile` | Записать результат в файл (UTF-8 BOM) |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cf-info/scripts/cf-info.py" -ConfigPath "<путь>"
|
powershell.exe -NoProfile -File .claude/skills/cf-info/scripts/cf-info.ps1 -ConfigPath "<путь>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Три режима
|
## Три режима
|
||||||
@@ -38,17 +37,14 @@ python ".opencode/skills/cf-info/scripts/cf-info.py" -ConfigPath "<путь>"
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Обзор пустой конфигурации
|
# Обзор пустой конфигурации
|
||||||
... -ConfigPath src
|
... -ConfigPath upload/cfempty
|
||||||
|
|
||||||
# Краткая сводка реальной конфигурации
|
# Краткая сводка реальной конфигурации
|
||||||
... -ConfigPath src -Mode brief
|
... -ConfigPath upload/acc_8.3.24 -Mode brief
|
||||||
|
|
||||||
# Полная информация
|
# Полная информация
|
||||||
... -ConfigPath src -Mode full
|
... -ConfigPath upload/acc_8.3.24 -Mode full
|
||||||
|
|
||||||
# С пагинацией
|
# С пагинацией
|
||||||
... -ConfigPath src -Mode full -Limit 50 -Offset 100
|
... -ConfigPath upload/acc_8.3.24 -Mode full -Limit 50 -Offset 100
|
||||||
|
|
||||||
# Drill-down: только начальная страница (раскладка форм с ролями)
|
|
||||||
... -ConfigPath src -Section home-page
|
|
||||||
```
|
```
|
||||||
+5
-272
@@ -1,12 +1,9 @@
|
|||||||
# cf-info v1.3 — Compact summary of 1C configuration root
|
# cf-info v1.0 — Compact summary of 1C configuration root
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory=$true)][Alias('Path')][string]$ConfigPath,
|
[Parameter(Mandatory=$true)][string]$ConfigPath,
|
||||||
[ValidateSet("overview","brief","full")]
|
[ValidateSet("overview","brief","full")]
|
||||||
[string]$Mode = "overview",
|
[string]$Mode = "overview",
|
||||||
[Alias('Name')]
|
|
||||||
[ValidateSet("home-page")]
|
|
||||||
[string]$Section,
|
|
||||||
[int]$Limit = 150,
|
[int]$Limit = 150,
|
||||||
[int]$Offset = 0,
|
[int]$Offset = 0,
|
||||||
[string]$OutFile
|
[string]$OutFile
|
||||||
@@ -121,187 +118,6 @@ $typeRuNames = @{
|
|||||||
"Task"="Задачи"; "IntegrationService"="Сервисы интеграции"
|
"Task"="Задачи"; "IntegrationService"="Сервисы интеграции"
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Read panel layout (Ext/ClientApplicationInterface.xml) ---
|
|
||||||
$script:panelNames = @{
|
|
||||||
"cbab57f2-a0f3-4f0a-89ea-4cb19570ab75" = "Открытых"
|
|
||||||
"b553047f-c9aa-4157-978d-448ecad24248" = "Разделов"
|
|
||||||
"13322b22-3960-4d68-93a6-fe2dd7f28ca3" = "Избранного"
|
|
||||||
"c933ac92-92cd-459d-81cc-e0c8a83ced99" = "История"
|
|
||||||
"b2735bd3-d822-4430-ba59-c9e869693b24" = "Функций"
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-PanelsLayout {
|
|
||||||
$configDir = [System.IO.Path]::GetDirectoryName($ConfigPath)
|
|
||||||
$caiPath = Join-Path (Join-Path $configDir "Ext") "ClientApplicationInterface.xml"
|
|
||||||
if (-not (Test-Path $caiPath)) { return $null }
|
|
||||||
try { [xml]$caiDoc = Get-Content -Path $caiPath -Encoding UTF8 } catch { return $null }
|
|
||||||
if (-not $caiDoc.DocumentElement) { return $null }
|
|
||||||
$caiNs = New-Object System.Xml.XmlNamespaceManager($caiDoc.NameTable)
|
|
||||||
$caiNs.AddNamespace("ca", "http://v8.1c.ru/8.2/managed-application/core")
|
|
||||||
$layout = [ordered]@{ top=@(); left=@(); right=@(); bottom=@(); declared=@() }
|
|
||||||
foreach ($side in @("top","left","right","bottom")) {
|
|
||||||
foreach ($sideEl in $caiDoc.DocumentElement.SelectNodes("ca:$side", $caiNs)) {
|
|
||||||
$slot = @()
|
|
||||||
foreach ($u in $sideEl.SelectNodes(".//ca:panel/ca:uuid", $caiNs)) {
|
|
||||||
$key = $u.InnerText.Trim()
|
|
||||||
$nm = if ($script:panelNames.Contains($key)) { $script:panelNames[$key] } else { "?$key" }
|
|
||||||
$slot += $nm
|
|
||||||
}
|
|
||||||
if ($slot.Count -gt 0) { $layout[$side] += ,$slot }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach ($pd in $caiDoc.DocumentElement.SelectNodes("ca:panelDef", $caiNs)) {
|
|
||||||
$key = $pd.GetAttribute("id")
|
|
||||||
$nm = if ($script:panelNames.Contains($key)) { $script:panelNames[$key] } else { "?$key" }
|
|
||||||
$layout.declared += $nm
|
|
||||||
}
|
|
||||||
return $layout
|
|
||||||
}
|
|
||||||
|
|
||||||
function Format-LayoutSlots($slots) {
|
|
||||||
# slots is array of arrays (each inner array = one side-tag's panels, may be 1+)
|
|
||||||
# Single inner array, single panel -> just name
|
|
||||||
# Single inner array, multiple panels -> "Стек(a, b)"
|
|
||||||
# Multiple inner arrays -> separate entries joined by " | "
|
|
||||||
if (-not $slots -or $slots.Count -eq 0) { return "" }
|
|
||||||
$parts = @()
|
|
||||||
foreach ($slot in $slots) {
|
|
||||||
if ($slot.Count -eq 1) { $parts += $slot[0] }
|
|
||||||
else { $parts += ("Стек(" + ($slot -join ", ") + ")") }
|
|
||||||
}
|
|
||||||
return ($parts -join " | ")
|
|
||||||
}
|
|
||||||
|
|
||||||
$script:panelLayout = Get-PanelsLayout
|
|
||||||
|
|
||||||
# --- Read home page layout (Ext/HomePageWorkArea.xml) ---
|
|
||||||
function Get-HomePageLayout {
|
|
||||||
$configDir = [System.IO.Path]::GetDirectoryName($ConfigPath)
|
|
||||||
$hpPath = Join-Path (Join-Path $configDir "Ext") "HomePageWorkArea.xml"
|
|
||||||
if (-not (Test-Path $hpPath)) { return $null }
|
|
||||||
try { [xml]$hpDoc = Get-Content -Path $hpPath -Encoding UTF8 } catch { return $null }
|
|
||||||
if (-not $hpDoc.DocumentElement) { return $null }
|
|
||||||
$hpNs = New-Object System.Xml.XmlNamespaceManager($hpDoc.NameTable)
|
|
||||||
$hpNs.AddNamespace("hp", "http://v8.1c.ru/8.3/xcf/extrnprops")
|
|
||||||
$hpNs.AddNamespace("xr", "http://v8.1c.ru/8.3/xcf/readable")
|
|
||||||
$result = [ordered]@{ template = ""; left = @(); right = @() }
|
|
||||||
$tmplNode = $hpDoc.DocumentElement.SelectSingleNode("hp:WorkingAreaTemplate", $hpNs)
|
|
||||||
if ($tmplNode) { $result.template = $tmplNode.InnerText.Trim() }
|
|
||||||
foreach ($colName in @("LeftColumn","RightColumn")) {
|
|
||||||
$colNode = $hpDoc.DocumentElement.SelectSingleNode("hp:$colName", $hpNs)
|
|
||||||
if (-not $colNode) { continue }
|
|
||||||
$items = @()
|
|
||||||
foreach ($item in $colNode.SelectNodes("hp:Item", $hpNs)) {
|
|
||||||
$f = $item.SelectSingleNode("hp:Form", $hpNs)
|
|
||||||
$h = $item.SelectSingleNode("hp:Height", $hpNs)
|
|
||||||
$visNode = $item.SelectSingleNode("hp:Visibility", $hpNs)
|
|
||||||
$common = $true
|
|
||||||
$roles = @()
|
|
||||||
if ($visNode) {
|
|
||||||
$cn = $visNode.SelectSingleNode("xr:Common", $hpNs)
|
|
||||||
if ($cn) { $common = ($cn.InnerText.Trim() -eq "true") }
|
|
||||||
foreach ($v in $visNode.SelectNodes("xr:Value", $hpNs)) {
|
|
||||||
$roles += @{ name = $v.GetAttribute("name"); value = ($v.InnerText.Trim() -eq "true") }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$items += [ordered]@{
|
|
||||||
form = if ($f) { $f.InnerText.Trim() } else { "" }
|
|
||||||
height = if ($h) { [int]$h.InnerText.Trim() } else { 10 }
|
|
||||||
common = $common
|
|
||||||
roles = $roles
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($colName -eq "LeftColumn") { $result.left = $items } else { $result.right = $items }
|
|
||||||
}
|
|
||||||
return $result
|
|
||||||
}
|
|
||||||
|
|
||||||
$script:homePage = Get-HomePageLayout
|
|
||||||
|
|
||||||
# --- Support state (Ext/ParentConfigurations.bin) ---
|
|
||||||
# Decodes the 1C support-state file. See docs/1c-support-state-spec.md.
|
|
||||||
# Returns $null on absent/error; else hashtable: State='absent'|'removed'|'parsed',
|
|
||||||
# G (0=editing on, 1=off), K (vendor configs), Vendors @(@{Vendor;Name;Version}),
|
|
||||||
# Counts @(locked, editable, removed) by f1 — record tally (K>1 counts each
|
|
||||||
# vendor block separately); only computed when G=0.
|
|
||||||
function Read-SupportState([string]$binPath) {
|
|
||||||
try {
|
|
||||||
if (-not (Test-Path $binPath)) { return @{ State = 'absent' } }
|
|
||||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
|
||||||
if ($bytes.Length -le 32) { return @{ State = 'removed' } }
|
|
||||||
$startIdx = 0
|
|
||||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $startIdx = 3 }
|
|
||||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $startIdx, $bytes.Length - $startIdx)
|
|
||||||
$h = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
|
||||||
if (-not $h.Success) { return $null }
|
|
||||||
$G = [int]$h.Groups[1].Value
|
|
||||||
$K = [int]$h.Groups[2].Value
|
|
||||||
if ($K -eq 0) { return @{ State = 'removed' } }
|
|
||||||
# Vendor descriptors: ...,"ver","vendor","name",count,
|
|
||||||
$vendors = @()
|
|
||||||
$vRe = [regex]'"((?:[^"]|"")*)","((?:[^"]|"")*)","((?:[^"]|"")*)",\d+,'
|
|
||||||
foreach ($m in $vRe.Matches($text)) {
|
|
||||||
$vendors += @{
|
|
||||||
Version = ($m.Groups[1].Value -replace '""','"')
|
|
||||||
Vendor = ($m.Groups[2].Value -replace '""','"')
|
|
||||||
Name = ($m.Groups[3].Value -replace '""','"')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
# Per-object counts only matter when editing is enabled (G=0); when G=1 the
|
|
||||||
# whole config is read-only and stored f1 values are the inactive default.
|
|
||||||
$counts = $null
|
|
||||||
if ($G -eq 0) {
|
|
||||||
$counts = @(0, 0, 0)
|
|
||||||
# Object records: f1,0,uuidLocal[,uuidVendor] — flags precede the uuid.
|
|
||||||
$rRe = [regex]'([0-2]),0,[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
|
|
||||||
foreach ($m in $rRe.Matches($text)) {
|
|
||||||
$counts[[int]$m.Groups[1].Value]++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return @{ State = 'parsed'; G = $G; K = $K; Vendors = $vendors; Counts = $counts }
|
|
||||||
} catch { return $null }
|
|
||||||
}
|
|
||||||
|
|
||||||
function Get-SupportLines {
|
|
||||||
$configDir = [System.IO.Path]::GetDirectoryName($ConfigPath)
|
|
||||||
$binPath = Join-Path (Join-Path $configDir "Ext") "ParentConfigurations.bin"
|
|
||||||
$st = Read-SupportState $binPath
|
|
||||||
$out = @()
|
|
||||||
if (-not $st -or $st.State -eq 'absent') {
|
|
||||||
if ($cfgExtPurpose) { $out += "Поддержка: расширение (CFE), правки свободны" }
|
|
||||||
else { $out += "Поддержка: не на поддержке (своя конфигурация)" }
|
|
||||||
return $out
|
|
||||||
}
|
|
||||||
if ($st.State -eq 'removed') {
|
|
||||||
$out += "Поддержка: снята с поддержки полностью"
|
|
||||||
return $out
|
|
||||||
}
|
|
||||||
$out += "Поддержка: на поддержке"
|
|
||||||
if ($st.G -eq 0) {
|
|
||||||
$out += " Возможность изменения: включена"
|
|
||||||
$out += " Объектов: на замке $($st.Counts[0]) / редактируется $($st.Counts[1]) / снято $($st.Counts[2])"
|
|
||||||
} else {
|
|
||||||
$out += " Возможность изменения: выключена — вся конфигурация read-only (правки заблокированы)"
|
|
||||||
}
|
|
||||||
$out += " Конфигураций поставщика: $($st.K)"
|
|
||||||
if ($st.K -gt 1) {
|
|
||||||
foreach ($v in $st.Vendors) { $out += " Поставщик: $($v.Vendor) — $($v.Name) $($v.Version)" }
|
|
||||||
}
|
|
||||||
return $out
|
|
||||||
}
|
|
||||||
|
|
||||||
function Format-HomePageItem($it, [bool]$detailed) {
|
|
||||||
$badges = @()
|
|
||||||
$badges += "h=$($it.height)"
|
|
||||||
if (-not $it.common) { $badges += "скрыта" }
|
|
||||||
if ($it.roles.Count -gt 0) {
|
|
||||||
if ($detailed) { $badges += "роли: $($it.roles.Count)" }
|
|
||||||
else { $badges += "+$($it.roles.Count) ролей" }
|
|
||||||
}
|
|
||||||
$tail = if ($badges.Count -gt 0) { " (" + ($badges -join ", ") + ")" } else { "" }
|
|
||||||
return " $($it.form)$tail"
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Count objects in ChildObjects ---
|
# --- Count objects in ChildObjects ---
|
||||||
$objectCounts = [ordered]@{}
|
$objectCounts = [ordered]@{}
|
||||||
$totalObjects = 0
|
$totalObjects = 0
|
||||||
@@ -325,7 +141,6 @@ $cfgVersion = Get-PropText "Version"
|
|||||||
$cfgVendor = Get-PropText "Vendor"
|
$cfgVendor = Get-PropText "Vendor"
|
||||||
$cfgCompat = Get-PropText "CompatibilityMode"
|
$cfgCompat = Get-PropText "CompatibilityMode"
|
||||||
$cfgExtCompat = Get-PropText "ConfigurationExtensionCompatibilityMode"
|
$cfgExtCompat = Get-PropText "ConfigurationExtensionCompatibilityMode"
|
||||||
$cfgExtPurpose = Get-PropText "ConfigurationExtensionPurpose"
|
|
||||||
$cfgDefaultRun = Get-PropText "DefaultRunMode"
|
$cfgDefaultRun = Get-PropText "DefaultRunMode"
|
||||||
$cfgScript = Get-PropText "ScriptVariant"
|
$cfgScript = Get-PropText "ScriptVariant"
|
||||||
$cfgDefaultLang = Get-PropText "DefaultLanguage"
|
$cfgDefaultLang = Get-PropText "DefaultLanguage"
|
||||||
@@ -339,7 +154,7 @@ $cfgDbSpaces = Get-PropText "DatabaseTablespacesUseMode"
|
|||||||
$cfgWindowMode = Get-PropText "MainClientApplicationWindowMode"
|
$cfgWindowMode = Get-PropText "MainClientApplicationWindowMode"
|
||||||
|
|
||||||
# --- BRIEF mode ---
|
# --- BRIEF mode ---
|
||||||
if ($Mode -eq "brief" -and -not $Section) {
|
if ($Mode -eq "brief") {
|
||||||
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
||||||
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
||||||
$compatPart = if ($cfgCompat) { " | $cfgCompat" } else { "" }
|
$compatPart = if ($cfgCompat) { " | $cfgCompat" } else { "" }
|
||||||
@@ -347,7 +162,7 @@ if ($Mode -eq "brief" -and -not $Section) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# --- OVERVIEW mode ---
|
# --- OVERVIEW mode ---
|
||||||
if ($Mode -eq "overview" -and -not $Section) {
|
if ($Mode -eq "overview") {
|
||||||
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
||||||
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
||||||
Out "=== Конфигурация: ${cfgName}${synPart}${verPart} ==="
|
Out "=== Конфигурация: ${cfgName}${synPart}${verPart} ==="
|
||||||
@@ -357,7 +172,6 @@ if ($Mode -eq "overview" -and -not $Section) {
|
|||||||
Out "Формат: $version"
|
Out "Формат: $version"
|
||||||
if ($cfgVendor) { Out "Поставщик: $cfgVendor" }
|
if ($cfgVendor) { Out "Поставщик: $cfgVendor" }
|
||||||
if ($cfgVersion) { Out "Версия: $cfgVersion" }
|
if ($cfgVersion) { Out "Версия: $cfgVersion" }
|
||||||
foreach ($l in (Get-SupportLines)) { Out $l }
|
|
||||||
Out "Совместимость: $cfgCompat"
|
Out "Совместимость: $cfgCompat"
|
||||||
Out "Режим запуска: $cfgDefaultRun"
|
Out "Режим запуска: $cfgDefaultRun"
|
||||||
Out "Язык скриптов: $cfgScript"
|
Out "Язык скриптов: $cfgScript"
|
||||||
@@ -367,33 +181,6 @@ if ($Mode -eq "overview" -and -not $Section) {
|
|||||||
Out "Интерфейс: $cfgIntfCompat"
|
Out "Интерфейс: $cfgIntfCompat"
|
||||||
Out ""
|
Out ""
|
||||||
|
|
||||||
# Panel layout (if file exists)
|
|
||||||
if ($script:panelLayout) {
|
|
||||||
$hasPlaced = $false
|
|
||||||
foreach ($s in @("top","left","right","bottom")) {
|
|
||||||
if ($script:panelLayout[$s].Count -gt 0) { $hasPlaced = $true; break }
|
|
||||||
}
|
|
||||||
if ($hasPlaced) {
|
|
||||||
Out "--- Раскладка панелей ---"
|
|
||||||
foreach ($s in @("top","left","right","bottom")) {
|
|
||||||
if ($script:panelLayout[$s].Count -gt 0) {
|
|
||||||
Out " $($s.PadRight(7)) $(Format-LayoutSlots $script:panelLayout[$s])"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Out ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Home page layout (brief summary)
|
|
||||||
if ($script:homePage) {
|
|
||||||
$ln = $script:homePage.left.Count
|
|
||||||
$rn = $script:homePage.right.Count
|
|
||||||
Out "--- Начальная страница ---"
|
|
||||||
Out " Шаблон: $($script:homePage.template)"
|
|
||||||
Out " LeftColumn: $ln, RightColumn: $rn (детали: -Section home-page)"
|
|
||||||
Out ""
|
|
||||||
}
|
|
||||||
|
|
||||||
# Object counts table
|
# Object counts table
|
||||||
Out "--- Состав ($totalObjects объектов) ---"
|
Out "--- Состав ($totalObjects объектов) ---"
|
||||||
Out ""
|
Out ""
|
||||||
@@ -416,34 +203,8 @@ if ($Mode -eq "overview" -and -not $Section) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Drill-down: -Section home-page ---
|
|
||||||
if ($Section -eq "home-page") {
|
|
||||||
if (-not $script:homePage) {
|
|
||||||
Out "Файл Ext/HomePageWorkArea.xml не найден"
|
|
||||||
} else {
|
|
||||||
Out "=== Начальная страница: $cfgName ==="
|
|
||||||
Out ""
|
|
||||||
Out "Шаблон: $($script:homePage.template)"
|
|
||||||
Out ""
|
|
||||||
foreach ($side in @(@("LeftColumn","left"), @("RightColumn","right"))) {
|
|
||||||
$items = $script:homePage[$side[1]]
|
|
||||||
$lbl = $side[0]
|
|
||||||
if ($items.Count -eq 0) { Out "${lbl}: —"; Out ""; continue }
|
|
||||||
Out "${lbl} ($($items.Count)):"
|
|
||||||
foreach ($it in $items) {
|
|
||||||
Out (Format-HomePageItem $it $true)
|
|
||||||
foreach ($r in $it.roles) {
|
|
||||||
$rval = if ($r.value) { "true" } else { "false" }
|
|
||||||
Out " $($r.name): $rval"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Out ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- FULL mode ---
|
# --- FULL mode ---
|
||||||
if ($Mode -eq "full" -and -not $Section) {
|
if ($Mode -eq "full") {
|
||||||
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
$synPart = if ($cfgSynonym) { " $dash `"$cfgSynonym`"" } else { "" }
|
||||||
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
$verPart = if ($cfgVersion) { " v$cfgVersion" } else { "" }
|
||||||
Out "=== Конфигурация: ${cfgName}${synPart}${verPart} ==="
|
Out "=== Конфигурация: ${cfgName}${synPart}${verPart} ==="
|
||||||
@@ -460,7 +221,6 @@ if ($Mode -eq "full" -and -not $Section) {
|
|||||||
if ($cfgPrefix) { Out "Префикс: $cfgPrefix" }
|
if ($cfgPrefix) { Out "Префикс: $cfgPrefix" }
|
||||||
if ($cfgVendor) { Out "Поставщик: $cfgVendor" }
|
if ($cfgVendor) { Out "Поставщик: $cfgVendor" }
|
||||||
if ($cfgVersion) { Out "Версия: $cfgVersion" }
|
if ($cfgVersion) { Out "Версия: $cfgVersion" }
|
||||||
foreach ($l in (Get-SupportLines)) { Out $l }
|
|
||||||
$cfgUpdateAddr = Get-PropText "UpdateCatalogAddress"
|
$cfgUpdateAddr = Get-PropText "UpdateCatalogAddress"
|
||||||
if ($cfgUpdateAddr) { Out "Каталог обн.: $cfgUpdateAddr" }
|
if ($cfgUpdateAddr) { Out "Каталог обн.: $cfgUpdateAddr" }
|
||||||
Out ""
|
Out ""
|
||||||
@@ -515,33 +275,6 @@ if ($Mode -eq "full" -and -not $Section) {
|
|||||||
Out "Обычн.формы в управл.: $useOF"
|
Out "Обычн.формы в управл.: $useOF"
|
||||||
Out ""
|
Out ""
|
||||||
|
|
||||||
# --- Section: Panel layout ---
|
|
||||||
if ($script:panelLayout) {
|
|
||||||
Out "--- Раскладка панелей ---"
|
|
||||||
foreach ($s in @("top","left","right","bottom")) {
|
|
||||||
$slots = $script:panelLayout[$s]
|
|
||||||
if ($slots.Count -gt 0) {
|
|
||||||
Out " $($s.PadRight(7)) $(Format-LayoutSlots $slots)"
|
|
||||||
} else {
|
|
||||||
Out " $($s.PadRight(7)) —"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($script:panelLayout.declared.Count -gt 0) {
|
|
||||||
Out " объявлено: $($script:panelLayout.declared -join ', ')"
|
|
||||||
}
|
|
||||||
Out ""
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Section: Home page (brief summary) ---
|
|
||||||
if ($script:homePage) {
|
|
||||||
$ln = $script:homePage.left.Count
|
|
||||||
$rn = $script:homePage.right.Count
|
|
||||||
Out "--- Начальная страница ---"
|
|
||||||
Out " Шаблон: $($script:homePage.template)"
|
|
||||||
Out " LeftColumn: $ln, RightColumn: $rn (детали: -Section home-page)"
|
|
||||||
Out ""
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Section: Storages & default forms ---
|
# --- Section: Storages & default forms ---
|
||||||
Out "--- Хранилища и формы по умолчанию ---"
|
Out "--- Хранилища и формы по умолчанию ---"
|
||||||
$storageProps = @("CommonSettingsStorage","ReportsUserSettingsStorage","ReportsVariantsStorage","FormDataSettingsStorage","DynamicListsUserSettingsStorage","URLExternalDataStorage")
|
$storageProps = @("CommonSettingsStorage","ReportsUserSettingsStorage","ReportsVariantsStorage","FormDataSettingsStorage","DynamicListsUserSettingsStorage","URLExternalDataStorage")
|
||||||
+5
-236
@@ -1,10 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-info v1.3 — Compact summary of 1C configuration root
|
# cf-info v1.0 — Compact summary of 1C configuration root
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
from collections import OrderedDict
|
from collections import OrderedDict
|
||||||
from lxml import etree
|
from lxml import etree
|
||||||
@@ -14,9 +13,8 @@ sys.stderr.reconfigure(encoding="utf-8")
|
|||||||
|
|
||||||
# --- Argument parsing ---
|
# --- Argument parsing ---
|
||||||
parser = argparse.ArgumentParser(description="Analyze 1C configuration structure", allow_abbrev=False)
|
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")
|
parser.add_argument("-ConfigPath", required=True, help="Path to Configuration.xml or directory")
|
||||||
parser.add_argument("-Mode", choices=["overview", "brief", "full"], default="overview", help="Output mode")
|
parser.add_argument("-Mode", choices=["overview", "brief", "full"], default="overview", help="Output mode")
|
||||||
parser.add_argument("-Section", "-Name", choices=["home-page"], default=None, help="Drill-down section (alias: -Name)")
|
|
||||||
parser.add_argument("-Limit", type=int, default=150, help="Max lines to show")
|
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("-Offset", type=int, default=0, help="Lines to skip")
|
||||||
parser.add_argument("-OutFile", default="", help="Write output to file")
|
parser.add_argument("-OutFile", default="", help="Write output to file")
|
||||||
@@ -127,173 +125,6 @@ type_ru_names = {
|
|||||||
"Task": "Задачи", "IntegrationService": "Сервисы интеграции",
|
"Task": "Задачи", "IntegrationService": "Сервисы интеграции",
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Read panel layout (Ext/ClientApplicationInterface.xml) ---
|
|
||||||
PANEL_NAMES = {
|
|
||||||
"cbab57f2-a0f3-4f0a-89ea-4cb19570ab75": "Открытых",
|
|
||||||
"b553047f-c9aa-4157-978d-448ecad24248": "Разделов",
|
|
||||||
"13322b22-3960-4d68-93a6-fe2dd7f28ca3": "Избранного",
|
|
||||||
"c933ac92-92cd-459d-81cc-e0c8a83ced99": "История",
|
|
||||||
"b2735bd3-d822-4430-ba59-c9e869693b24": "Функций",
|
|
||||||
}
|
|
||||||
CAI_NS = "http://v8.1c.ru/8.2/managed-application/core"
|
|
||||||
|
|
||||||
def get_panels_layout():
|
|
||||||
cfg_dir = os.path.dirname(config_path)
|
|
||||||
cai_path = os.path.join(cfg_dir, "Ext", "ClientApplicationInterface.xml")
|
|
||||||
if not os.path.isfile(cai_path):
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
cai_tree = etree.parse(cai_path)
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
cai_root = cai_tree.getroot()
|
|
||||||
layout = {"top": [], "left": [], "right": [], "bottom": [], "declared": []}
|
|
||||||
for side in ("top", "left", "right", "bottom"):
|
|
||||||
for side_el in cai_root.findall(f"{{{CAI_NS}}}{side}"):
|
|
||||||
slot = []
|
|
||||||
for u in side_el.iter(f"{{{CAI_NS}}}uuid"):
|
|
||||||
key = (u.text or "").strip()
|
|
||||||
slot.append(PANEL_NAMES.get(key, f"?{key}"))
|
|
||||||
if slot:
|
|
||||||
layout[side].append(slot)
|
|
||||||
for pd in cai_root.findall(f"{{{CAI_NS}}}panelDef"):
|
|
||||||
key = pd.get("id", "")
|
|
||||||
layout["declared"].append(PANEL_NAMES.get(key, f"?{key}"))
|
|
||||||
return layout
|
|
||||||
|
|
||||||
def format_layout_slots(slots):
|
|
||||||
if not slots:
|
|
||||||
return ""
|
|
||||||
parts = []
|
|
||||||
for slot in slots:
|
|
||||||
if len(slot) == 1:
|
|
||||||
parts.append(slot[0])
|
|
||||||
else:
|
|
||||||
parts.append("Стек(" + ", ".join(slot) + ")")
|
|
||||||
return " | ".join(parts)
|
|
||||||
|
|
||||||
panel_layout = get_panels_layout()
|
|
||||||
|
|
||||||
# --- Read home page layout (Ext/HomePageWorkArea.xml) ---
|
|
||||||
HP_NS = "http://v8.1c.ru/8.3/xcf/extrnprops"
|
|
||||||
XR_NS_HP = "http://v8.1c.ru/8.3/xcf/readable"
|
|
||||||
|
|
||||||
def get_home_page_layout():
|
|
||||||
cfg_dir = os.path.dirname(config_path)
|
|
||||||
hp_path = os.path.join(cfg_dir, "Ext", "HomePageWorkArea.xml")
|
|
||||||
if not os.path.isfile(hp_path):
|
|
||||||
return None
|
|
||||||
try:
|
|
||||||
hp_tree = etree.parse(hp_path)
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
hp_root = hp_tree.getroot()
|
|
||||||
result = {"template": "", "left": [], "right": []}
|
|
||||||
tn = hp_root.find(f"{{{HP_NS}}}WorkingAreaTemplate")
|
|
||||||
if tn is not None and tn.text:
|
|
||||||
result["template"] = tn.text.strip()
|
|
||||||
for col_name, key in (("LeftColumn", "left"), ("RightColumn", "right")):
|
|
||||||
col = hp_root.find(f"{{{HP_NS}}}{col_name}")
|
|
||||||
if col is None:
|
|
||||||
continue
|
|
||||||
items = []
|
|
||||||
for it in col.findall(f"{{{HP_NS}}}Item"):
|
|
||||||
f = it.find(f"{{{HP_NS}}}Form")
|
|
||||||
h = it.find(f"{{{HP_NS}}}Height")
|
|
||||||
vis = it.find(f"{{{HP_NS}}}Visibility")
|
|
||||||
common = True
|
|
||||||
roles = []
|
|
||||||
if vis is not None:
|
|
||||||
cn = vis.find(f"{{{XR_NS_HP}}}Common")
|
|
||||||
if cn is not None and cn.text:
|
|
||||||
common = cn.text.strip() == "true"
|
|
||||||
for v in vis.findall(f"{{{XR_NS_HP}}}Value"):
|
|
||||||
roles.append({"name": v.get("name", ""), "value": (v.text or "").strip() == "true"})
|
|
||||||
items.append({
|
|
||||||
"form": (f.text or "").strip() if f is not None else "",
|
|
||||||
"height": int((h.text or "10").strip()) if h is not None else 10,
|
|
||||||
"common": common,
|
|
||||||
"roles": roles,
|
|
||||||
})
|
|
||||||
result[key] = items
|
|
||||||
return result
|
|
||||||
|
|
||||||
home_page = get_home_page_layout()
|
|
||||||
|
|
||||||
# --- Support state (Ext/ParentConfigurations.bin) ---
|
|
||||||
# Decodes the 1C support-state file. See docs/1c-support-state-spec.md.
|
|
||||||
# Returns None on absent/error; else dict: state='absent'|'removed'|'parsed',
|
|
||||||
# g (0=editing on, 1=off), k (vendor configs), vendors [{vendor,name,version}],
|
|
||||||
# counts [locked, editable, removed] by f1 — record tally (k>1 counts each
|
|
||||||
# vendor block separately); only computed when g==0.
|
|
||||||
def read_support_state(bin_path):
|
|
||||||
try:
|
|
||||||
if not os.path.isfile(bin_path):
|
|
||||||
return {"state": "absent"}
|
|
||||||
data = open(bin_path, "rb").read()
|
|
||||||
if len(data) <= 32:
|
|
||||||
return {"state": "removed"}
|
|
||||||
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 None
|
|
||||||
g = int(h.group(1))
|
|
||||||
k = int(h.group(2))
|
|
||||||
if k == 0:
|
|
||||||
return {"state": "removed"}
|
|
||||||
vendors = []
|
|
||||||
for m in re.finditer(r'"((?:[^"]|"")*)","((?:[^"]|"")*)","((?:[^"]|"")*)",\d+,', text):
|
|
||||||
vendors.append({
|
|
||||||
"version": m.group(1).replace('""', '"'),
|
|
||||||
"vendor": m.group(2).replace('""', '"'),
|
|
||||||
"name": m.group(3).replace('""', '"'),
|
|
||||||
})
|
|
||||||
counts = None
|
|
||||||
if g == 0:
|
|
||||||
counts = [0, 0, 0]
|
|
||||||
for m in re.finditer(r"([0-2]),0,[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", text):
|
|
||||||
counts[int(m.group(1))] += 1
|
|
||||||
return {"state": "parsed", "g": g, "k": k, "vendors": vendors, "counts": counts}
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_support_lines():
|
|
||||||
config_dir = os.path.dirname(config_path)
|
|
||||||
bin_path = os.path.join(config_dir, "Ext", "ParentConfigurations.bin")
|
|
||||||
st = read_support_state(bin_path)
|
|
||||||
res = []
|
|
||||||
if not st or st["state"] == "absent":
|
|
||||||
if cfg_ext_purpose:
|
|
||||||
res.append("Поддержка: расширение (CFE), правки свободны")
|
|
||||||
else:
|
|
||||||
res.append("Поддержка: не на поддержке (своя конфигурация)")
|
|
||||||
return res
|
|
||||||
if st["state"] == "removed":
|
|
||||||
res.append("Поддержка: снята с поддержки полностью")
|
|
||||||
return res
|
|
||||||
res.append("Поддержка: на поддержке")
|
|
||||||
if st["g"] == 0:
|
|
||||||
res.append(" Возможность изменения: включена")
|
|
||||||
res.append(f" Объектов: на замке {st['counts'][0]} / редактируется {st['counts'][1]} / снято {st['counts'][2]}")
|
|
||||||
else:
|
|
||||||
res.append(" Возможность изменения: выключена — вся конфигурация read-only (правки заблокированы)")
|
|
||||||
res.append(f" Конфигураций поставщика: {st['k']}")
|
|
||||||
if st["k"] > 1:
|
|
||||||
for v in st["vendors"]:
|
|
||||||
res.append(f" Поставщик: {v['vendor']} — {v['name']} {v['version']}")
|
|
||||||
return res
|
|
||||||
|
|
||||||
def format_home_page_item(it, detailed):
|
|
||||||
badges = [f"h={it['height']}"]
|
|
||||||
if not it["common"]:
|
|
||||||
badges.append("скрыта")
|
|
||||||
if it["roles"]:
|
|
||||||
badges.append(f"роли: {len(it['roles'])}" if detailed else f"+{len(it['roles'])} ролей")
|
|
||||||
tail = f" ({', '.join(badges)})" if badges else ""
|
|
||||||
return f" {it['form']}{tail}"
|
|
||||||
|
|
||||||
# --- Count objects in ChildObjects ---
|
# --- Count objects in ChildObjects ---
|
||||||
object_counts = OrderedDict()
|
object_counts = OrderedDict()
|
||||||
total_objects = 0
|
total_objects = 0
|
||||||
@@ -315,7 +146,6 @@ cfg_version = get_prop_text("Version")
|
|||||||
cfg_vendor = get_prop_text("Vendor")
|
cfg_vendor = get_prop_text("Vendor")
|
||||||
cfg_compat = get_prop_text("CompatibilityMode")
|
cfg_compat = get_prop_text("CompatibilityMode")
|
||||||
cfg_ext_compat = get_prop_text("ConfigurationExtensionCompatibilityMode")
|
cfg_ext_compat = get_prop_text("ConfigurationExtensionCompatibilityMode")
|
||||||
cfg_ext_purpose = get_prop_text("ConfigurationExtensionPurpose")
|
|
||||||
cfg_default_run = get_prop_text("DefaultRunMode")
|
cfg_default_run = get_prop_text("DefaultRunMode")
|
||||||
cfg_script = get_prop_text("ScriptVariant")
|
cfg_script = get_prop_text("ScriptVariant")
|
||||||
cfg_default_lang = get_prop_text("DefaultLanguage")
|
cfg_default_lang = get_prop_text("DefaultLanguage")
|
||||||
@@ -329,14 +159,14 @@ cfg_db_spaces = get_prop_text("DatabaseTablespacesUseMode")
|
|||||||
cfg_window_mode = get_prop_text("MainClientApplicationWindowMode")
|
cfg_window_mode = get_prop_text("MainClientApplicationWindowMode")
|
||||||
|
|
||||||
# --- BRIEF mode ---
|
# --- BRIEF mode ---
|
||||||
if args.Mode == "brief" and not args.Section:
|
if args.Mode == "brief":
|
||||||
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
||||||
ver_part = f" v{cfg_version}" if cfg_version else ""
|
ver_part = f" v{cfg_version}" if cfg_version else ""
|
||||||
compat_part = f" | {cfg_compat}" if cfg_compat else ""
|
compat_part = f" | {cfg_compat}" if cfg_compat else ""
|
||||||
out(f"Конфигурация: {cfg_name}{syn_part}{ver_part} | {total_objects} объектов{compat_part}")
|
out(f"Конфигурация: {cfg_name}{syn_part}{ver_part} | {total_objects} объектов{compat_part}")
|
||||||
|
|
||||||
# --- OVERVIEW mode ---
|
# --- OVERVIEW mode ---
|
||||||
if args.Mode == "overview" and not args.Section:
|
if args.Mode == "overview":
|
||||||
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
||||||
ver_part = f" v{cfg_version}" if cfg_version else ""
|
ver_part = f" v{cfg_version}" if cfg_version else ""
|
||||||
out(f"=== Конфигурация: {cfg_name}{syn_part}{ver_part} ===")
|
out(f"=== Конфигурация: {cfg_name}{syn_part}{ver_part} ===")
|
||||||
@@ -348,8 +178,6 @@ if args.Mode == "overview" and not args.Section:
|
|||||||
out(f"Поставщик: {cfg_vendor}")
|
out(f"Поставщик: {cfg_vendor}")
|
||||||
if cfg_version:
|
if cfg_version:
|
||||||
out(f"Версия: {cfg_version}")
|
out(f"Версия: {cfg_version}")
|
||||||
for ln in get_support_lines():
|
|
||||||
out(ln)
|
|
||||||
out(f"Совместимость: {cfg_compat}")
|
out(f"Совместимость: {cfg_compat}")
|
||||||
out(f"Режим запуска: {cfg_default_run}")
|
out(f"Режим запуска: {cfg_default_run}")
|
||||||
out(f"Язык скриптов: {cfg_script}")
|
out(f"Язык скриптов: {cfg_script}")
|
||||||
@@ -359,20 +187,6 @@ if args.Mode == "overview" and not args.Section:
|
|||||||
out(f"Интерфейс: {cfg_intf_compat}")
|
out(f"Интерфейс: {cfg_intf_compat}")
|
||||||
out()
|
out()
|
||||||
|
|
||||||
if panel_layout and any(panel_layout[s] for s in ("top", "left", "right", "bottom")):
|
|
||||||
out("--- Раскладка панелей ---")
|
|
||||||
for s in ("top", "left", "right", "bottom"):
|
|
||||||
if panel_layout[s]:
|
|
||||||
out(f" {s.ljust(7)} {format_layout_slots(panel_layout[s])}")
|
|
||||||
out()
|
|
||||||
|
|
||||||
# Home page (brief summary)
|
|
||||||
if home_page:
|
|
||||||
out("--- Начальная страница ---")
|
|
||||||
out(f" Шаблон: {home_page['template']}")
|
|
||||||
out(f" LeftColumn: {len(home_page['left'])}, RightColumn: {len(home_page['right'])} (детали: -Section home-page)")
|
|
||||||
out()
|
|
||||||
|
|
||||||
# Object counts table
|
# Object counts table
|
||||||
out(f"--- Состав ({total_objects} объектов) ---")
|
out(f"--- Состав ({total_objects} объектов) ---")
|
||||||
out()
|
out()
|
||||||
@@ -393,30 +207,7 @@ if args.Mode == "overview" and not args.Section:
|
|||||||
out(f" {padded} {count}")
|
out(f" {padded} {count}")
|
||||||
|
|
||||||
# --- FULL mode ---
|
# --- FULL mode ---
|
||||||
# --- Drill-down: -Section home-page ---
|
if args.Mode == "full":
|
||||||
if args.Section == "home-page":
|
|
||||||
if not home_page:
|
|
||||||
out("Файл Ext/HomePageWorkArea.xml не найден")
|
|
||||||
else:
|
|
||||||
out(f"=== Начальная страница: {cfg_name} ===")
|
|
||||||
out()
|
|
||||||
out(f"Шаблон: {home_page['template']}")
|
|
||||||
out()
|
|
||||||
for col_lbl, col_key in (("LeftColumn", "left"), ("RightColumn", "right")):
|
|
||||||
items = home_page[col_key]
|
|
||||||
if not items:
|
|
||||||
out(f"{col_lbl}: —")
|
|
||||||
out()
|
|
||||||
continue
|
|
||||||
out(f"{col_lbl} ({len(items)}):")
|
|
||||||
for it in items:
|
|
||||||
out(format_home_page_item(it, True))
|
|
||||||
for r in it["roles"]:
|
|
||||||
rval = "true" if r["value"] else "false"
|
|
||||||
out(f" {r['name']}: {rval}")
|
|
||||||
out()
|
|
||||||
|
|
||||||
if args.Mode == "full" and not args.Section:
|
|
||||||
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
syn_part = f' {dash} "{cfg_synonym}"' if cfg_synonym else ""
|
||||||
ver_part = f" v{cfg_version}" if cfg_version else ""
|
ver_part = f" v{cfg_version}" if cfg_version else ""
|
||||||
out(f"=== Конфигурация: {cfg_name}{syn_part}{ver_part} ===")
|
out(f"=== Конфигурация: {cfg_name}{syn_part}{ver_part} ===")
|
||||||
@@ -438,8 +229,6 @@ if args.Mode == "full" and not args.Section:
|
|||||||
out(f"Поставщик: {cfg_vendor}")
|
out(f"Поставщик: {cfg_vendor}")
|
||||||
if cfg_version:
|
if cfg_version:
|
||||||
out(f"Версия: {cfg_version}")
|
out(f"Версия: {cfg_version}")
|
||||||
for ln in get_support_lines():
|
|
||||||
out(ln)
|
|
||||||
cfg_update_addr = get_prop_text("UpdateCatalogAddress")
|
cfg_update_addr = get_prop_text("UpdateCatalogAddress")
|
||||||
if cfg_update_addr:
|
if cfg_update_addr:
|
||||||
out(f"Каталог обн.: {cfg_update_addr}")
|
out(f"Каталог обн.: {cfg_update_addr}")
|
||||||
@@ -494,26 +283,6 @@ if args.Mode == "full" and not args.Section:
|
|||||||
out(f"Обычн.формы в управл.: {use_of}")
|
out(f"Обычн.формы в управл.: {use_of}")
|
||||||
out()
|
out()
|
||||||
|
|
||||||
# --- Section: Panel layout ---
|
|
||||||
if panel_layout:
|
|
||||||
out("--- Раскладка панелей ---")
|
|
||||||
for s in ("top", "left", "right", "bottom"):
|
|
||||||
slots = panel_layout[s]
|
|
||||||
if slots:
|
|
||||||
out(f" {s.ljust(7)} {format_layout_slots(slots)}")
|
|
||||||
else:
|
|
||||||
out(f" {s.ljust(7)} —")
|
|
||||||
if panel_layout["declared"]:
|
|
||||||
out(f" объявлено: {', '.join(panel_layout['declared'])}")
|
|
||||||
out()
|
|
||||||
|
|
||||||
# --- Section: Home page (brief summary) ---
|
|
||||||
if home_page:
|
|
||||||
out("--- Начальная страница ---")
|
|
||||||
out(f" Шаблон: {home_page['template']}")
|
|
||||||
out(f" LeftColumn: {len(home_page['left'])}, RightColumn: {len(home_page['right'])} (детали: -Section home-page)")
|
|
||||||
out()
|
|
||||||
|
|
||||||
# --- Section: Storages & default forms ---
|
# --- Section: Storages & default forms ---
|
||||||
out("--- Хранилища и формы по умолчанию ---")
|
out("--- Хранилища и формы по умолчанию ---")
|
||||||
storage_props = [
|
storage_props = [
|
||||||
@@ -24,7 +24,16 @@ allowed-tools:
|
|||||||
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cf-init/scripts/cf-init.py" -Name "МояКонфигурация"
|
powershell.exe -NoProfile -File .claude/skills/cf-init/scripts/cf-init.ps1 -Name "МояКонфигурация"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<OutputDir>/
|
||||||
|
├── Configuration.xml # Корневой файл — все свойства
|
||||||
|
└── Languages/
|
||||||
|
└── Русский.xml # Язык по умолчанию
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+2
-36
@@ -1,4 +1,4 @@
|
|||||||
# cf-init v1.2 — Create empty 1C configuration scaffold
|
# cf-init v1.0 — Create empty 1C configuration scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -160,7 +160,7 @@ $cfgXml = @"
|
|||||||
<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
||||||
<ModalityUseMode>DontUse</ModalityUseMode>
|
<ModalityUseMode>DontUse</ModalityUseMode>
|
||||||
<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
||||||
<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
<InterfaceCompatibilityMode>Taxi</InterfaceCompatibilityMode>
|
||||||
<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
||||||
<CompatibilityMode>$CompatibilityMode</CompatibilityMode>
|
<CompatibilityMode>$CompatibilityMode</CompatibilityMode>
|
||||||
<DefaultConstantsForm/>
|
<DefaultConstantsForm/>
|
||||||
@@ -192,33 +192,6 @@ $langXml = @"
|
|||||||
</MetaDataObject>
|
</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).
|
|
||||||
$openPanelInst = [guid]::NewGuid().ToString()
|
|
||||||
$sectionsPanelInst = [guid]::NewGuid().ToString()
|
|
||||||
$caiXml = @"
|
|
||||||
<?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">
|
|
||||||
<top>
|
|
||||||
<panel id="$openPanelInst">
|
|
||||||
<uuid>cbab57f2-a0f3-4f0a-89ea-4cb19570ab75</uuid>
|
|
||||||
</panel>
|
|
||||||
</top>
|
|
||||||
<left>
|
|
||||||
<panel id="$sectionsPanelInst">
|
|
||||||
<uuid>b553047f-c9aa-4157-978d-448ecad24248</uuid>
|
|
||||||
</panel>
|
|
||||||
</left>
|
|
||||||
<panelDef id="b553047f-c9aa-4157-978d-448ecad24248"/>
|
|
||||||
<panelDef id="13322b22-3960-4d68-93a6-fe2dd7f28ca3"/>
|
|
||||||
<panelDef id="c933ac92-92cd-459d-81cc-e0c8a83ced99"/>
|
|
||||||
<panelDef id="cbab57f2-a0f3-4f0a-89ea-4cb19570ab75"/>
|
|
||||||
<panelDef id="b2735bd3-d822-4430-ba59-c9e869693b24"/>
|
|
||||||
</ClientApplicationInterface>
|
|
||||||
"@
|
|
||||||
|
|
||||||
# --- Create directories ---
|
# --- Create directories ---
|
||||||
if (-not (Test-Path $OutputDir)) {
|
if (-not (Test-Path $OutputDir)) {
|
||||||
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
|
||||||
@@ -227,10 +200,6 @@ $langDir = Join-Path $OutputDir "Languages"
|
|||||||
if (-not (Test-Path $langDir)) {
|
if (-not (Test-Path $langDir)) {
|
||||||
New-Item -ItemType Directory -Path $langDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $langDir -Force | Out-Null
|
||||||
}
|
}
|
||||||
$extDir = Join-Path $OutputDir "Ext"
|
|
||||||
if (-not (Test-Path $extDir)) {
|
|
||||||
New-Item -ItemType Directory -Path $extDir -Force | Out-Null
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Write files with UTF-8 BOM ---
|
# --- Write files with UTF-8 BOM ---
|
||||||
$enc = New-Object System.Text.UTF8Encoding($true)
|
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||||
@@ -238,12 +207,9 @@ $enc = New-Object System.Text.UTF8Encoding($true)
|
|||||||
[System.IO.File]::WriteAllText($cfgFile, $cfgXml, $enc)
|
[System.IO.File]::WriteAllText($cfgFile, $cfgXml, $enc)
|
||||||
$langFile = Join-Path $langDir "Русский.xml"
|
$langFile = Join-Path $langDir "Русский.xml"
|
||||||
[System.IO.File]::WriteAllText($langFile, $langXml, $enc)
|
[System.IO.File]::WriteAllText($langFile, $langXml, $enc)
|
||||||
$caiFile = Join-Path $extDir "ClientApplicationInterface.xml"
|
|
||||||
[System.IO.File]::WriteAllText($caiFile, $caiXml, $enc)
|
|
||||||
|
|
||||||
# --- Output ---
|
# --- Output ---
|
||||||
Write-Host "[OK] Создана конфигурация: $Name"
|
Write-Host "[OK] Создана конфигурация: $Name"
|
||||||
Write-Host " Каталог: $OutputDir"
|
Write-Host " Каталог: $OutputDir"
|
||||||
Write-Host " Configuration.xml: $cfgFile"
|
Write-Host " Configuration.xml: $cfgFile"
|
||||||
Write-Host " Languages: $langFile"
|
Write-Host " Languages: $langFile"
|
||||||
Write-Host " Ext/CAI: $caiFile"
|
|
||||||
+2
-32
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-init v1.2 — Create empty 1C configuration scaffold
|
# cf-init v1.0 — Create empty 1C configuration scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Generates minimal XML source files for a 1C configuration."""
|
"""Generates minimal XML source files for a 1C configuration."""
|
||||||
import sys, os, argparse, uuid
|
import sys, os, argparse, uuid
|
||||||
@@ -155,7 +155,7 @@ def main():
|
|||||||
\t\t\t<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
\t\t\t<ObjectAutonumerationMode>NotAutoFree</ObjectAutonumerationMode>
|
||||||
\t\t\t<ModalityUseMode>DontUse</ModalityUseMode>
|
\t\t\t<ModalityUseMode>DontUse</ModalityUseMode>
|
||||||
\t\t\t<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
\t\t\t<SynchronousPlatformExtensionAndAddInCallUseMode>DontUse</SynchronousPlatformExtensionAndAddInCallUseMode>
|
||||||
\t\t\t<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
\t\t\t<InterfaceCompatibilityMode>Taxi</InterfaceCompatibilityMode>
|
||||||
\t\t\t<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
\t\t\t<DatabaseTablespacesUseMode>DontUse</DatabaseTablespacesUseMode>
|
||||||
\t\t\t<CompatibilityMode>{compat}</CompatibilityMode>
|
\t\t\t<CompatibilityMode>{compat}</CompatibilityMode>
|
||||||
\t\t\t<DefaultConstantsForm/>
|
\t\t\t<DefaultConstantsForm/>
|
||||||
@@ -184,50 +184,20 @@ def main():
|
|||||||
\t</Language>
|
\t</Language>
|
||||||
</MetaDataObject>'''
|
</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 ---
|
# --- Create directories ---
|
||||||
os.makedirs(output_dir, exist_ok=True)
|
os.makedirs(output_dir, exist_ok=True)
|
||||||
lang_dir = os.path.join(output_dir, "Languages")
|
lang_dir = os.path.join(output_dir, "Languages")
|
||||||
os.makedirs(lang_dir, exist_ok=True)
|
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 files ---
|
||||||
write_utf8_bom(cfg_file, cfg_xml)
|
write_utf8_bom(cfg_file, cfg_xml)
|
||||||
lang_file = os.path.join(lang_dir, "Русский.xml")
|
lang_file = os.path.join(lang_dir, "Русский.xml")
|
||||||
write_utf8_bom(lang_file, lang_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"[OK] Создана конфигурация: {name}")
|
||||||
print(f" Каталог: {output_dir}")
|
print(f" Каталог: {output_dir}")
|
||||||
print(f" Configuration.xml: {cfg_file}")
|
print(f" Configuration.xml: {cfg_file}")
|
||||||
print(f" Languages: {lang_file}")
|
print(f" Languages: {lang_file}")
|
||||||
print(f" Ext/CAI: {cai_file}")
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
main()
|
main()
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
name: cf-validate
|
||||||
|
description: Валидация конфигурации 1С. Используй после создания или модификации конфигурации для проверки корректности
|
||||||
|
argument-hint: <ConfigPath> [-Detailed] [-MaxErrors 30]
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Glob
|
||||||
|
---
|
||||||
|
|
||||||
|
# /cf-validate — валидация конфигурации 1С
|
||||||
|
|
||||||
|
Проверяет Configuration.xml на структурные ошибки: XML well-formedness, InternalInfo, свойства, enum-значения, ChildObjects, DefaultLanguage, файлы языков, каталоги объектов.
|
||||||
|
|
||||||
|
## Параметры
|
||||||
|
|
||||||
|
| Параметр | Обяз. | Умолч. | Описание |
|
||||||
|
|------------|:-----:|---------|-------------------------------------------------|
|
||||||
|
| ConfigPath | да | — | Путь к Configuration.xml или каталогу выгрузки |
|
||||||
|
| Detailed | нет | — | Показывать [OK] для каждой проверки |
|
||||||
|
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||||
|
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/cf-validate/scripts/cf-validate.ps1 -ConfigPath "upload/cfempty"
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/cf-validate/scripts/cf-validate.ps1 -ConfigPath "upload/cfempty/Configuration.xml"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
| # | Проверка | Серьёзность |
|
||||||
|
|---|----------|-------------|
|
||||||
|
| 1 | XML well-formedness, MetaDataObject/Configuration, version 2.17/2.20 | ERROR |
|
||||||
|
| 2 | InternalInfo: 7 ContainedObject, валидные ClassId, уникальность | ERROR |
|
||||||
|
| 3 | Properties: Name непустой, Synonym, DefaultLanguage, DefaultRunMode | ERROR/WARN |
|
||||||
|
| 4 | Properties: enum-значения (11 свойств) | ERROR |
|
||||||
|
| 5 | ChildObjects: валидные имена типов (44 типа), нет дубликатов, порядок типов | ERROR/WARN |
|
||||||
|
| 6 | DefaultLanguage ссылается на существующий Language в ChildObjects | ERROR |
|
||||||
|
| 7 | Файлы языков Languages/<name>.xml существуют | WARN |
|
||||||
|
| 8 | Каталоги объектов из ChildObjects существуют (spot-check) | WARN |
|
||||||
|
|
||||||
|
Exit code: 0 = OK, 1 = есть ошибки. По умолчанию краткий вывод. `-Detailed` для поштучной детализации.
|
||||||
+6
-73
@@ -1,8 +1,7 @@
|
|||||||
# cf-validate v1.3 — Validate 1C configuration root structure
|
# cf-validate v1.1 — Validate 1C configuration root structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$ConfigPath,
|
[string]$ConfigPath,
|
||||||
|
|
||||||
[switch]$Detailed,
|
[switch]$Detailed,
|
||||||
@@ -146,17 +145,17 @@ $childTypeDirMap = @{
|
|||||||
|
|
||||||
# Valid enum values for Configuration properties
|
# Valid enum values for Configuration properties
|
||||||
$validEnumValues = @{
|
$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")
|
"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")
|
||||||
"DefaultRunMode" = @("ManagedApplication","OrdinaryApplication","Auto")
|
"DefaultRunMode" = @("ManagedApplication","OrdinaryApplication","Auto")
|
||||||
"ScriptVariant" = @("Russian","English")
|
"ScriptVariant" = @("Russian","English")
|
||||||
"DataLockControlMode" = @("Automatic","Managed","AutomaticAndManaged")
|
"DataLockControlMode" = @("Automatic","Managed","AutomaticAndManaged")
|
||||||
"ObjectAutonumerationMode" = @("NotAutoFree","AutoFree")
|
"ObjectAutonumerationMode" = @("NotAutoFree","AutoFree")
|
||||||
"ModalityUseMode" = @("DontUse","Use","UseWithWarnings")
|
"ModalityUseMode" = @("DontUse","Use","UseWithWarnings")
|
||||||
"SynchronousPlatformExtensionAndAddInCallUseMode" = @("DontUse","Use","UseWithWarnings")
|
"SynchronousPlatformExtensionAndAddInCallUseMode" = @("DontUse","Use","UseWithWarnings")
|
||||||
"InterfaceCompatibilityMode" = @("Version8_2","Version8_2EnableTaxi","Taxi","TaxiEnableVersion8_2","TaxiEnableVersion8_5","Version8_5EnableTaxi","Version8_5")
|
"InterfaceCompatibilityMode" = @("Taxi","TaxiEnableVersion8_2","Version8_2")
|
||||||
"DatabaseTablespacesUseMode" = @("DontUse","Use")
|
"DatabaseTablespacesUseMode" = @("DontUse","Use")
|
||||||
"MainClientApplicationWindowMode" = @("Normal","Fullscreen","Kiosk")
|
"MainClientApplicationWindowMode" = @("Normal","Fullscreen","Kiosk")
|
||||||
"CompatibilityMode" = @("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")
|
"CompatibilityMode" = @("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")
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 1. Parse XML ---
|
# --- 1. Parse XML ---
|
||||||
@@ -204,8 +203,8 @@ if ($root.NamespaceURI -ne $expectedNs) {
|
|||||||
$version = $root.GetAttribute("version")
|
$version = $root.GetAttribute("version")
|
||||||
if (-not $version) {
|
if (-not $version) {
|
||||||
Report-Warn "1. Missing version attribute on MetaDataObject"
|
Report-Warn "1. Missing version attribute on MetaDataObject"
|
||||||
} elseif ($version -ne "2.17" -and $version -ne "2.20" -and $version -ne "2.21") {
|
} elseif ($version -ne "2.17" -and $version -ne "2.20") {
|
||||||
Report-Warn "1. Unusual version '$version' (expected 2.17, 2.20 or 2.21)"
|
Report-Warn "1. Unusual version '$version' (expected 2.17 or 2.20)"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Must have Configuration child
|
# Must have Configuration child
|
||||||
@@ -536,72 +535,6 @@ if ($childObjNode) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Check 9: Form references (HomePageWorkArea + Properties) ---
|
|
||||||
function Test-FormRef([string]$ref) {
|
|
||||||
if (-not $ref) { return $true }
|
|
||||||
# UUID — cannot verify without scanning all forms; skip
|
|
||||||
if ($ref -match $guidPattern) { return $true }
|
|
||||||
$parts = $ref.Split(".")
|
|
||||||
if ($parts.Count -eq 2 -and $parts[0] -eq "CommonForm") {
|
|
||||||
$p = Join-Path (Join-Path (Join-Path $configDir "CommonForms") $parts[1]) "Form.xml"
|
|
||||||
$pExt = Join-Path (Join-Path (Join-Path (Join-Path $configDir "CommonForms") $parts[1]) "Ext") "Form.xml"
|
|
||||||
return (Test-Path $p) -or (Test-Path $pExt)
|
|
||||||
}
|
|
||||||
if ($parts.Count -eq 4 -and $parts[2] -eq "Form" -and $childTypeDirMap.ContainsKey($parts[0])) {
|
|
||||||
$dir = $childTypeDirMap[$parts[0]]
|
|
||||||
$p = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $configDir $dir) $parts[1]) "Forms") $parts[3]) "Form.xml"
|
|
||||||
$pExt = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $configDir $dir) $parts[1]) "Forms") $parts[3]) "Ext") "Form.xml"
|
|
||||||
return (Test-Path $p) -or (Test-Path $pExt)
|
|
||||||
}
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
|
|
||||||
$formRefsChecked = 0
|
|
||||||
$formRefErrors = @()
|
|
||||||
|
|
||||||
# HomePageWorkArea
|
|
||||||
$hpPath = Join-Path (Join-Path $configDir "Ext") "HomePageWorkArea.xml"
|
|
||||||
if (Test-Path $hpPath) {
|
|
||||||
try {
|
|
||||||
[xml]$hpDoc = Get-Content -Path $hpPath -Encoding UTF8
|
|
||||||
$hpNs = New-Object System.Xml.XmlNamespaceManager($hpDoc.NameTable)
|
|
||||||
$hpNs.AddNamespace("hp", "http://v8.1c.ru/8.3/xcf/extrnprops")
|
|
||||||
foreach ($f in $hpDoc.DocumentElement.SelectNodes("//hp:Item/hp:Form", $hpNs)) {
|
|
||||||
$ref = $f.InnerText.Trim()
|
|
||||||
if (-not $ref) { continue }
|
|
||||||
$formRefsChecked++
|
|
||||||
if (-not (Test-FormRef $ref)) {
|
|
||||||
$formRefErrors += "HomePageWorkArea.Form '$ref' — file not found"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
$formRefErrors += "HomePageWorkArea.xml: parse error — $($_.Exception.Message)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Properties: DefaultXxxForm refs
|
|
||||||
if ($propsNode) {
|
|
||||||
$formProps = @("DefaultReportForm","DefaultReportVariantForm","DefaultReportSettingsForm","DefaultDynamicListSettingsForm","DefaultSearchForm","DefaultDataHistoryChangeHistoryForm","DefaultDataHistoryVersionDataForm","DefaultDataHistoryVersionDifferencesForm","DefaultCollaborationSystemUsersChoiceForm","DefaultConstantsForm")
|
|
||||||
foreach ($pn in $formProps) {
|
|
||||||
$node = $propsNode.SelectSingleNode("md:$pn", $ns)
|
|
||||||
if ($node -and $node.InnerText.Trim()) {
|
|
||||||
$ref = $node.InnerText.Trim()
|
|
||||||
$formRefsChecked++
|
|
||||||
if (-not (Test-FormRef $ref)) {
|
|
||||||
$formRefErrors += "Properties.$pn '$ref' — form not found"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($formRefsChecked -eq 0) {
|
|
||||||
Report-OK "9. Form references: none to check"
|
|
||||||
} elseif ($formRefErrors.Count -eq 0) {
|
|
||||||
Report-OK "9. Form references: $formRefsChecked verified"
|
|
||||||
} else {
|
|
||||||
foreach ($err in $formRefErrors) { Report-Error "9. $err" }
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Final output ---
|
# --- Final output ---
|
||||||
& $finalize
|
& $finalize
|
||||||
|
|
||||||
+7
-64
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-validate v1.3 — Validate 1C configuration XML structure
|
# cf-validate v1.1 — Validate 1C configuration XML structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Validates Configuration.xml: root structure, InternalInfo, properties, ChildObjects, languages."""
|
"""Validates Configuration.xml: root structure, InternalInfo, properties, ChildObjects, languages."""
|
||||||
import sys, os, argparse, re
|
import sys, os, argparse, re
|
||||||
@@ -82,7 +82,7 @@ VALID_ENUM_VALUES = {
|
|||||||
'Version8_3_11', 'Version8_3_12', 'Version8_3_13', 'Version8_3_14', 'Version8_3_15',
|
'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_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_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',
|
'Version8_3_26', 'Version8_3_27', 'Version8_3_28',
|
||||||
],
|
],
|
||||||
'DefaultRunMode': ['ManagedApplication', 'OrdinaryApplication', 'Auto'],
|
'DefaultRunMode': ['ManagedApplication', 'OrdinaryApplication', 'Auto'],
|
||||||
'ScriptVariant': ['Russian', 'English'],
|
'ScriptVariant': ['Russian', 'English'],
|
||||||
@@ -90,10 +90,7 @@ VALID_ENUM_VALUES = {
|
|||||||
'ObjectAutonumerationMode': ['NotAutoFree', 'AutoFree'],
|
'ObjectAutonumerationMode': ['NotAutoFree', 'AutoFree'],
|
||||||
'ModalityUseMode': ['DontUse', 'Use', 'UseWithWarnings'],
|
'ModalityUseMode': ['DontUse', 'Use', 'UseWithWarnings'],
|
||||||
'SynchronousPlatformExtensionAndAddInCallUseMode': ['DontUse', 'Use', 'UseWithWarnings'],
|
'SynchronousPlatformExtensionAndAddInCallUseMode': ['DontUse', 'Use', 'UseWithWarnings'],
|
||||||
'InterfaceCompatibilityMode': [
|
'InterfaceCompatibilityMode': ['Taxi', 'TaxiEnableVersion8_2', 'Version8_2'],
|
||||||
'Version8_2', 'Version8_2EnableTaxi', 'Taxi', 'TaxiEnableVersion8_2',
|
|
||||||
'TaxiEnableVersion8_5', 'Version8_5EnableTaxi', 'Version8_5',
|
|
||||||
],
|
|
||||||
'DatabaseTablespacesUseMode': ['DontUse', 'Use'],
|
'DatabaseTablespacesUseMode': ['DontUse', 'Use'],
|
||||||
'MainClientApplicationWindowMode': ['Normal', 'Fullscreen', 'Kiosk'],
|
'MainClientApplicationWindowMode': ['Normal', 'Fullscreen', 'Kiosk'],
|
||||||
'CompatibilityMode': [
|
'CompatibilityMode': [
|
||||||
@@ -103,7 +100,7 @@ VALID_ENUM_VALUES = {
|
|||||||
'Version8_3_11', 'Version8_3_12', 'Version8_3_13', 'Version8_3_14', 'Version8_3_15',
|
'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_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_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',
|
'Version8_3_26', 'Version8_3_27', 'Version8_3_28',
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,7 +162,7 @@ def main():
|
|||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description='Validate 1C configuration XML structure', allow_abbrev=False
|
description='Validate 1C configuration XML structure', allow_abbrev=False
|
||||||
)
|
)
|
||||||
parser.add_argument('-ConfigPath', '-Path', dest='ConfigPath', required=True)
|
parser.add_argument('-ConfigPath', dest='ConfigPath', required=True)
|
||||||
parser.add_argument('-Detailed', action='store_true')
|
parser.add_argument('-Detailed', action='store_true')
|
||||||
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
||||||
parser.add_argument('-OutFile', dest='OutFile', default='')
|
parser.add_argument('-OutFile', dest='OutFile', default='')
|
||||||
@@ -231,8 +228,8 @@ def main():
|
|||||||
version = root.get('version', '')
|
version = root.get('version', '')
|
||||||
if not version:
|
if not version:
|
||||||
r.warn('1. Missing version attribute on MetaDataObject')
|
r.warn('1. Missing version attribute on MetaDataObject')
|
||||||
elif version not in ('2.17', '2.20', '2.21'):
|
elif version not in ('2.17', '2.20'):
|
||||||
r.warn(f"1. Unusual version '{version}' (expected 2.17, 2.20 or 2.21)")
|
r.warn(f"1. Unusual version '{version}' (expected 2.17 or 2.20)")
|
||||||
|
|
||||||
# Must have Configuration child
|
# Must have Configuration child
|
||||||
cfg_node = None
|
cfg_node = None
|
||||||
@@ -537,60 +534,6 @@ def main():
|
|||||||
else:
|
else:
|
||||||
pass # no ChildObjects
|
pass # no ChildObjects
|
||||||
|
|
||||||
# --- Check 9: Form references (HomePageWorkArea + Properties) ---
|
|
||||||
def test_form_ref(ref):
|
|
||||||
if not ref:
|
|
||||||
return True
|
|
||||||
if GUID_PATTERN.match(ref):
|
|
||||||
return True
|
|
||||||
parts = ref.split('.')
|
|
||||||
if len(parts) == 2 and parts[0] == 'CommonForm':
|
|
||||||
p = os.path.join(config_dir, 'CommonForms', parts[1], 'Form.xml')
|
|
||||||
p_ext = os.path.join(config_dir, 'CommonForms', parts[1], 'Ext', 'Form.xml')
|
|
||||||
return os.path.isfile(p) or os.path.isfile(p_ext)
|
|
||||||
if len(parts) == 4 and parts[2] == 'Form' and parts[0] in CHILD_TYPE_DIR_MAP:
|
|
||||||
d = CHILD_TYPE_DIR_MAP[parts[0]]
|
|
||||||
p = os.path.join(config_dir, d, parts[1], 'Forms', parts[3], 'Form.xml')
|
|
||||||
p_ext = os.path.join(config_dir, d, parts[1], 'Forms', parts[3], 'Ext', 'Form.xml')
|
|
||||||
return os.path.isfile(p) or os.path.isfile(p_ext)
|
|
||||||
return False
|
|
||||||
|
|
||||||
form_refs_checked = 0
|
|
||||||
form_ref_errors = []
|
|
||||||
|
|
||||||
hp_path = os.path.join(config_dir, 'Ext', 'HomePageWorkArea.xml')
|
|
||||||
if os.path.isfile(hp_path):
|
|
||||||
try:
|
|
||||||
hp_tree = etree.parse(hp_path)
|
|
||||||
HP_NS = 'http://v8.1c.ru/8.3/xcf/extrnprops'
|
|
||||||
for f in hp_tree.getroot().iter(f'{{{HP_NS}}}Form'):
|
|
||||||
ref = (f.text or '').strip()
|
|
||||||
if not ref:
|
|
||||||
continue
|
|
||||||
form_refs_checked += 1
|
|
||||||
if not test_form_ref(ref):
|
|
||||||
form_ref_errors.append(f"HomePageWorkArea.Form '{ref}' — file not found")
|
|
||||||
except Exception as e:
|
|
||||||
form_ref_errors.append(f'HomePageWorkArea.xml: parse error — {e}')
|
|
||||||
|
|
||||||
if props_node is not None:
|
|
||||||
form_props = ['DefaultReportForm','DefaultReportVariantForm','DefaultReportSettingsForm','DefaultDynamicListSettingsForm','DefaultSearchForm','DefaultDataHistoryChangeHistoryForm','DefaultDataHistoryVersionDataForm','DefaultDataHistoryVersionDifferencesForm','DefaultCollaborationSystemUsersChoiceForm','DefaultConstantsForm']
|
|
||||||
for pn in form_props:
|
|
||||||
node = props_node.find(f'md:{pn}', NS)
|
|
||||||
if node is not None and node.text and node.text.strip():
|
|
||||||
ref = node.text.strip()
|
|
||||||
form_refs_checked += 1
|
|
||||||
if not test_form_ref(ref):
|
|
||||||
form_ref_errors.append(f"Properties.{pn} '{ref}' — form not found")
|
|
||||||
|
|
||||||
if form_refs_checked == 0:
|
|
||||||
r.ok('9. Form references: none to check')
|
|
||||||
elif not form_ref_errors:
|
|
||||||
r.ok(f'9. Form references: {form_refs_checked} verified')
|
|
||||||
else:
|
|
||||||
for err in form_ref_errors:
|
|
||||||
r.error(f'9. {err}')
|
|
||||||
|
|
||||||
# --- Final output ---
|
# --- Final output ---
|
||||||
r.finalize(out_file)
|
r.finalize(out_file)
|
||||||
sys.exit(1 if r.errors > 0 else 0)
|
sys.exit(1 if r.errors > 0 else 0)
|
||||||
@@ -31,7 +31,7 @@ allowed-tools:
|
|||||||
| `ExtensionPath` | Путь к каталогу расширения (обязат.) |
|
| `ExtensionPath` | Путь к каталогу расширения (обязат.) |
|
||||||
| `ConfigPath` | Путь к конфигурации-источнику (обязат.) |
|
| `ConfigPath` | Путь к конфигурации-источнику (обязат.) |
|
||||||
| `Object` | Что заимствовать (обязат.), batch через `;;` |
|
| `Object` | Что заимствовать (обязат.), batch через `;;` |
|
||||||
| `BorrowMainAttribute` | Заимствовать основной реквизит формы. Без параметра — не заимствует. `Form` — реквизиты, используемые на форме. `All` — все реквизиты объекта. Требует форму в -Object |
|
| `BorrowMainAttribute` | Используй при добавлении нового реквизита на заимствованную форму. `Form` (по умолч.) — реквизиты с формы, `All` — все реквизиты объекта |
|
||||||
|
|
||||||
## Формат -Object
|
## Формат -Object
|
||||||
|
|
||||||
@@ -71,7 +71,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cfe-borrow/scripts/cfe-borrow.py" -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты"
|
powershell.exe -NoProfile -File .claude/skills/cfe-borrow/scripts/cfe-borrow.ps1 -ExtensionPath src -ConfigPath C:\cfsrc\erp -Object "Catalog.Контрагенты"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+118
-231
@@ -1,4 +1,4 @@
|
|||||||
# cfe-borrow v1.8 — Borrow objects from configuration into extension (CFE)
|
# cfe-borrow v1.2 — Borrow objects from configuration into extension (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)][string]$ExtensionPath,
|
[Parameter(Mandatory)][string]$ExtensionPath,
|
||||||
@@ -13,31 +13,6 @@ $ErrorActionPreference = "Stop"
|
|||||||
function Info([string]$msg) { Write-Host "[INFO] $msg" }
|
function Info([string]$msg) { Write-Host "[INFO] $msg" }
|
||||||
function Warn([string]$msg) { Write-Host "[WARN] $msg" }
|
function Warn([string]$msg) { Write-Host "[WARN] $msg" }
|
||||||
|
|
||||||
# Form data-binding tags (value = attribute path). A binding survives only if its root
|
|
||||||
# attribute is borrowed into the form's <Attributes>; otherwise it must be stripped or the
|
|
||||||
# platform rejects the form with "Неверный путь к данным" on load.
|
|
||||||
$script:formBindingDataTags = @('DataPath','TitleDataPath','FooterDataPath','HeaderDataPath','MultipleValueDataPath','MultipleValuePresentDataPath')
|
|
||||||
# Picture-path binding tags (value = picture index path, never a data attribute) — always stripped in the skeleton.
|
|
||||||
$script:formBindingPictureTags = @('RowPictureDataPath','MultipleValuePictureDataPath')
|
|
||||||
|
|
||||||
# Strip data-binding tags whose root attribute isn't borrowed.
|
|
||||||
# $keepObjekt=$true (BorrowMainAttribute): keep Объект.* data bindings, strip the rest.
|
|
||||||
# $keepObjekt=$false (default skeleton): strip all bindings. Picture-path tags are always stripped.
|
|
||||||
function Strip-FormBindings {
|
|
||||||
param([string]$xml, [bool]$keepObjekt)
|
|
||||||
foreach ($tag in $script:formBindingDataTags) {
|
|
||||||
if ($keepObjekt) {
|
|
||||||
$xml = [regex]::Replace($xml, "\s*<$tag>(?!Объект\.)[^<]*</$tag>", '')
|
|
||||||
} else {
|
|
||||||
$xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
foreach ($tag in $script:formBindingPictureTags) {
|
|
||||||
$xml = [regex]::Replace($xml, "\s*<$tag>[^<]*</$tag>", '')
|
|
||||||
}
|
|
||||||
return $xml
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1. Resolve paths ---
|
# --- 1. Resolve paths ---
|
||||||
if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
|
if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
|
||||||
$ExtensionPath = Join-Path (Get-Location).Path $ExtensionPath
|
$ExtensionPath = Join-Path (Get-Location).Path $ExtensionPath
|
||||||
@@ -341,25 +316,6 @@ function Expand-SelfClosingElement($container, $parentIndent) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 7b. Detect format version ---
|
|
||||||
|
|
||||||
function Detect-FormatVersion([string]$dir) {
|
|
||||||
$d = $dir
|
|
||||||
while ($d) {
|
|
||||||
$cfgPath = Join-Path $d "Configuration.xml"
|
|
||||||
if (Test-Path $cfgPath) {
|
|
||||||
$head = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8).Substring(0, [Math]::Min(2000, (Get-Item $cfgPath).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"
|
|
||||||
}
|
|
||||||
|
|
||||||
$script:formatVersion = Detect-FormatVersion $extDir
|
|
||||||
|
|
||||||
# --- 8. Namespaces declaration for object XML ---
|
# --- 8. Namespaces declaration for object XML ---
|
||||||
$script: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"'
|
$script: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"'
|
||||||
|
|
||||||
@@ -444,14 +400,6 @@ function Read-SourceObject {
|
|||||||
$srcProps[$propName] = $propNode.InnerText.Trim()
|
$srcProps[$propName] = $propNode.InnerText.Trim()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
# DefinedType: carry the <Type> definition. A type alias is meaningless as a bare shell —
|
|
||||||
# the platform needs its underlying type (e.g. to know a column is a summable Number for totals).
|
|
||||||
if ($typeName -eq "DefinedType") {
|
|
||||||
$typeNode = $propsNode.SelectSingleNode("md:Type", $srcNs)
|
|
||||||
if ($typeNode) {
|
|
||||||
$srcProps["__TypeXml"] = [regex]::Replace($typeNode.OuterXml, '\s+xmlns(?::\w+)?="[^"]*"', '')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return @{
|
return @{
|
||||||
@@ -514,26 +462,11 @@ function Borrow-Form {
|
|||||||
}
|
}
|
||||||
$srcFormContent = [System.IO.File]::ReadAllText($srcFormXmlPath, $enc)
|
$srcFormContent = [System.IO.File]::ReadAllText($srcFormXmlPath, $enc)
|
||||||
|
|
||||||
# 3. Generate form metadata XML (ФормаЭлемента.xml).
|
# 3. Generate form metadata XML (ФормаЭлемента.xml)
|
||||||
# If the wrapper was already borrowed, reuse its uuid so re-borrow is idempotent
|
$newFormUuid = [guid]::NewGuid().ToString()
|
||||||
# (regenerating it would churn the form's identity on every rerun).
|
|
||||||
$formMetaFileExisting = Join-Path (Join-Path (Join-Path (Join-Path $extDir $dirName) $objName) "Forms") "${formName}.xml"
|
|
||||||
$newFormUuid = ""
|
|
||||||
if (Test-Path $formMetaFileExisting) {
|
|
||||||
try {
|
|
||||||
$existingDoc = New-Object System.Xml.XmlDocument
|
|
||||||
$existingDoc.Load($formMetaFileExisting)
|
|
||||||
$existingFormNode = $existingDoc.DocumentElement.SelectSingleNode("*[local-name()='Form']")
|
|
||||||
if ($existingFormNode) {
|
|
||||||
$existingUuid = $existingFormNode.GetAttribute("uuid")
|
|
||||||
if ($existingUuid) { $newFormUuid = $existingUuid }
|
|
||||||
}
|
|
||||||
} catch { }
|
|
||||||
}
|
|
||||||
if (-not $newFormUuid) { $newFormUuid = [guid]::NewGuid().ToString() }
|
|
||||||
$formMetaSb = New-Object System.Text.StringBuilder
|
$formMetaSb = New-Object System.Text.StringBuilder
|
||||||
$formMetaSb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
|
$formMetaSb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
|
||||||
$formMetaSb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
|
$formMetaSb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"2.17`">") | Out-Null
|
||||||
$formMetaSb.AppendLine("`t<Form uuid=`"${newFormUuid}`">") | Out-Null
|
$formMetaSb.AppendLine("`t<Form uuid=`"${newFormUuid}`">") | Out-Null
|
||||||
$formMetaSb.AppendLine("`t`t<InternalInfo/>") | Out-Null
|
$formMetaSb.AppendLine("`t`t<InternalInfo/>") | Out-Null
|
||||||
$formMetaSb.AppendLine("`t`t<Properties>") | Out-Null
|
$formMetaSb.AppendLine("`t`t<Properties>") | Out-Null
|
||||||
@@ -564,10 +497,8 @@ function Borrow-Form {
|
|||||||
$srcFormDoc.Load($srcFormXmlPath)
|
$srcFormDoc.Load($srcFormXmlPath)
|
||||||
$srcFormEl = $srcFormDoc.DocumentElement
|
$srcFormEl = $srcFormDoc.DocumentElement
|
||||||
|
|
||||||
# Borrowed form must use the extension's format version (not the source form's), so the whole
|
$formVersion = $srcFormEl.GetAttribute("version")
|
||||||
# extension stays uniform — otherwise the platform rejects the import on a version mismatch
|
if (-not $formVersion) { $formVersion = "2.17" }
|
||||||
# (e.g. a 2.13 form inside a 2.17 extension). The platform itself upgrades the form to the root version.
|
|
||||||
$formVersion = $script:formatVersion
|
|
||||||
|
|
||||||
# Find direct children: form properties, AutoCommandBar, ChildItems
|
# Find direct children: form properties, AutoCommandBar, ChildItems
|
||||||
$srcAutoCmd = $null
|
$srcAutoCmd = $null
|
||||||
@@ -602,8 +533,13 @@ function Borrow-Form {
|
|||||||
$autoCmdXml = $autoCmdXml -replace '<Autofill>true</Autofill>', '<Autofill>false</Autofill>'
|
$autoCmdXml = $autoCmdXml -replace '<Autofill>true</Autofill>', '<Autofill>false</Autofill>'
|
||||||
# Strip ExcludedCommand (references to standard commands invalid in extension)
|
# Strip ExcludedCommand (references to standard commands invalid in extension)
|
||||||
$autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '')
|
$autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '')
|
||||||
# Strip data-binding tags whose root attribute isn't borrowed
|
# Strip DataPath in AutoCommandBar buttons
|
||||||
$autoCmdXml = Strip-FormBindings $autoCmdXml ([bool]$BorrowMainAttr)
|
if ($BorrowMainAttr) {
|
||||||
|
# Keep only Объект.* DataPaths
|
||||||
|
$autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<DataPath>(?!Объект\.)[^<]*</DataPath>', '')
|
||||||
|
} else {
|
||||||
|
$autoCmdXml = [regex]::Replace($autoCmdXml, '\s*<DataPath>[^<]*</DataPath>', '')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# ChildItems: copy full tree, clean up base-config references
|
# ChildItems: copy full tree, clean up base-config references
|
||||||
@@ -613,9 +549,17 @@ function Borrow-Form {
|
|||||||
$childItemsXml = [regex]::Replace($childItemsXml, $nsStripPattern, '')
|
$childItemsXml = [regex]::Replace($childItemsXml, $nsStripPattern, '')
|
||||||
# Replace all CommandName values with 0
|
# Replace all CommandName values with 0
|
||||||
$childItemsXml = [regex]::Replace($childItemsXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
|
$childItemsXml = [regex]::Replace($childItemsXml, '<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>')
|
||||||
# Strip data-binding tags whose root attribute isn't borrowed
|
# Strip DataPath, TitleDataPath, RowPictureDataPath
|
||||||
# (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*/RowPicture*)
|
if ($BorrowMainAttr) {
|
||||||
$childItemsXml = Strip-FormBindings $childItemsXml ([bool]$BorrowMainAttr)
|
# Keep only Объект.* DataPaths — strip form-attribute DataPaths (not borrowed)
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<DataPath>(?!Объект\.)[^<]*</DataPath>', '')
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<TitleDataPath>(?!Объект\.)[^<]*</TitleDataPath>', '')
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<RowPictureDataPath>[^<]*</RowPictureDataPath>', '')
|
||||||
|
} else {
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<DataPath>[^<]*</DataPath>', '')
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<TitleDataPath>[^<]*</TitleDataPath>', '')
|
||||||
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<RowPictureDataPath>[^<]*</RowPictureDataPath>', '')
|
||||||
|
}
|
||||||
# Strip ExcludedCommand in nested AutoCommandBars (references to standard commands invalid in extension)
|
# Strip ExcludedCommand in nested AutoCommandBars (references to standard commands invalid in extension)
|
||||||
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '')
|
$childItemsXml = [regex]::Replace($childItemsXml, '\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '')
|
||||||
# Strip TypeLink blocks with human-readable DataPath (Items.XXX — can't convert to UUID)
|
# Strip TypeLink blocks with human-readable DataPath (Items.XXX — can't convert to UUID)
|
||||||
@@ -892,19 +836,14 @@ function Borrow-Form {
|
|||||||
[System.IO.File]::WriteAllText($formXmlFile, $formXmlSb.ToString(), $enc)
|
[System.IO.File]::WriteAllText($formXmlFile, $formXmlSb.ToString(), $enc)
|
||||||
Info " Created: $formXmlFile"
|
Info " Created: $formXmlFile"
|
||||||
|
|
||||||
# 6. Create empty Module.bsl — but NEVER overwrite an existing one (re-borrow must
|
# 6. Create empty Module.bsl
|
||||||
# not clobber user code added to the form module).
|
|
||||||
$moduleDir = Join-Path $formXmlDir "Form"
|
$moduleDir = Join-Path $formXmlDir "Form"
|
||||||
if (-not (Test-Path $moduleDir)) {
|
if (-not (Test-Path $moduleDir)) {
|
||||||
New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $moduleDir -Force | Out-Null
|
||||||
}
|
}
|
||||||
$moduleBslFile = Join-Path $moduleDir "Module.bsl"
|
$moduleBslFile = Join-Path $moduleDir "Module.bsl"
|
||||||
if (Test-Path $moduleBslFile) {
|
[System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
|
||||||
Info " Preserved existing Module.bsl"
|
Info " Created: $moduleBslFile"
|
||||||
} else {
|
|
||||||
[System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
|
|
||||||
Info " Created: $moduleBslFile"
|
|
||||||
}
|
|
||||||
|
|
||||||
# 7. Register form in parent object ChildObjects
|
# 7. Register form in parent object ChildObjects
|
||||||
Register-FormInObject $typeName $objName $formName
|
Register-FormInObject $typeName $objName $formName
|
||||||
@@ -1052,29 +991,8 @@ function Collect-FormDataPaths {
|
|||||||
$firstLevel = @{}
|
$firstLevel = @{}
|
||||||
$deepPaths = @()
|
$deepPaths = @()
|
||||||
|
|
||||||
# Scan every data-binding tag (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*)
|
$matches2 = [regex]::Matches($content, '<DataPath>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</DataPath>')
|
||||||
# for Объект.* references — picture-path tags carry picture indices, not data attributes.
|
foreach ($m in $matches2) {
|
||||||
foreach ($tag in $script:formBindingDataTags) {
|
|
||||||
$bms = [regex]::Matches($content, "<$tag>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</$tag>")
|
|
||||||
foreach ($m in $bms) {
|
|
||||||
$path = $m.Groups[1].Value
|
|
||||||
$segments = $path.Split(".")
|
|
||||||
$seg0 = $segments[0]
|
|
||||||
if ($script:standardFields -contains $seg0) { continue }
|
|
||||||
$firstLevel[$seg0] = $true
|
|
||||||
if ($segments.Count -ge 2) {
|
|
||||||
$seg1 = $segments[1]
|
|
||||||
if ($script:standardFields -contains $seg1) { continue }
|
|
||||||
$seg2 = if ($segments.Count -ge 3) { $segments[2] } else { $null }
|
|
||||||
$deepPaths += @{ ObjectAttr = $seg0; SubAttr = $seg1; SubSubAttr = $seg2 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Also scan <Field>Объект.X</Field> — object attributes referenced by filter/conditional-appearance
|
|
||||||
# fields (and dynamic lists), not via a *DataPath binding (e.g. УдалитьЮрФизЛицо). Designer borrows these too.
|
|
||||||
$fieldMatches = [regex]::Matches($content, "<Field>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</Field>")
|
|
||||||
foreach ($m in $fieldMatches) {
|
|
||||||
$path = $m.Groups[1].Value
|
$path = $m.Groups[1].Value
|
||||||
$segments = $path.Split(".")
|
$segments = $path.Split(".")
|
||||||
$seg0 = $segments[0]
|
$seg0 = $segments[0]
|
||||||
@@ -1087,11 +1005,21 @@ function Collect-FormDataPaths {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Also collect from TitleDataPath
|
||||||
|
$matches3 = [regex]::Matches($content, '<TitleDataPath>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</TitleDataPath>')
|
||||||
|
foreach ($m in $matches3) {
|
||||||
|
$path = $m.Groups[1].Value
|
||||||
|
$segments = $path.Split(".")
|
||||||
|
$seg0 = $segments[0]
|
||||||
|
if ($script:standardFields -contains $seg0) { continue }
|
||||||
|
$firstLevel[$seg0] = $true
|
||||||
|
}
|
||||||
|
|
||||||
# Deduplicate deep paths
|
# Deduplicate deep paths
|
||||||
$seen = @{}
|
$seen = @{}
|
||||||
$uniqueDeep = @()
|
$uniqueDeep = @()
|
||||||
foreach ($dp in $deepPaths) {
|
foreach ($dp in $deepPaths) {
|
||||||
$key = "$($dp.ObjectAttr).$($dp.SubAttr).$($dp.SubSubAttr)"
|
$key = "$($dp.ObjectAttr).$($dp.SubAttr)"
|
||||||
if (-not $seen.ContainsKey($key)) {
|
if (-not $seen.ContainsKey($key)) {
|
||||||
$seen[$key] = $true
|
$seen[$key] = $true
|
||||||
$uniqueDeep += $dp
|
$uniqueDeep += $dp
|
||||||
@@ -1195,8 +1123,7 @@ function Resolve-SourceAttributes {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# Extract extra Properties for main object enrichment (Hierarchical, CodeLength, etc.)
|
# Extract extra Properties for main object enrichment (Hierarchical, CodeLength, etc.)
|
||||||
# Ordered so PS emits the same property order as the Python port (dict preserves insertion order).
|
$extraProps = @{}
|
||||||
$extraProps = [ordered]@{}
|
|
||||||
$propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
|
$propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
|
||||||
if ($propsNode) {
|
if ($propsNode) {
|
||||||
$propsToExtract = @("Hierarchical","FoldersOnTop","CodeLength","DescriptionLength","CodeType","CodeAllowedLength",
|
$propsToExtract = @("Hierarchical","FoldersOnTop","CodeLength","DescriptionLength","CodeType","CodeAllowedLength",
|
||||||
@@ -1429,45 +1356,28 @@ function Borrow-MainAttribute {
|
|||||||
# Step 3: Build the adopted content and insert into main object XML
|
# Step 3: Build the adopted content and insert into main object XML
|
||||||
$objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
|
$objFile = Join-Path (Join-Path $extDir $dirName) "${objName}.xml"
|
||||||
|
|
||||||
# Read existing object XML (needed for dedup + enrichment)
|
|
||||||
$objContent = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
|
|
||||||
|
|
||||||
# Dedup: skip attributes/TS already present in object's ChildObjects (idempotent re-borrow)
|
|
||||||
$existingChildNames = @{}
|
|
||||||
if ($objContent -match '(?s)<ChildObjects>(.*?)</ChildObjects>') {
|
|
||||||
foreach ($nm in [regex]::Matches($Matches[1], '<Name>(\w+)</Name>')) {
|
|
||||||
$existingChildNames[$nm.Groups[1].Value] = $true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$insertAttrs = @($srcAttrs | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
|
|
||||||
$insertTS = @($srcTS | Where-Object { -not $existingChildNames.ContainsKey($_.Name) })
|
|
||||||
|
|
||||||
# Generate full object XML with attributes and TS
|
# Generate full object XML with attributes and TS
|
||||||
$contentSb = New-Object System.Text.StringBuilder
|
$contentSb = New-Object System.Text.StringBuilder
|
||||||
foreach ($attr in $insertAttrs) {
|
foreach ($attr in $srcAttrs) {
|
||||||
$attrXml = Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t"
|
$attrXml = Build-AdoptedAttributeXml $attr.Name $attr.Uuid $attr.TypeXml "`t`t`t"
|
||||||
$contentSb.AppendLine($attrXml) | Out-Null
|
$contentSb.AppendLine($attrXml) | Out-Null
|
||||||
}
|
}
|
||||||
foreach ($ts in $insertTS) {
|
foreach ($ts in $srcTS) {
|
||||||
$tsXml = Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes $ts.Attributes "`t`t`t"
|
$tsXml = Build-AdoptedTabularSectionXml $ts.Name $ts.Uuid $ts.GeneratedTypes $ts.Attributes "`t`t`t"
|
||||||
$contentSb.AppendLine($tsXml) | Out-Null
|
$contentSb.AppendLine($tsXml) | Out-Null
|
||||||
}
|
}
|
||||||
$adoptedContent = $contentSb.ToString().TrimEnd()
|
$adoptedContent = $contentSb.ToString().TrimEnd()
|
||||||
|
|
||||||
# Inject extra properties into the object's OWN Properties only — idempotent and anchored to the
|
# Read existing object XML and inject
|
||||||
# first ExtendedConfigurationObject (the object's). On re-borrow, adopted attributes each have their
|
$objContent = [System.IO.File]::ReadAllText($objFile, (New-Object System.Text.UTF8Encoding($true)))
|
||||||
# own ExtendedConfigurationObject; a global replace would push object props inside every <Attribute>.
|
|
||||||
|
# Inject extra properties after ExtendedConfigurationObject
|
||||||
if ($extraProps.Count -gt 0) {
|
if ($extraProps.Count -gt 0) {
|
||||||
$objPropsBlock = ""
|
|
||||||
if ($objContent -match '(?s)<Properties>(.*?)</Properties>') { $objPropsBlock = $Matches[1] }
|
|
||||||
$propsSb = New-Object System.Text.StringBuilder
|
$propsSb = New-Object System.Text.StringBuilder
|
||||||
foreach ($pName in $extraProps.Keys) {
|
foreach ($pName in $extraProps.Keys) {
|
||||||
if ($objPropsBlock -match "<$pName>") { continue }
|
|
||||||
$propsSb.Append("`r`n`t`t`t<${pName}>$($extraProps[$pName])</${pName}>") | Out-Null
|
$propsSb.Append("`r`n`t`t`t<${pName}>$($extraProps[$pName])</${pName}>") | Out-Null
|
||||||
}
|
}
|
||||||
if ($propsSb.Length -gt 0) {
|
$objContent = $objContent -replace '(</ExtendedConfigurationObject>)', "`$1$($propsSb.ToString())"
|
||||||
$objContent = ([regex]'</ExtendedConfigurationObject>').Replace($objContent, "</ExtendedConfigurationObject>$($propsSb.ToString())", 1)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Replace empty ChildObjects with adopted content
|
# Replace empty ChildObjects with adopted content
|
||||||
@@ -1525,46 +1435,79 @@ function Borrow-MainAttribute {
|
|||||||
|
|
||||||
# Step 5: Handle deep paths (Form mode only)
|
# Step 5: Handle deep paths (Form mode only)
|
||||||
if ($mode -eq "Form" -and $deepPaths.Count -gt 0) {
|
if ($mode -eq "Form" -and $deepPaths.Count -gt 0) {
|
||||||
# Top-level ref deep paths: Объект.<Ref>.<Sub> — borrow the ref attribute's catalog with the sub-attribute
|
# Filter out deep paths where ObjectAttr is a TabularSection (those are TS column refs, not deep attribute refs)
|
||||||
$deepByAttr = @{}
|
$realDeep = @()
|
||||||
foreach ($dp in $deepPaths) {
|
foreach ($dp in $deepPaths) {
|
||||||
if ($tsNames.ContainsKey($dp.ObjectAttr)) { continue }
|
if (-not $tsNames.ContainsKey($dp.ObjectAttr)) { $realDeep += $dp }
|
||||||
if (-not $deepByAttr.ContainsKey($dp.ObjectAttr)) { $deepByAttr[$dp.ObjectAttr] = @() }
|
|
||||||
if ($deepByAttr[$dp.ObjectAttr] -notcontains $dp.SubAttr) { $deepByAttr[$dp.ObjectAttr] += $dp.SubAttr }
|
|
||||||
}
|
|
||||||
if ($deepByAttr.Count -gt 0) {
|
|
||||||
Info " Processing $($deepByAttr.Count) deep path attribute(s)..."
|
|
||||||
foreach ($attrName in $deepByAttr.Keys) {
|
|
||||||
$attrInfo = $srcAttrs | Where-Object { $_.Name -eq $attrName } | Select-Object -First 1
|
|
||||||
if (-not $attrInfo) { continue }
|
|
||||||
$catMatch = [regex]::Match($attrInfo.TypeXml, 'cfg:(\w+)Ref\.(\w+)')
|
|
||||||
if (-not $catMatch.Success) { continue }
|
|
||||||
Borrow-DeepTargetAttrs $catMatch.Groups[1].Value $catMatch.Groups[2].Value $deepByAttr[$attrName]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Tabular-section deep paths: Объект.<ТЧ>.<Колонка>.<Sub> — borrow the column's catalog with the sub-attribute
|
if ($realDeep.Count -gt 0) {
|
||||||
$tsDeepByCol = @{}
|
Info " Processing $($realDeep.Count) deep path(s)..."
|
||||||
foreach ($dp in $deepPaths) {
|
|
||||||
if (-not $tsNames.ContainsKey($dp.ObjectAttr)) { continue }
|
# Group by ObjectAttr → target catalog
|
||||||
if (-not $dp.SubSubAttr) { continue }
|
$deepByAttr = @{}
|
||||||
if ($script:standardFields -contains $dp.SubSubAttr) { continue }
|
foreach ($dp in $realDeep) {
|
||||||
$k = "$($dp.ObjectAttr)|$($dp.SubAttr)"
|
if (-not $deepByAttr.ContainsKey($dp.ObjectAttr)) { $deepByAttr[$dp.ObjectAttr] = @() }
|
||||||
if (-not $tsDeepByCol.ContainsKey($k)) { $tsDeepByCol[$k] = @() }
|
$deepByAttr[$dp.ObjectAttr] += $dp.SubAttr
|
||||||
if ($tsDeepByCol[$k] -notcontains $dp.SubSubAttr) { $tsDeepByCol[$k] += $dp.SubSubAttr }
|
}
|
||||||
}
|
|
||||||
if ($tsDeepByCol.Count -gt 0) {
|
foreach ($attrName in $deepByAttr.Keys) {
|
||||||
Info " Processing $($tsDeepByCol.Count) tabular-section deep path(s)..."
|
# Find the attribute's type to determine target catalog
|
||||||
foreach ($k in $tsDeepByCol.Keys) {
|
$attrInfo = $srcAttrs | Where-Object { $_.Name -eq $attrName } | Select-Object -First 1
|
||||||
$parts = $k.Split("|")
|
if (-not $attrInfo) { continue }
|
||||||
$tsName = $parts[0]; $colName = $parts[1]
|
|
||||||
$tsInfo = $srcTS | Where-Object { $_.Name -eq $tsName } | Select-Object -First 1
|
# Extract catalog name from type: cfg:CatalogRef.XXX
|
||||||
if (-not $tsInfo) { continue }
|
$catMatch = [regex]::Match($attrInfo.TypeXml, 'cfg:(\w+)Ref\.(\w+)')
|
||||||
$colInfo = $tsInfo.Attributes | Where-Object { $_.Name -eq $colName } | Select-Object -First 1
|
|
||||||
if (-not $colInfo) { continue }
|
|
||||||
$catMatch = [regex]::Match($colInfo.TypeXml, 'cfg:(\w+)Ref\.(\w+)')
|
|
||||||
if (-not $catMatch.Success) { continue }
|
if (-not $catMatch.Success) { continue }
|
||||||
Borrow-DeepTargetAttrs $catMatch.Groups[1].Value $catMatch.Groups[2].Value $tsDeepByCol[$k]
|
|
||||||
|
$targetTypeName = $catMatch.Groups[1].Value
|
||||||
|
$targetObjName = $catMatch.Groups[2].Value
|
||||||
|
|
||||||
|
# Ensure target is borrowed
|
||||||
|
if (-not (Test-ObjectBorrowed $targetTypeName $targetObjName)) {
|
||||||
|
$tSrc = Read-SourceObject $targetTypeName $targetObjName
|
||||||
|
$tBorrowedXml = Build-BorrowedObjectXml $targetTypeName $targetObjName $tSrc.Uuid $tSrc.Properties
|
||||||
|
$tTargetDir = Join-Path $extDir $childTypeDirMap[$targetTypeName]
|
||||||
|
if (-not (Test-Path $tTargetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $tTargetDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
$tTargetFile = Join-Path $tTargetDir "${targetObjName}.xml"
|
||||||
|
[System.IO.File]::WriteAllText($tTargetFile, $tBorrowedXml, $encBom)
|
||||||
|
Add-ToChildObjects $targetTypeName $targetObjName
|
||||||
|
$script:borrowedFiles += $tTargetFile
|
||||||
|
Info " Auto-borrowed for deep path: ${targetTypeName}.${targetObjName}"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Resolve sub-attributes in target catalog
|
||||||
|
$subNames = @{}
|
||||||
|
foreach ($sn in $deepByAttr[$attrName]) { $subNames[$sn] = $true }
|
||||||
|
$subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
|
||||||
|
|
||||||
|
if ($subResolved.Attributes.Count -gt 0) {
|
||||||
|
Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
|
||||||
|
|
||||||
|
# Collect and borrow ref types from deep attributes
|
||||||
|
$subTypeXmls = @()
|
||||||
|
foreach ($sa in $subResolved.Attributes) { $subTypeXmls += $sa.TypeXml }
|
||||||
|
$subRefTypes = Collect-ReferenceTypes $subTypeXmls
|
||||||
|
foreach ($srt in $subRefTypes) {
|
||||||
|
if (-not $childTypeDirMap.ContainsKey($srt.TypeName)) { continue }
|
||||||
|
if (Test-ObjectBorrowed $srt.TypeName $srt.ObjName) { continue }
|
||||||
|
$sSrcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$srt.TypeName]) "$($srt.ObjName).xml"
|
||||||
|
if (-not (Test-Path $sSrcFile)) { continue }
|
||||||
|
$sSrc = Read-SourceObject $srt.TypeName $srt.ObjName
|
||||||
|
$sBorrowedXml = Build-BorrowedObjectXml $srt.TypeName $srt.ObjName $sSrc.Uuid $sSrc.Properties
|
||||||
|
$sTargetDir = Join-Path $extDir $childTypeDirMap[$srt.TypeName]
|
||||||
|
if (-not (Test-Path $sTargetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $sTargetDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
$sTargetFile = Join-Path $sTargetDir "$($srt.ObjName).xml"
|
||||||
|
[System.IO.File]::WriteAllText($sTargetFile, $sBorrowedXml, $encBom)
|
||||||
|
Add-ToChildObjects $srt.TypeName $srt.ObjName
|
||||||
|
$script:borrowedFiles += $sTargetFile
|
||||||
|
Info " Auto-borrowed (deep): $($srt.TypeName).$($srt.ObjName)"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1572,57 +1515,6 @@ function Borrow-MainAttribute {
|
|||||||
Info " Main attribute borrowing complete"
|
Info " Main attribute borrowing complete"
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 11i. Helper: borrow a deep-path target catalog together with the referenced sub-attributes ---
|
|
||||||
# Used for both Объект.<Ref>.<Sub> (top-level ref attr) and Объект.<ТЧ>.<Колонка>.<Sub> (tabular-section
|
|
||||||
# column ref). Mirrors Designer: the referenced catalog is adopted WITH the sub-attributes the form shows,
|
|
||||||
# otherwise the platform rejects the deep DataPath ("Неверный путь к данным").
|
|
||||||
function Borrow-DeepTargetAttrs {
|
|
||||||
param([string]$targetTypeName, [string]$targetObjName, $subAttrNames)
|
|
||||||
|
|
||||||
$encBomLocal = New-Object System.Text.UTF8Encoding($true)
|
|
||||||
|
|
||||||
# Ensure target is borrowed (shell)
|
|
||||||
if (-not (Test-ObjectBorrowed $targetTypeName $targetObjName)) {
|
|
||||||
$tSrc = Read-SourceObject $targetTypeName $targetObjName
|
|
||||||
$tBorrowedXml = Build-BorrowedObjectXml $targetTypeName $targetObjName $tSrc.Uuid $tSrc.Properties
|
|
||||||
$tTargetDir = Join-Path $extDir $childTypeDirMap[$targetTypeName]
|
|
||||||
if (-not (Test-Path $tTargetDir)) { New-Item -ItemType Directory -Path $tTargetDir -Force | Out-Null }
|
|
||||||
$tTargetFile = Join-Path $tTargetDir "${targetObjName}.xml"
|
|
||||||
[System.IO.File]::WriteAllText($tTargetFile, $tBorrowedXml, $encBomLocal)
|
|
||||||
Add-ToChildObjects $targetTypeName $targetObjName
|
|
||||||
$script:borrowedFiles += $tTargetFile
|
|
||||||
Info " Auto-borrowed for deep path: ${targetTypeName}.${targetObjName}"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Resolve sub-attributes in target catalog and merge them in
|
|
||||||
$subNames = @{}
|
|
||||||
foreach ($sn in $subAttrNames) { $subNames[$sn] = $true }
|
|
||||||
$subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
|
|
||||||
if ($subResolved.Attributes.Count -gt 0) {
|
|
||||||
Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
|
|
||||||
|
|
||||||
# Borrow ref types referenced by the sub-attributes
|
|
||||||
$subTypeXmls = @()
|
|
||||||
foreach ($sa in $subResolved.Attributes) { $subTypeXmls += $sa.TypeXml }
|
|
||||||
$subRefTypes = Collect-ReferenceTypes $subTypeXmls
|
|
||||||
foreach ($srt in $subRefTypes) {
|
|
||||||
if (-not $childTypeDirMap.ContainsKey($srt.TypeName)) { continue }
|
|
||||||
if (Test-ObjectBorrowed $srt.TypeName $srt.ObjName) { continue }
|
|
||||||
$sSrcFile = Join-Path (Join-Path $cfgDir $childTypeDirMap[$srt.TypeName]) "$($srt.ObjName).xml"
|
|
||||||
if (-not (Test-Path $sSrcFile)) { continue }
|
|
||||||
$sSrc = Read-SourceObject $srt.TypeName $srt.ObjName
|
|
||||||
$sBorrowedXml = Build-BorrowedObjectXml $srt.TypeName $srt.ObjName $sSrc.Uuid $sSrc.Properties
|
|
||||||
$sTargetDir = Join-Path $extDir $childTypeDirMap[$srt.TypeName]
|
|
||||||
if (-not (Test-Path $sTargetDir)) { New-Item -ItemType Directory -Path $sTargetDir -Force | Out-Null }
|
|
||||||
$sTargetFile = Join-Path $sTargetDir "$($srt.ObjName).xml"
|
|
||||||
[System.IO.File]::WriteAllText($sTargetFile, $sBorrowedXml, $encBomLocal)
|
|
||||||
Add-ToChildObjects $srt.TypeName $srt.ObjName
|
|
||||||
$script:borrowedFiles += $sTargetFile
|
|
||||||
Info " Auto-borrowed (deep): $($srt.TypeName).$($srt.ObjName)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 12. Helper: build borrowed object XML ---
|
# --- 12. Helper: build borrowed object XML ---
|
||||||
function Build-BorrowedObjectXml {
|
function Build-BorrowedObjectXml {
|
||||||
param(
|
param(
|
||||||
@@ -1637,7 +1529,7 @@ function Build-BorrowedObjectXml {
|
|||||||
|
|
||||||
$sb = New-Object System.Text.StringBuilder
|
$sb = New-Object System.Text.StringBuilder
|
||||||
$sb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
|
$sb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
|
||||||
$sb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"$($script:formatVersion)`">") | Out-Null
|
$sb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"2.17`">") | Out-Null
|
||||||
$sb.AppendLine("`t<${typeName} uuid=`"${newUuid}`">") | Out-Null
|
$sb.AppendLine("`t<${typeName} uuid=`"${newUuid}`">") | Out-Null
|
||||||
|
|
||||||
# InternalInfo
|
# InternalInfo
|
||||||
@@ -1661,11 +1553,6 @@ function Build-BorrowedObjectXml {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# DefinedType: emit the carried <Type> definition (needed for the alias to resolve, e.g. totals)
|
|
||||||
if ($typeName -eq "DefinedType" -and $sourceProps.ContainsKey("__TypeXml")) {
|
|
||||||
$sb.AppendLine("`t`t`t$($sourceProps['__TypeXml'])") | Out-Null
|
|
||||||
}
|
|
||||||
|
|
||||||
$sb.AppendLine("`t`t</Properties>") | Out-Null
|
$sb.AppendLine("`t`t</Properties>") | Out-Null
|
||||||
|
|
||||||
# ChildObjects (for types that need it)
|
# ChildObjects (for types that need it)
|
||||||
+116
-225
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cfe-borrow v1.8 — Borrow objects from configuration into extension (CFE)
|
# cfe-borrow v1.2 — Borrow objects from configuration into extension (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -14,36 +14,6 @@ XR_NS = "http://v8.1c.ru/8.3/xcf/readable"
|
|||||||
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
|
XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
|
||||||
V8_NS = "http://v8.1c.ru/8.1/data/core"
|
V8_NS = "http://v8.1c.ru/8.1/data/core"
|
||||||
|
|
||||||
# Form data-binding tags (value = attribute path). A binding survives only if its root
|
|
||||||
# attribute is borrowed into the form's <Attributes>; otherwise it must be stripped or the
|
|
||||||
# platform rejects the form with "Неверный путь к данным" on load.
|
|
||||||
FORM_BINDING_DATA_TAGS = ["DataPath", "TitleDataPath", "FooterDataPath", "HeaderDataPath", "MultipleValueDataPath", "MultipleValuePresentDataPath"]
|
|
||||||
# Picture-path binding tags (value = picture index path, never a data attribute) — always stripped in the skeleton.
|
|
||||||
FORM_BINDING_PICTURE_TAGS = ["RowPictureDataPath", "MultipleValuePictureDataPath"]
|
|
||||||
|
|
||||||
|
|
||||||
def strip_form_bindings(xml, keep_objekt):
|
|
||||||
"""Strip data-binding tags whose root attribute isn't borrowed.
|
|
||||||
keep_objekt=True (BorrowMainAttribute): keep Объект.* data bindings, strip the rest.
|
|
||||||
keep_objekt=False (default skeleton): strip all bindings. Picture-path tags are always stripped."""
|
|
||||||
for tag in FORM_BINDING_DATA_TAGS:
|
|
||||||
if keep_objekt:
|
|
||||||
xml = re.sub(rf'\s*<{tag}>(?!Объект\.)[^<]*</{tag}>', '', xml)
|
|
||||||
else:
|
|
||||||
xml = re.sub(rf'\s*<{tag}>[^<]*</{tag}>', '', xml)
|
|
||||||
for tag in FORM_BINDING_PICTURE_TAGS:
|
|
||||||
xml = re.sub(rf'\s*<{tag}>[^<]*</{tag}>', '', xml)
|
|
||||||
return xml
|
|
||||||
|
|
||||||
|
|
||||||
def decode_numeric_entities(s):
|
|
||||||
"""lxml emits numeric character refs (&#xNNNN;) for non-ASCII in some self-closed
|
|
||||||
elements where the PowerShell port writes literal characters. Normalize numeric refs
|
|
||||||
back to literal so PS↔PY output matches. Named entities (& < ...) are left intact."""
|
|
||||||
s = re.sub(r'&#x([0-9A-Fa-f]+);', lambda m: chr(int(m.group(1), 16)), s)
|
|
||||||
s = re.sub(r'&#(\d+);', lambda m: chr(int(m.group(1))), s)
|
|
||||||
return s
|
|
||||||
|
|
||||||
|
|
||||||
def localname(el):
|
def localname(el):
|
||||||
return etree.QName(el.tag).localname
|
return etree.QName(el.tag).localname
|
||||||
@@ -284,22 +254,6 @@ XMLNS_DECL = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
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 get_child_indent(container):
|
def get_child_indent(container):
|
||||||
if container.text and "\n" in container.text:
|
if container.text and "\n" in container.text:
|
||||||
after_nl = container.text.rsplit("\n", 1)[-1]
|
after_nl = container.text.rsplit("\n", 1)[-1]
|
||||||
@@ -351,9 +305,7 @@ def expand_self_closing(container, parent_indent):
|
|||||||
|
|
||||||
def save_xml_bom(tree, path):
|
def save_xml_bom(tree, path):
|
||||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
if not xml_bytes.endswith(b"\n"):
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
with open(path, "wb") as f:
|
with open(path, "wb") as f:
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
@@ -411,8 +363,6 @@ def main():
|
|||||||
cfg_resolved = os.path.abspath(cfg_path)
|
cfg_resolved = os.path.abspath(cfg_path)
|
||||||
cfg_dir = os.path.dirname(cfg_resolved)
|
cfg_dir = os.path.dirname(cfg_resolved)
|
||||||
|
|
||||||
format_version = detect_format_version(ext_dir)
|
|
||||||
|
|
||||||
# --- 2. Load extension Configuration.xml ---
|
# --- 2. Load extension Configuration.xml ---
|
||||||
xml_parser = etree.XMLParser(remove_blank_text=False)
|
xml_parser = etree.XMLParser(remove_blank_text=False)
|
||||||
tree = etree.parse(ext_resolved, xml_parser)
|
tree = etree.parse(ext_resolved, xml_parser)
|
||||||
@@ -492,13 +442,6 @@ def main():
|
|||||||
prop_node = props_node.find(f"{{{MD_NS}}}{prop_name}")
|
prop_node = props_node.find(f"{{{MD_NS}}}{prop_name}")
|
||||||
if prop_node is not None:
|
if prop_node is not None:
|
||||||
src_props[prop_name] = (prop_node.text or "").strip()
|
src_props[prop_name] = (prop_node.text or "").strip()
|
||||||
# DefinedType: carry the <Type> definition. A type alias is meaningless as a bare shell —
|
|
||||||
# the platform needs its underlying type (e.g. to know a column is a summable Number for totals).
|
|
||||||
if type_name == "DefinedType":
|
|
||||||
type_node = props_node.find(f"{{{MD_NS}}}Type")
|
|
||||||
if type_node is not None:
|
|
||||||
type_xml = etree.tostring(type_node, encoding="unicode")
|
|
||||||
src_props["__TypeXml"] = re.sub(r'\s+xmlns(?::\w+)?="[^"]*"', '', type_xml)
|
|
||||||
|
|
||||||
return {"Uuid": src_uuid, "Properties": src_props, "Element": src_el}
|
return {"Uuid": src_uuid, "Properties": src_props, "Element": src_el}
|
||||||
|
|
||||||
@@ -556,7 +499,7 @@ def main():
|
|||||||
|
|
||||||
lines = []
|
lines = []
|
||||||
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
|
lines.append('<?xml version="1.0" encoding="UTF-8"?>')
|
||||||
lines.append(f'<MetaDataObject {XMLNS_DECL} version="{format_version}">')
|
lines.append(f'<MetaDataObject {XMLNS_DECL} version="2.17">')
|
||||||
lines.append(f'\t<{type_name} uuid="{new_uuid_val}">')
|
lines.append(f'\t<{type_name} uuid="{new_uuid_val}">')
|
||||||
lines.append(internal_info_xml)
|
lines.append(internal_info_xml)
|
||||||
lines.append("\t\t<Properties>")
|
lines.append("\t\t<Properties>")
|
||||||
@@ -570,10 +513,6 @@ def main():
|
|||||||
prop_val = source_props.get(prop_name, "false")
|
prop_val = source_props.get(prop_name, "false")
|
||||||
lines.append(f"\t\t\t<{prop_name}>{prop_val}</{prop_name}>")
|
lines.append(f"\t\t\t<{prop_name}>{prop_val}</{prop_name}>")
|
||||||
|
|
||||||
# DefinedType: emit the carried <Type> definition (needed for the alias to resolve, e.g. totals)
|
|
||||||
if type_name == "DefinedType" and "__TypeXml" in source_props:
|
|
||||||
lines.append(f"\t\t\t{source_props['__TypeXml']}")
|
|
||||||
|
|
||||||
lines.append("\t\t</Properties>")
|
lines.append("\t\t</Properties>")
|
||||||
|
|
||||||
if type_name in TYPES_WITH_CHILD_OBJECTS:
|
if type_name in TYPES_WITH_CHILD_OBJECTS:
|
||||||
@@ -685,26 +624,7 @@ def main():
|
|||||||
first_level = {}
|
first_level = {}
|
||||||
deep_paths = []
|
deep_paths = []
|
||||||
|
|
||||||
# Scan every data-binding tag (DataPath/TitleDataPath/FooterDataPath/HeaderDataPath/MultipleValue*)
|
for m in re.finditer(r'<DataPath>[^<]*\b\u041e\u0431\u044a\u0435\u043a\u0442\.(\w+(?:\.\w+)*)</DataPath>', content):
|
||||||
# for Объект.* references — picture-path tags carry picture indices, not data attributes.
|
|
||||||
for tag in FORM_BINDING_DATA_TAGS:
|
|
||||||
for m in re.finditer(r'<' + tag + r'>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</' + tag + r'>', content):
|
|
||||||
path = m.group(1)
|
|
||||||
segments = path.split(".")
|
|
||||||
seg0 = segments[0]
|
|
||||||
if seg0 in STANDARD_FIELDS:
|
|
||||||
continue
|
|
||||||
first_level[seg0] = True
|
|
||||||
if len(segments) >= 2:
|
|
||||||
seg1 = segments[1]
|
|
||||||
if seg1 in STANDARD_FIELDS:
|
|
||||||
continue
|
|
||||||
seg2 = segments[2] if len(segments) >= 3 else None
|
|
||||||
deep_paths.append({"ObjectAttr": seg0, "SubAttr": seg1, "SubSubAttr": seg2})
|
|
||||||
|
|
||||||
# Also scan <Field>Объект.X</Field> — object attributes referenced by filter/conditional-appearance
|
|
||||||
# fields (and dynamic lists), not via a *DataPath binding (e.g. УдалитьЮрФизЛицо). Designer borrows these too.
|
|
||||||
for m in re.finditer(r'<Field>[^<]*\bОбъект\.(\w+(?:\.\w+)*)</Field>', content):
|
|
||||||
path = m.group(1)
|
path = m.group(1)
|
||||||
segments = path.split(".")
|
segments = path.split(".")
|
||||||
seg0 = segments[0]
|
seg0 = segments[0]
|
||||||
@@ -715,14 +635,22 @@ def main():
|
|||||||
seg1 = segments[1]
|
seg1 = segments[1]
|
||||||
if seg1 in STANDARD_FIELDS:
|
if seg1 in STANDARD_FIELDS:
|
||||||
continue
|
continue
|
||||||
seg2 = segments[2] if len(segments) >= 3 else None
|
deep_paths.append({"ObjectAttr": seg0, "SubAttr": seg1})
|
||||||
deep_paths.append({"ObjectAttr": seg0, "SubAttr": seg1, "SubSubAttr": seg2})
|
|
||||||
|
# Also collect from TitleDataPath
|
||||||
|
for m in re.finditer(r'<TitleDataPath>[^<]*\b\u041e\u0431\u044a\u0435\u043a\u0442\.(\w+(?:\.\w+)*)</TitleDataPath>', content):
|
||||||
|
path = m.group(1)
|
||||||
|
segments = path.split(".")
|
||||||
|
seg0 = segments[0]
|
||||||
|
if seg0 in STANDARD_FIELDS:
|
||||||
|
continue
|
||||||
|
first_level[seg0] = True
|
||||||
|
|
||||||
# Deduplicate deep paths
|
# Deduplicate deep paths
|
||||||
seen = set()
|
seen = set()
|
||||||
unique_deep = []
|
unique_deep = []
|
||||||
for dp in deep_paths:
|
for dp in deep_paths:
|
||||||
key = f"{dp['ObjectAttr']}.{dp['SubAttr']}.{dp.get('SubSubAttr')}"
|
key = f"{dp['ObjectAttr']}.{dp['SubAttr']}"
|
||||||
if key not in seen:
|
if key not in seen:
|
||||||
seen.add(key)
|
seen.add(key)
|
||||||
unique_deep.append(dp)
|
unique_deep.append(dp)
|
||||||
@@ -993,40 +921,26 @@ def main():
|
|||||||
# Step 3: Build the adopted content and insert into main object XML
|
# Step 3: Build the adopted content and insert into main object XML
|
||||||
obj_file = os.path.join(ext_dir, dir_name, f"{obj_name}.xml")
|
obj_file = os.path.join(ext_dir, dir_name, f"{obj_name}.xml")
|
||||||
|
|
||||||
# Read existing object XML (needed for dedup + enrichment)
|
# Generate full object XML with attributes and TS
|
||||||
|
content_parts = []
|
||||||
|
for attr in src_attrs:
|
||||||
|
attr_xml = build_adopted_attribute_xml(attr["Name"], attr["Uuid"], attr["TypeXml"], "\t\t\t")
|
||||||
|
content_parts.append(attr_xml)
|
||||||
|
for ts in src_ts:
|
||||||
|
ts_xml = build_adopted_tabular_section_xml(ts["Name"], ts["Uuid"], ts["GeneratedTypes"], ts["Attributes"], "\t\t\t")
|
||||||
|
content_parts.append(ts_xml)
|
||||||
|
adopted_content = "\n".join(content_parts).rstrip()
|
||||||
|
|
||||||
|
# Read existing object XML and inject
|
||||||
with open(obj_file, "r", encoding="utf-8-sig") as fh:
|
with open(obj_file, "r", encoding="utf-8-sig") as fh:
|
||||||
obj_content = fh.read()
|
obj_content = fh.read()
|
||||||
|
|
||||||
# Dedup: skip attributes/TS already present in object's ChildObjects (idempotent re-borrow)
|
# Inject extra properties after ExtendedConfigurationObject
|
||||||
existing_child_names = set()
|
|
||||||
m_co = re.search(r'(?s)<ChildObjects>(.*?)</ChildObjects>', obj_content)
|
|
||||||
if m_co:
|
|
||||||
for nm in re.findall(r'<Name>(\w+)</Name>', m_co.group(1)):
|
|
||||||
existing_child_names.add(nm)
|
|
||||||
insert_attrs = [a for a in src_attrs if a["Name"] not in existing_child_names]
|
|
||||||
insert_ts = [t for t in src_ts if t["Name"] not in existing_child_names]
|
|
||||||
|
|
||||||
# Generate full object XML with attributes and TS
|
|
||||||
content_parts = []
|
|
||||||
for attr in insert_attrs:
|
|
||||||
content_parts.append(build_adopted_attribute_xml(attr["Name"], attr["Uuid"], attr["TypeXml"], "\t\t\t"))
|
|
||||||
for ts in insert_ts:
|
|
||||||
content_parts.append(build_adopted_tabular_section_xml(ts["Name"], ts["Uuid"], ts["GeneratedTypes"], ts["Attributes"], "\t\t\t"))
|
|
||||||
adopted_content = "\n".join(content_parts).rstrip()
|
|
||||||
|
|
||||||
# Inject extra properties into the object's OWN Properties only — idempotent and anchored to the
|
|
||||||
# first ExtendedConfigurationObject (the object's). On re-borrow, adopted attributes each have their
|
|
||||||
# own ExtendedConfigurationObject; a global replace would push object props inside every <Attribute>.
|
|
||||||
if extra_props:
|
if extra_props:
|
||||||
m_props = re.search(r'(?s)<Properties>(.*?)</Properties>', obj_content)
|
|
||||||
obj_props_block = m_props.group(1) if m_props else ""
|
|
||||||
props_xml = ""
|
props_xml = ""
|
||||||
for p_name, p_val in extra_props.items():
|
for p_name, p_val in extra_props.items():
|
||||||
if f"<{p_name}>" in obj_props_block:
|
|
||||||
continue
|
|
||||||
props_xml += f"\r\n\t\t\t<{p_name}>{p_val}</{p_name}>"
|
props_xml += f"\r\n\t\t\t<{p_name}>{p_val}</{p_name}>"
|
||||||
if props_xml:
|
obj_content = obj_content.replace("</ExtendedConfigurationObject>", f"</ExtendedConfigurationObject>{props_xml}")
|
||||||
obj_content = obj_content.replace("</ExtendedConfigurationObject>", f"</ExtendedConfigurationObject>{props_xml}", 1)
|
|
||||||
|
|
||||||
# Replace empty ChildObjects with adopted content
|
# Replace empty ChildObjects with adopted content
|
||||||
if adopted_content:
|
if adopted_content:
|
||||||
@@ -1078,93 +992,79 @@ def main():
|
|||||||
|
|
||||||
# Step 5: Handle deep paths (Form mode only)
|
# Step 5: Handle deep paths (Form mode only)
|
||||||
if mode == "Form" and deep_paths:
|
if mode == "Form" and deep_paths:
|
||||||
# Top-level ref deep paths: Объект.<Ref>.<Sub> — borrow the ref attribute's catalog with the sub-attribute
|
# Filter out deep paths where ObjectAttr is a TabularSection
|
||||||
deep_by_attr = {}
|
real_deep = [dp for dp in deep_paths if dp["ObjectAttr"] not in ts_names]
|
||||||
for dp in deep_paths:
|
|
||||||
if dp["ObjectAttr"] in ts_names:
|
if real_deep:
|
||||||
continue
|
info(f" Processing {len(real_deep)} deep path(s)...")
|
||||||
deep_by_attr.setdefault(dp["ObjectAttr"], [])
|
|
||||||
if dp["SubAttr"] not in deep_by_attr[dp["ObjectAttr"]]:
|
# Group by ObjectAttr -> target catalog
|
||||||
|
deep_by_attr = {}
|
||||||
|
for dp in real_deep:
|
||||||
|
if dp["ObjectAttr"] not in deep_by_attr:
|
||||||
|
deep_by_attr[dp["ObjectAttr"]] = []
|
||||||
deep_by_attr[dp["ObjectAttr"]].append(dp["SubAttr"])
|
deep_by_attr[dp["ObjectAttr"]].append(dp["SubAttr"])
|
||||||
if deep_by_attr:
|
|
||||||
info(f" Processing {len(deep_by_attr)} deep path attribute(s)...")
|
|
||||||
for attr_name, sub_attr_names in deep_by_attr.items():
|
for attr_name, sub_attr_names in deep_by_attr.items():
|
||||||
attr_info = next((a for a in src_attrs if a["Name"] == attr_name), None)
|
# Find the attribute's type to determine target catalog
|
||||||
|
attr_info = None
|
||||||
|
for a in src_attrs:
|
||||||
|
if a["Name"] == attr_name:
|
||||||
|
attr_info = a
|
||||||
|
break
|
||||||
if not attr_info:
|
if not attr_info:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
# Extract catalog name from type: cfg:CatalogRef.XXX
|
||||||
cat_match = re.search(r'cfg:(\w+)Ref\.(\w+)', attr_info["TypeXml"])
|
cat_match = re.search(r'cfg:(\w+)Ref\.(\w+)', attr_info["TypeXml"])
|
||||||
if not cat_match:
|
if not cat_match:
|
||||||
continue
|
continue
|
||||||
borrow_deep_target_attrs(cat_match.group(1), cat_match.group(2), sub_attr_names)
|
|
||||||
|
|
||||||
# Tabular-section deep paths: Объект.<ТЧ>.<Колонка>.<Sub> — borrow the column's catalog with the sub-attribute
|
target_type_name = cat_match.group(1)
|
||||||
ts_deep_by_col = {}
|
target_obj_name = cat_match.group(2)
|
||||||
for dp in deep_paths:
|
|
||||||
if dp["ObjectAttr"] not in ts_names:
|
# Ensure target is borrowed
|
||||||
continue
|
if not test_object_borrowed(target_type_name, target_obj_name):
|
||||||
if not dp.get("SubSubAttr"):
|
t_src = read_source_object(target_type_name, target_obj_name)
|
||||||
continue
|
t_borrowed_xml = build_borrowed_object_xml(target_type_name, target_obj_name, t_src["Uuid"], t_src["Properties"])
|
||||||
if dp["SubSubAttr"] in STANDARD_FIELDS:
|
t_target_dir = os.path.join(ext_dir, CHILD_TYPE_DIR_MAP[target_type_name])
|
||||||
continue
|
os.makedirs(t_target_dir, exist_ok=True)
|
||||||
k = (dp["ObjectAttr"], dp["SubAttr"])
|
t_target_file = os.path.join(t_target_dir, f"{target_obj_name}.xml")
|
||||||
ts_deep_by_col.setdefault(k, [])
|
save_text_bom(t_target_file, t_borrowed_xml)
|
||||||
if dp["SubSubAttr"] not in ts_deep_by_col[k]:
|
add_to_child_objects(target_type_name, target_obj_name)
|
||||||
ts_deep_by_col[k].append(dp["SubSubAttr"])
|
borrowed_files.append(t_target_file)
|
||||||
if ts_deep_by_col:
|
info(f" Auto-borrowed for deep path: {target_type_name}.{target_obj_name}")
|
||||||
info(f" Processing {len(ts_deep_by_col)} tabular-section deep path(s)...")
|
|
||||||
for (ts_name, col_name), sub_attr_names in ts_deep_by_col.items():
|
# Resolve sub-attributes in target catalog
|
||||||
ts_info = next((t for t in src_ts if t["Name"] == ts_name), None)
|
sub_names = {sn: True for sn in sub_attr_names}
|
||||||
if not ts_info:
|
sub_resolved = resolve_source_attributes(target_type_name, target_obj_name, sub_names)
|
||||||
continue
|
|
||||||
col_info = next((c for c in ts_info["Attributes"] if c["Name"] == col_name), None)
|
if sub_resolved["Attributes"]:
|
||||||
if not col_info:
|
merge_attributes_into_object(target_type_name, target_obj_name, sub_resolved["Attributes"])
|
||||||
continue
|
|
||||||
cat_match = re.search(r'cfg:(\w+)Ref\.(\w+)', col_info["TypeXml"])
|
# Collect and borrow ref types from deep attributes
|
||||||
if not cat_match:
|
sub_type_xmls = [sa["TypeXml"] for sa in sub_resolved["Attributes"]]
|
||||||
continue
|
sub_ref_types = collect_reference_types(sub_type_xmls)
|
||||||
borrow_deep_target_attrs(cat_match.group(1), cat_match.group(2), sub_attr_names)
|
for srt in sub_ref_types:
|
||||||
|
if srt["TypeName"] not in CHILD_TYPE_DIR_MAP:
|
||||||
|
continue
|
||||||
|
if test_object_borrowed(srt["TypeName"], srt["ObjName"]):
|
||||||
|
continue
|
||||||
|
s_src_file = os.path.join(cfg_dir, CHILD_TYPE_DIR_MAP[srt["TypeName"]], f"{srt['ObjName']}.xml")
|
||||||
|
if not os.path.isfile(s_src_file):
|
||||||
|
continue
|
||||||
|
s_src = read_source_object(srt["TypeName"], srt["ObjName"])
|
||||||
|
s_borrowed_xml = build_borrowed_object_xml(srt["TypeName"], srt["ObjName"], s_src["Uuid"], s_src["Properties"])
|
||||||
|
s_target_dir = os.path.join(ext_dir, CHILD_TYPE_DIR_MAP[srt["TypeName"]])
|
||||||
|
os.makedirs(s_target_dir, exist_ok=True)
|
||||||
|
s_target_file = os.path.join(s_target_dir, f"{srt['ObjName']}.xml")
|
||||||
|
save_text_bom(s_target_file, s_borrowed_xml)
|
||||||
|
add_to_child_objects(srt["TypeName"], srt["ObjName"])
|
||||||
|
borrowed_files.append(s_target_file)
|
||||||
|
info(f" Auto-borrowed (deep): {srt['TypeName']}.{srt['ObjName']}")
|
||||||
|
|
||||||
info(" Main attribute borrowing complete")
|
info(" Main attribute borrowing complete")
|
||||||
|
|
||||||
def borrow_deep_target_attrs(target_type_name, target_obj_name, sub_attr_names):
|
|
||||||
# Borrow a deep-path target catalog together with the referenced sub-attributes, for both
|
|
||||||
# Объект.<Ref>.<Sub> and Объект.<ТЧ>.<Колонка>.<Sub>. Mirrors Designer: the referenced catalog
|
|
||||||
# is adopted WITH the sub-attributes the form shows, else the platform rejects the deep DataPath.
|
|
||||||
if not test_object_borrowed(target_type_name, target_obj_name):
|
|
||||||
t_src = read_source_object(target_type_name, target_obj_name)
|
|
||||||
t_borrowed_xml = build_borrowed_object_xml(target_type_name, target_obj_name, t_src["Uuid"], t_src["Properties"])
|
|
||||||
t_target_dir = os.path.join(ext_dir, CHILD_TYPE_DIR_MAP[target_type_name])
|
|
||||||
os.makedirs(t_target_dir, exist_ok=True)
|
|
||||||
t_target_file = os.path.join(t_target_dir, f"{target_obj_name}.xml")
|
|
||||||
save_text_bom(t_target_file, t_borrowed_xml)
|
|
||||||
add_to_child_objects(target_type_name, target_obj_name)
|
|
||||||
borrowed_files.append(t_target_file)
|
|
||||||
info(f" Auto-borrowed for deep path: {target_type_name}.{target_obj_name}")
|
|
||||||
|
|
||||||
sub_names = {sn: True for sn in sub_attr_names}
|
|
||||||
sub_resolved = resolve_source_attributes(target_type_name, target_obj_name, sub_names)
|
|
||||||
if sub_resolved["Attributes"]:
|
|
||||||
merge_attributes_into_object(target_type_name, target_obj_name, sub_resolved["Attributes"])
|
|
||||||
sub_type_xmls = [sa["TypeXml"] for sa in sub_resolved["Attributes"]]
|
|
||||||
sub_ref_types = collect_reference_types(sub_type_xmls)
|
|
||||||
for srt in sub_ref_types:
|
|
||||||
if srt["TypeName"] not in CHILD_TYPE_DIR_MAP:
|
|
||||||
continue
|
|
||||||
if test_object_borrowed(srt["TypeName"], srt["ObjName"]):
|
|
||||||
continue
|
|
||||||
s_src_file = os.path.join(cfg_dir, CHILD_TYPE_DIR_MAP[srt["TypeName"]], f"{srt['ObjName']}.xml")
|
|
||||||
if not os.path.isfile(s_src_file):
|
|
||||||
continue
|
|
||||||
s_src = read_source_object(srt["TypeName"], srt["ObjName"])
|
|
||||||
s_borrowed_xml = build_borrowed_object_xml(srt["TypeName"], srt["ObjName"], s_src["Uuid"], s_src["Properties"])
|
|
||||||
s_target_dir = os.path.join(ext_dir, CHILD_TYPE_DIR_MAP[srt["TypeName"]])
|
|
||||||
os.makedirs(s_target_dir, exist_ok=True)
|
|
||||||
s_target_file = os.path.join(s_target_dir, f"{srt['ObjName']}.xml")
|
|
||||||
save_text_bom(s_target_file, s_borrowed_xml)
|
|
||||||
add_to_child_objects(srt["TypeName"], srt["ObjName"])
|
|
||||||
borrowed_files.append(s_target_file)
|
|
||||||
info(f" Auto-borrowed (deep): {srt['TypeName']}.{srt['ObjName']}")
|
|
||||||
|
|
||||||
def borrow_form(type_name, obj_name, form_name, borrow_main_attr=False):
|
def borrow_form(type_name, obj_name, form_name, borrow_main_attr=False):
|
||||||
dir_name = CHILD_TYPE_DIR_MAP[type_name]
|
dir_name = CHILD_TYPE_DIR_MAP[type_name]
|
||||||
|
|
||||||
@@ -1180,25 +1080,11 @@ def main():
|
|||||||
with open(src_form_xml_path, "r", encoding="utf-8-sig") as fh:
|
with open(src_form_xml_path, "r", encoding="utf-8-sig") as fh:
|
||||||
src_form_content = fh.read()
|
src_form_content = fh.read()
|
||||||
|
|
||||||
# 3. Generate form metadata XML.
|
# 3. Generate form metadata XML
|
||||||
# If the wrapper was already borrowed, reuse its uuid so re-borrow is idempotent
|
new_form_uuid = new_guid()
|
||||||
# (regenerating it would churn the form's identity on every rerun).
|
|
||||||
existing_wrapper = os.path.join(ext_dir, dir_name, obj_name, "Forms", f"{form_name}.xml")
|
|
||||||
new_form_uuid = ""
|
|
||||||
if os.path.isfile(existing_wrapper):
|
|
||||||
try:
|
|
||||||
existing_root = etree.parse(existing_wrapper).getroot()
|
|
||||||
for c in existing_root:
|
|
||||||
if isinstance(c.tag, str) and localname(c) == "Form":
|
|
||||||
new_form_uuid = c.get("uuid", "") or ""
|
|
||||||
break
|
|
||||||
except Exception:
|
|
||||||
new_form_uuid = ""
|
|
||||||
if not new_form_uuid:
|
|
||||||
new_form_uuid = new_guid()
|
|
||||||
form_meta_lines = [
|
form_meta_lines = [
|
||||||
'<?xml version="1.0" encoding="UTF-8"?>',
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
||||||
f'<MetaDataObject {XMLNS_DECL} version="{format_version}">',
|
f'<MetaDataObject {XMLNS_DECL} version="2.17">',
|
||||||
f'\t<Form uuid="{new_form_uuid}">',
|
f'\t<Form uuid="{new_form_uuid}">',
|
||||||
'\t\t<InternalInfo/>',
|
'\t\t<InternalInfo/>',
|
||||||
'\t\t<Properties>',
|
'\t\t<Properties>',
|
||||||
@@ -1225,10 +1111,7 @@ def main():
|
|||||||
src_form_tree = etree.parse(src_form_xml_path, src_form_parser)
|
src_form_tree = etree.parse(src_form_xml_path, src_form_parser)
|
||||||
src_form_el = src_form_tree.getroot()
|
src_form_el = src_form_tree.getroot()
|
||||||
|
|
||||||
# Borrowed form uses the extension's format version (not the source form's) — keeps the
|
form_version = src_form_el.get("version", "2.17")
|
||||||
# extension uniform; otherwise the platform rejects the import on a version mismatch
|
|
||||||
# (e.g. a 2.13 form inside a 2.17 extension). The platform upgrades the form to the root version.
|
|
||||||
form_version = format_version
|
|
||||||
|
|
||||||
src_auto_cmd = None
|
src_auto_cmd = None
|
||||||
form_props = []
|
form_props = []
|
||||||
@@ -1246,21 +1129,25 @@ def main():
|
|||||||
continue
|
continue
|
||||||
if not reached_visual:
|
if not reached_visual:
|
||||||
# Form-level properties before AutoCommandBar (WindowOpeningMode, AutoFillCheck, etc.)
|
# Form-level properties before AutoCommandBar (WindowOpeningMode, AutoFillCheck, etc.)
|
||||||
form_props.append(decode_numeric_entities(etree.tostring(fc, encoding="unicode")))
|
form_props.append(etree.tostring(fc, encoding="unicode"))
|
||||||
|
|
||||||
ns_strip_pattern = re.compile(r'\s+xmlns(?::\w+)?="[^"]*"')
|
ns_strip_pattern = re.compile(r'\s+xmlns(?::\w+)?="[^"]*"')
|
||||||
|
|
||||||
# AutoCommandBar: keep ChildItems (buttons with CommandName->0), Autofill->false
|
# AutoCommandBar: keep ChildItems (buttons with CommandName->0), Autofill->false
|
||||||
auto_cmd_xml = ""
|
auto_cmd_xml = ""
|
||||||
if src_auto_cmd is not None:
|
if src_auto_cmd is not None:
|
||||||
auto_cmd_xml = decode_numeric_entities(etree.tostring(src_auto_cmd, encoding="unicode"))
|
auto_cmd_xml = etree.tostring(src_auto_cmd, encoding="unicode")
|
||||||
auto_cmd_xml = ns_strip_pattern.sub("", auto_cmd_xml)
|
auto_cmd_xml = ns_strip_pattern.sub("", auto_cmd_xml)
|
||||||
auto_cmd_xml = re.sub(r'<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>', auto_cmd_xml)
|
auto_cmd_xml = re.sub(r'<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>', auto_cmd_xml)
|
||||||
auto_cmd_xml = auto_cmd_xml.replace('<Autofill>true</Autofill>', '<Autofill>false</Autofill>')
|
auto_cmd_xml = auto_cmd_xml.replace('<Autofill>true</Autofill>', '<Autofill>false</Autofill>')
|
||||||
# Strip ExcludedCommand (references to standard commands invalid in extension)
|
# Strip ExcludedCommand (references to standard commands invalid in extension)
|
||||||
auto_cmd_xml = re.sub(r'\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '', auto_cmd_xml)
|
auto_cmd_xml = re.sub(r'\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '', auto_cmd_xml)
|
||||||
# Strip data-binding tags whose root attribute isn't borrowed
|
# Strip DataPath in AutoCommandBar buttons
|
||||||
auto_cmd_xml = strip_form_bindings(auto_cmd_xml, borrow_main_attr)
|
if borrow_main_attr:
|
||||||
|
# Keep only Объект.* DataPaths
|
||||||
|
auto_cmd_xml = re.sub(r'\s*<DataPath>(?!\u041e\u0431\u044a\u0435\u043a\u0442\.)[^<]*</DataPath>', '', auto_cmd_xml)
|
||||||
|
else:
|
||||||
|
auto_cmd_xml = re.sub(r'\s*<DataPath>[^<]*</DataPath>', '', auto_cmd_xml)
|
||||||
|
|
||||||
# ChildItems: copy full tree, clean up base-config references
|
# ChildItems: copy full tree, clean up base-config references
|
||||||
child_items_xml = ""
|
child_items_xml = ""
|
||||||
@@ -1271,12 +1158,20 @@ def main():
|
|||||||
break
|
break
|
||||||
|
|
||||||
if src_child_items is not None:
|
if src_child_items is not None:
|
||||||
child_items_xml = decode_numeric_entities(etree.tostring(src_child_items, encoding="unicode"))
|
child_items_xml = etree.tostring(src_child_items, encoding="unicode")
|
||||||
child_items_xml = ns_strip_pattern.sub("", child_items_xml)
|
child_items_xml = ns_strip_pattern.sub("", child_items_xml)
|
||||||
# Replace all CommandName values with 0
|
# Replace all CommandName values with 0
|
||||||
child_items_xml = re.sub(r'<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>', child_items_xml)
|
child_items_xml = re.sub(r'<CommandName>[^<]*</CommandName>', '<CommandName>0</CommandName>', child_items_xml)
|
||||||
# Strip data-binding tags whose root attribute isn't borrowed
|
# Strip DataPath / TitleDataPath / RowPictureDataPath
|
||||||
child_items_xml = strip_form_bindings(child_items_xml, borrow_main_attr)
|
if borrow_main_attr:
|
||||||
|
# Keep only Объект.* DataPaths — strip form-attribute DataPaths (not borrowed)
|
||||||
|
child_items_xml = re.sub(r'\s*<DataPath>(?!\u041e\u0431\u044a\u0435\u043a\u0442\.)[^<]*</DataPath>', '', child_items_xml)
|
||||||
|
child_items_xml = re.sub(r'\s*<TitleDataPath>(?!\u041e\u0431\u044a\u0435\u043a\u0442\.)[^<]*</TitleDataPath>', '', child_items_xml)
|
||||||
|
child_items_xml = re.sub(r'\s*<RowPictureDataPath>[^<]*</RowPictureDataPath>', '', child_items_xml)
|
||||||
|
else:
|
||||||
|
child_items_xml = re.sub(r'\s*<DataPath>[^<]*</DataPath>', '', child_items_xml)
|
||||||
|
child_items_xml = re.sub(r'\s*<TitleDataPath>[^<]*</TitleDataPath>', '', child_items_xml)
|
||||||
|
child_items_xml = re.sub(r'\s*<RowPictureDataPath>[^<]*</RowPictureDataPath>', '', child_items_xml)
|
||||||
# Strip ExcludedCommand in nested AutoCommandBars (references to standard commands invalid in extension)
|
# Strip ExcludedCommand in nested AutoCommandBars (references to standard commands invalid in extension)
|
||||||
child_items_xml = re.sub(r'\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '', child_items_xml)
|
child_items_xml = re.sub(r'\s*<ExcludedCommand>[^<]*</ExcludedCommand>', '', child_items_xml)
|
||||||
# Strip TypeLink blocks with human-readable DataPath (Items.XXX)
|
# Strip TypeLink blocks with human-readable DataPath (Items.XXX)
|
||||||
@@ -1513,16 +1408,12 @@ def main():
|
|||||||
save_text_bom(form_xml_file, "".join(parts))
|
save_text_bom(form_xml_file, "".join(parts))
|
||||||
info(f" Created: {form_xml_file}")
|
info(f" Created: {form_xml_file}")
|
||||||
|
|
||||||
# 6. Create empty Module.bsl — but NEVER overwrite an existing one (re-borrow must
|
# 6. Create empty Module.bsl
|
||||||
# not clobber user code added to the form module).
|
|
||||||
module_dir = os.path.join(form_xml_dir, "Form")
|
module_dir = os.path.join(form_xml_dir, "Form")
|
||||||
os.makedirs(module_dir, exist_ok=True)
|
os.makedirs(module_dir, exist_ok=True)
|
||||||
module_bsl_file = os.path.join(module_dir, "Module.bsl")
|
module_bsl_file = os.path.join(module_dir, "Module.bsl")
|
||||||
if os.path.isfile(module_bsl_file):
|
save_text_bom(module_bsl_file, "")
|
||||||
info(" Preserved existing Module.bsl")
|
info(f" Created: {module_bsl_file}")
|
||||||
else:
|
|
||||||
save_text_bom(module_bsl_file, "")
|
|
||||||
info(f" Created: {module_bsl_file}")
|
|
||||||
|
|
||||||
# 7. Register form in parent object ChildObjects
|
# 7. Register form in parent object ChildObjects
|
||||||
register_form_in_object(type_name, obj_name, form_name)
|
register_form_in_object(type_name, obj_name, form_name)
|
||||||
@@ -23,7 +23,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cfe-diff/scripts/cfe-diff.py" -ExtensionPath src -ConfigPath C:\cfsrc\erp -Mode A
|
powershell.exe -NoProfile -File .claude/skills/cfe-diff/scripts/cfe-diff.ps1 -ExtensionPath src -ConfigPath C:\cfsrc\erp -Mode A
|
||||||
```
|
```
|
||||||
|
|
||||||
## Mode A — обзор расширения
|
## Mode A — обзор расширения
|
||||||
@@ -32,6 +32,19 @@ python ".opencode/skills/cfe-diff/scripts/cfe-diff.py" -ExtensionPath src -Confi
|
|||||||
- `[BORROWED]` — заимствованный: перехватчики (`&Перед`, `&После`, `&ИзменениеИКонтроль`, `&Вместо`), собственные реквизиты/ТЧ/формы
|
- `[BORROWED]` — заимствованный: перехватчики (`&Перед`, `&После`, `&ИзменениеИКонтроль`, `&Вместо`), собственные реквизиты/ТЧ/формы
|
||||||
- `[OWN]` — собственный: количество реквизитов, ТЧ, форм
|
- `[OWN]` — собственный: количество реквизитов, ТЧ, форм
|
||||||
|
|
||||||
|
Пример вывода:
|
||||||
|
```
|
||||||
|
[BORROWED] Catalog.Валюты
|
||||||
|
&ИзменениеИКонтроль("РеквизитыРедактируемыеВГрупповойОбработке") — line 4 in ...
|
||||||
|
&Перед("ЗагрузитьКурсыВалют") — line 13 in ...
|
||||||
|
ChildObjects: 1 own attrs, 1 own TS, 3 own forms
|
||||||
|
Form.ФормаЭлемента (borrowed):
|
||||||
|
Event:OnCreateAtServer [After] -> Расш1_ПриСозданииПосле
|
||||||
|
Command:Подбор [Before] -> Расш1_ПодборПеред
|
||||||
|
Form.Расш1_МояФорма (own)
|
||||||
|
[OWN] Catalog.Расш5_Справочник1
|
||||||
|
```
|
||||||
|
|
||||||
Для каждой формы заимствованного объекта показывается:
|
Для каждой формы заимствованного объекта показывается:
|
||||||
- `(borrowed)` / `(own)` — заимствованная или собственная форма
|
- `(borrowed)` / `(own)` — заимствованная или собственная форма
|
||||||
- callType-события формы и элементов
|
- callType-события формы и элементов
|
||||||
@@ -44,7 +44,18 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cfe-init/scripts/cfe-init.py" -Name "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/cfe-init/scripts/cfe-init.ps1 -Name "МоёРасширение"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<OutputDir>/
|
||||||
|
├── Configuration.xml # Свойства расширения
|
||||||
|
├── Languages/
|
||||||
|
│ └── Русский.xml # Язык (заимствованный)
|
||||||
|
└── Roles/ # Если не -NoRole
|
||||||
|
└── <Prefix>ОсновнаяРоль.xml
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+6
-24
@@ -1,4 +1,4 @@
|
|||||||
# cfe-init v1.2 — Create 1C configuration extension scaffold (CFE)
|
# cfe-init v1.0 — Create 1C configuration extension scaffold (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -35,10 +35,6 @@ if (Test-Path $cfgFile) {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# MDClasses format version — inherited from the base config so the extension stays uniform
|
|
||||||
# with it (a 2.13 base must yield a 2.13 extension, else platform import rejects the mismatch).
|
|
||||||
$formatVersion = "2.17"
|
|
||||||
|
|
||||||
# --- Resolve ConfigPath ---
|
# --- Resolve ConfigPath ---
|
||||||
$baseLangUuid = "00000000-0000-0000-0000-000000000000"
|
$baseLangUuid = "00000000-0000-0000-0000-000000000000"
|
||||||
if ($ConfigPath) {
|
if ($ConfigPath) {
|
||||||
@@ -73,17 +69,12 @@ if ($ConfigPath) {
|
|||||||
Write-Host "[WARN] Base config language not found: $baseLangFile"
|
Write-Host "[WARN] Base config language not found: $baseLangFile"
|
||||||
}
|
}
|
||||||
|
|
||||||
# 3b. Read CompatibilityMode and InterfaceCompatibilityMode from base config
|
# 3b. Read CompatibilityMode from base config
|
||||||
$baseCfgDoc = New-Object System.Xml.XmlDocument
|
$baseCfgDoc = New-Object System.Xml.XmlDocument
|
||||||
$baseCfgDoc.PreserveWhitespace = $false
|
$baseCfgDoc.PreserveWhitespace = $false
|
||||||
$baseCfgDoc.Load((Resolve-Path $ConfigPath).Path)
|
$baseCfgDoc.Load((Resolve-Path $ConfigPath).Path)
|
||||||
$baseCfgNs = New-Object System.Xml.XmlNamespaceManager($baseCfgDoc.NameTable)
|
$baseCfgNs = New-Object System.Xml.XmlNamespaceManager($baseCfgDoc.NameTable)
|
||||||
$baseCfgNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
$baseCfgNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||||
$fmtVer = $baseCfgDoc.DocumentElement.GetAttribute("version")
|
|
||||||
if ($fmtVer) {
|
|
||||||
$formatVersion = $fmtVer
|
|
||||||
Write-Host "[INFO] Base config format version: $formatVersion"
|
|
||||||
}
|
|
||||||
$compatNode = $baseCfgDoc.SelectSingleNode("//md:Configuration/md:Properties/md:CompatibilityMode", $baseCfgNs)
|
$compatNode = $baseCfgDoc.SelectSingleNode("//md:Configuration/md:Properties/md:CompatibilityMode", $baseCfgNs)
|
||||||
if ($compatNode -and $compatNode.InnerText) {
|
if ($compatNode -and $compatNode.InnerText) {
|
||||||
$CompatibilityMode = $compatNode.InnerText.Trim()
|
$CompatibilityMode = $compatNode.InnerText.Trim()
|
||||||
@@ -91,16 +82,7 @@ if ($ConfigPath) {
|
|||||||
} else {
|
} else {
|
||||||
Write-Host "[WARN] CompatibilityMode not found in base config, using default: $CompatibilityMode"
|
Write-Host "[WARN] CompatibilityMode not found in base config, using default: $CompatibilityMode"
|
||||||
}
|
}
|
||||||
$ifcNode = $baseCfgDoc.SelectSingleNode("//md:Configuration/md:Properties/md:InterfaceCompatibilityMode", $baseCfgNs)
|
|
||||||
if ($ifcNode -and $ifcNode.InnerText) {
|
|
||||||
$InterfaceCompatibilityMode = $ifcNode.InnerText.Trim()
|
|
||||||
Write-Host "[INFO] Base config InterfaceCompatibilityMode: $InterfaceCompatibilityMode"
|
|
||||||
} else {
|
|
||||||
$InterfaceCompatibilityMode = "TaxiEnableVersion8_2"
|
|
||||||
Write-Host "[WARN] InterfaceCompatibilityMode not found in base config, using default: $InterfaceCompatibilityMode"
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
$InterfaceCompatibilityMode = "TaxiEnableVersion8_2"
|
|
||||||
Write-Host "[WARN] Language ExtendedConfigurationObject set to zeros. Use -ConfigPath to auto-resolve from base config, or fix manually before loading."
|
Write-Host "[WARN] Language ExtendedConfigurationObject set to zeros. Use -ConfigPath to auto-resolve from base config, or fix manually before loading."
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,7 +129,7 @@ $childObjectsXml += "`r`n`t`t"
|
|||||||
# --- Configuration.xml ---
|
# --- Configuration.xml ---
|
||||||
$cfgXml = @"
|
$cfgXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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" 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">
|
||||||
<Configuration uuid="$uuidCfg">
|
<Configuration uuid="$uuidCfg">
|
||||||
<InternalInfo>
|
<InternalInfo>
|
||||||
<xr:ContainedObject>
|
<xr:ContainedObject>
|
||||||
@@ -202,7 +184,7 @@ $cfgXml = @"
|
|||||||
<Copyright/>
|
<Copyright/>
|
||||||
<VendorInformationAddress/>
|
<VendorInformationAddress/>
|
||||||
<ConfigurationInformationAddress/>
|
<ConfigurationInformationAddress/>
|
||||||
<InterfaceCompatibilityMode>$InterfaceCompatibilityMode</InterfaceCompatibilityMode>
|
<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
||||||
</Properties>
|
</Properties>
|
||||||
<ChildObjects>$childObjectsXml</ChildObjects>
|
<ChildObjects>$childObjectsXml</ChildObjects>
|
||||||
</Configuration>
|
</Configuration>
|
||||||
@@ -212,7 +194,7 @@ $cfgXml = @"
|
|||||||
# --- Languages/Русский.xml (adopted format) ---
|
# --- Languages/Русский.xml (adopted format) ---
|
||||||
$langXml = @"
|
$langXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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" 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">
|
||||||
<Language uuid="$uuidLang">
|
<Language uuid="$uuidLang">
|
||||||
<InternalInfo/>
|
<InternalInfo/>
|
||||||
<Properties>
|
<Properties>
|
||||||
@@ -229,7 +211,7 @@ $langXml = @"
|
|||||||
# --- Role XML ---
|
# --- Role XML ---
|
||||||
$roleXml = @"
|
$roleXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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" 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">
|
||||||
<Role uuid="$uuidRole">
|
<Role uuid="$uuidRole">
|
||||||
<Properties>
|
<Properties>
|
||||||
<Name>$([System.Security.SecurityElement]::Escape($roleName))</Name>
|
<Name>$([System.Security.SecurityElement]::Escape($roleName))</Name>
|
||||||
+6
-23
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cfe-init v1.2 — Create 1C configuration extension scaffold (CFE)
|
# cfe-init v1.0 — Create 1C configuration extension scaffold (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Generates minimal XML source files for a 1C configuration extension."""
|
"""Generates minimal XML source files for a 1C configuration extension."""
|
||||||
import sys, os, argparse, uuid
|
import sys, os, argparse, uuid
|
||||||
@@ -50,10 +50,6 @@ def main():
|
|||||||
print(f"Configuration.xml already exists: {cfg_file}", file=sys.stderr)
|
print(f"Configuration.xml already exists: {cfg_file}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
# MDClasses format version — inherited from the base config so the extension stays uniform
|
|
||||||
# with it (a 2.13 base must yield a 2.13 extension, else platform import rejects the mismatch).
|
|
||||||
format_version = "2.17"
|
|
||||||
|
|
||||||
# --- Resolve ConfigPath ---
|
# --- Resolve ConfigPath ---
|
||||||
base_lang_uuid = "00000000-0000-0000-0000-000000000000"
|
base_lang_uuid = "00000000-0000-0000-0000-000000000000"
|
||||||
if args.ConfigPath:
|
if args.ConfigPath:
|
||||||
@@ -88,14 +84,10 @@ def main():
|
|||||||
else:
|
else:
|
||||||
print(f"[WARN] Base config language not found: {base_lang_file}")
|
print(f"[WARN] Base config language not found: {base_lang_file}")
|
||||||
|
|
||||||
# Read CompatibilityMode and InterfaceCompatibilityMode from base config
|
# Read CompatibilityMode from base config
|
||||||
try:
|
try:
|
||||||
base_cfg_tree = ET.parse(os.path.abspath(config_path))
|
base_cfg_tree = ET.parse(os.path.abspath(config_path))
|
||||||
base_cfg_root = base_cfg_tree.getroot()
|
base_cfg_root = base_cfg_tree.getroot()
|
||||||
fmt_ver = base_cfg_root.get("version")
|
|
||||||
if fmt_ver:
|
|
||||||
format_version = fmt_ver
|
|
||||||
print(f"[INFO] Base config format version: {format_version}")
|
|
||||||
ns = {'md': 'http://v8.1c.ru/8.3/MDClasses'}
|
ns = {'md': 'http://v8.1c.ru/8.3/MDClasses'}
|
||||||
compat_node = base_cfg_root.find('.//md:Configuration/md:Properties/md:CompatibilityMode', ns)
|
compat_node = base_cfg_root.find('.//md:Configuration/md:Properties/md:CompatibilityMode', ns)
|
||||||
if compat_node is not None and compat_node.text:
|
if compat_node is not None and compat_node.text:
|
||||||
@@ -103,18 +95,9 @@ def main():
|
|||||||
print(f"[INFO] Base config CompatibilityMode: {compat}")
|
print(f"[INFO] Base config CompatibilityMode: {compat}")
|
||||||
else:
|
else:
|
||||||
print(f"[WARN] CompatibilityMode not found in base config, using default: {compat}")
|
print(f"[WARN] CompatibilityMode not found in base config, using default: {compat}")
|
||||||
ifc_node = base_cfg_root.find('.//md:Configuration/md:Properties/md:InterfaceCompatibilityMode', ns)
|
|
||||||
if ifc_node is not None and ifc_node.text:
|
|
||||||
ifc_mode = ifc_node.text.strip()
|
|
||||||
print(f"[INFO] Base config InterfaceCompatibilityMode: {ifc_mode}")
|
|
||||||
else:
|
|
||||||
ifc_mode = "TaxiEnableVersion8_2"
|
|
||||||
print(f"[WARN] InterfaceCompatibilityMode not found in base config, using default: {ifc_mode}")
|
|
||||||
except Exception:
|
except Exception:
|
||||||
print(f"[WARN] Could not parse base config, using default CompatibilityMode: {compat}")
|
print(f"[WARN] Could not parse base config, using default CompatibilityMode: {compat}")
|
||||||
ifc_mode = "TaxiEnableVersion8_2"
|
|
||||||
else:
|
else:
|
||||||
ifc_mode = "TaxiEnableVersion8_2"
|
|
||||||
print("[WARN] Language ExtendedConfigurationObject set to zeros. Use -ConfigPath to auto-resolve from base config, or fix manually before loading.")
|
print("[WARN] Language ExtendedConfigurationObject set to zeros. Use -ConfigPath to auto-resolve from base config, or fix manually before loading.")
|
||||||
|
|
||||||
# --- Generate UUIDs ---
|
# --- Generate UUIDs ---
|
||||||
@@ -163,7 +146,7 @@ def main():
|
|||||||
\t\t\t</xr:ContainedObject>\n"""
|
\t\t\t</xr:ContainedObject>\n"""
|
||||||
|
|
||||||
cfg_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
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="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<Configuration uuid="{uuid_cfg}">
|
\t<Configuration uuid="{uuid_cfg}">
|
||||||
\t\t<InternalInfo>
|
\t\t<InternalInfo>
|
||||||
{contained_objects}\t\t</InternalInfo>
|
{contained_objects}\t\t</InternalInfo>
|
||||||
@@ -190,7 +173,7 @@ def main():
|
|||||||
\t\t\t<Copyright/>
|
\t\t\t<Copyright/>
|
||||||
\t\t\t<VendorInformationAddress/>
|
\t\t\t<VendorInformationAddress/>
|
||||||
\t\t\t<ConfigurationInformationAddress/>
|
\t\t\t<ConfigurationInformationAddress/>
|
||||||
\t\t\t<InterfaceCompatibilityMode>{ifc_mode}</InterfaceCompatibilityMode>
|
\t\t\t<InterfaceCompatibilityMode>TaxiEnableVersion8_2</InterfaceCompatibilityMode>
|
||||||
\t\t</Properties>
|
\t\t</Properties>
|
||||||
\t\t<ChildObjects>{child_objects_xml}</ChildObjects>
|
\t\t<ChildObjects>{child_objects_xml}</ChildObjects>
|
||||||
\t</Configuration>
|
\t</Configuration>
|
||||||
@@ -198,7 +181,7 @@ def main():
|
|||||||
|
|
||||||
# --- Languages/Русский.xml (adopted format) ---
|
# --- Languages/Русский.xml (adopted format) ---
|
||||||
lang_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
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="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<Language uuid="{uuid_lang}">
|
\t<Language uuid="{uuid_lang}">
|
||||||
\t\t<InternalInfo/>
|
\t\t<InternalInfo/>
|
||||||
\t\t<Properties>
|
\t\t<Properties>
|
||||||
@@ -213,7 +196,7 @@ def main():
|
|||||||
|
|
||||||
# --- Role XML ---
|
# --- Role XML ---
|
||||||
role_xml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
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="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<Role uuid="{uuid_role}">
|
\t<Role uuid="{uuid_role}">
|
||||||
\t\t<Properties>
|
\t\t<Properties>
|
||||||
\t\t\t<Name>{esc_xml(role_name)}</Name>
|
\t\t\t<Name>{esc_xml(role_name)}</Name>
|
||||||
+1
-1
@@ -51,7 +51,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/cfe-patch-method/scripts/cfe-patch-method.py" -ExtensionPath src -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
powershell.exe -NoProfile -File .claude/skills/cfe-patch-method/scripts/cfe-patch-method.ps1 -ExtensionPath src -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+1
-9
@@ -1,4 +1,4 @@
|
|||||||
# cfe-patch-method v1.1 — Generate method interceptor for 1C extension (CFE)
|
# cfe-patch-method v1.0 — Generate method interceptor for 1C extension (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -66,14 +66,6 @@ $typeDirMap = @{
|
|||||||
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
|
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
|
||||||
"InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
|
"InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
|
||||||
"AccountingRegister"="AccountingRegisters"; "CalculationRegister"="CalculationRegisters"
|
"AccountingRegister"="AccountingRegisters"; "CalculationRegister"="CalculationRegisters"
|
||||||
"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"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$parts = $ModulePath.Split(".")
|
$parts = $ModulePath.Split(".")
|
||||||
+1
-17
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cfe-patch-method v1.1 — Generate method interceptor for 1C extension (CFE)
|
# cfe-patch-method v1.0 — Generate method interceptor for 1C extension (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -84,22 +84,6 @@ def main():
|
|||||||
"AccumulationRegister": "AccumulationRegisters",
|
"AccumulationRegister": "AccumulationRegisters",
|
||||||
"AccountingRegister": "AccountingRegisters",
|
"AccountingRegister": "AccountingRegisters",
|
||||||
"CalculationRegister": "CalculationRegisters",
|
"CalculationRegister": "CalculationRegisters",
|
||||||
"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",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
parts = module_path.split(".")
|
parts = module_path.split(".")
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
---
|
||||||
|
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 | нет | — | Показывать [OK] для каждой проверки |
|
||||||
|
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||||
|
| OutFile | нет | — | Записать результат в файл |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/cfe-validate/scripts/cfe-validate.ps1 -ExtensionPath "src"
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/cfe-validate/scripts/cfe-validate.ps1 -ExtensionPath "src/Configuration.xml"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Проверки (13 шагов)
|
||||||
|
|
||||||
|
| # | Проверка | Уровень |
|
||||||
|
|---|----------|---------|
|
||||||
|
| 1 | XML well-formedness, MetaDataObject/Configuration, version | ERROR |
|
||||||
|
| 2 | InternalInfo: 7 ContainedObject, валидные ClassId | ERROR |
|
||||||
|
| 3 | Extension properties: ObjectBelonging=Adopted, Name, Purpose, NamePrefix, KeepMapping | ERROR |
|
||||||
|
| 4 | Enum-значения: ConfigurationExtensionCompatibilityMode, DefaultRunMode, ScriptVariant, InterfaceCompatibilityMode | ERROR |
|
||||||
|
| 5 | ChildObjects: валидные типы (44), нет дубликатов, каноничный порядок | ERROR/WARN |
|
||||||
|
| 6 | DefaultLanguage ссылается на Language в ChildObjects | ERROR |
|
||||||
|
| 7 | Файлы языков существуют | WARN |
|
||||||
|
| 8 | Каталоги объектов существуют | WARN |
|
||||||
|
| 9 | Заимствованные объекты: ObjectBelonging=Adopted, ExtendedConfigurationObject UUID | ERROR/WARN |
|
||||||
|
| 10 | Sub-items: Attribute, TabularSection (InternalInfo + вложенные), EnumValue, Form-ссылки | ERROR |
|
||||||
|
| 11 | Заимствованные формы: метаданные, Form.xml, Module.bsl, BaseForm version | ERROR/WARN |
|
||||||
|
| 12 | Зависимости форм: CommonPicture, StyleItem (с whitelist платформенных), Enum DesignTimeRef | WARN |
|
||||||
|
| 13 | TypeLink: human-readable Items.* DataPath (должны быть удалены) | WARN |
|
||||||
|
|
||||||
|
Exit code: 0 = OK, 1 = есть ошибки. По умолчанию краткий вывод. `-Detailed` для поштучной детализации.
|
||||||
+5
-6
@@ -1,8 +1,7 @@
|
|||||||
# cfe-validate v1.4 — Validate 1C configuration extension structure (CFE)
|
# cfe-validate v1.3 — Validate 1C configuration extension structure (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$ExtensionPath,
|
[string]$ExtensionPath,
|
||||||
|
|
||||||
[switch]$Detailed,
|
[switch]$Detailed,
|
||||||
@@ -146,10 +145,10 @@ $childTypeDirMap = @{
|
|||||||
|
|
||||||
# Valid enum values for extension properties
|
# Valid enum values for extension properties
|
||||||
$validEnumValues = @{
|
$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")
|
"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")
|
||||||
"DefaultRunMode" = @("ManagedApplication","OrdinaryApplication","Auto")
|
"DefaultRunMode" = @("ManagedApplication","OrdinaryApplication","Auto")
|
||||||
"ScriptVariant" = @("Russian","English")
|
"ScriptVariant" = @("Russian","English")
|
||||||
"InterfaceCompatibilityMode" = @("Version8_2","Version8_2EnableTaxi","Taxi","TaxiEnableVersion8_2","TaxiEnableVersion8_5","Version8_5EnableTaxi","Version8_5")
|
"InterfaceCompatibilityMode" = @("Taxi","TaxiEnableVersion8_2","Version8_2")
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 1. Parse XML ---
|
# --- 1. Parse XML ---
|
||||||
@@ -197,8 +196,8 @@ if ($root.NamespaceURI -ne $expectedNs) {
|
|||||||
$version = $root.GetAttribute("version")
|
$version = $root.GetAttribute("version")
|
||||||
if (-not $version) {
|
if (-not $version) {
|
||||||
Report-Warn "1. Missing version attribute on MetaDataObject"
|
Report-Warn "1. Missing version attribute on MetaDataObject"
|
||||||
} elseif ($version -ne "2.17" -and $version -ne "2.20" -and $version -ne "2.21") {
|
} elseif ($version -ne "2.17" -and $version -ne "2.20") {
|
||||||
Report-Warn "1. Unusual version '$version' (expected 2.17, 2.20 or 2.21)"
|
Report-Warn "1. Unusual version '$version' (expected 2.17 or 2.20)"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Must have Configuration child
|
# Must have Configuration child
|
||||||
+6
-9
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cfe-validate v1.4 — Validate 1C configuration extension XML structure (CFE)
|
# cfe-validate v1.3 — Validate 1C configuration extension XML structure (CFE)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Validates extension Configuration.xml: root, InternalInfo, extension properties, ChildObjects, borrowed objects."""
|
"""Validates extension Configuration.xml: root, InternalInfo, extension properties, ChildObjects, borrowed objects."""
|
||||||
import sys, os, argparse, re
|
import sys, os, argparse, re
|
||||||
@@ -82,14 +82,11 @@ VALID_ENUM_VALUES = {
|
|||||||
'Version8_3_11', 'Version8_3_12', 'Version8_3_13', 'Version8_3_14', 'Version8_3_15',
|
'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_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_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',
|
'Version8_3_26', 'Version8_3_27', 'Version8_3_28',
|
||||||
],
|
],
|
||||||
'DefaultRunMode': ['ManagedApplication', 'OrdinaryApplication', 'Auto'],
|
'DefaultRunMode': ['ManagedApplication', 'OrdinaryApplication', 'Auto'],
|
||||||
'ScriptVariant': ['Russian', 'English'],
|
'ScriptVariant': ['Russian', 'English'],
|
||||||
'InterfaceCompatibilityMode': [
|
'InterfaceCompatibilityMode': ['Taxi', 'TaxiEnableVersion8_2', 'Version8_2'],
|
||||||
'Version8_2', 'Version8_2EnableTaxi', 'Taxi', 'TaxiEnableVersion8_2',
|
|
||||||
'TaxiEnableVersion8_5', 'Version8_5EnableTaxi', 'Version8_5',
|
|
||||||
],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPECTED_NS = 'http://v8.1c.ru/8.3/MDClasses'
|
EXPECTED_NS = 'http://v8.1c.ru/8.3/MDClasses'
|
||||||
@@ -150,7 +147,7 @@ def main():
|
|||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description='Validate 1C configuration extension XML structure (CFE)', allow_abbrev=False
|
description='Validate 1C configuration extension XML structure (CFE)', allow_abbrev=False
|
||||||
)
|
)
|
||||||
parser.add_argument('-ExtensionPath', '-Path', dest='ExtensionPath', required=True)
|
parser.add_argument('-ExtensionPath', dest='ExtensionPath', required=True)
|
||||||
parser.add_argument('-Detailed', action='store_true')
|
parser.add_argument('-Detailed', action='store_true')
|
||||||
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
parser.add_argument('-MaxErrors', dest='MaxErrors', type=int, default=30)
|
||||||
parser.add_argument('-OutFile', dest='OutFile', default='')
|
parser.add_argument('-OutFile', dest='OutFile', default='')
|
||||||
@@ -216,8 +213,8 @@ def main():
|
|||||||
version = root.get('version', '')
|
version = root.get('version', '')
|
||||||
if not version:
|
if not version:
|
||||||
r.warn('1. Missing version attribute on MetaDataObject')
|
r.warn('1. Missing version attribute on MetaDataObject')
|
||||||
elif version not in ('2.17', '2.20', '2.21'):
|
elif version not in ('2.17', '2.20'):
|
||||||
r.warn(f"1. Unusual version '{version}' (expected 2.17, 2.20 or 2.21)")
|
r.warn(f"1. Unusual version '{version}' (expected 2.17 or 2.20)")
|
||||||
|
|
||||||
# Must have Configuration child
|
# Must have Configuration child
|
||||||
cfg_node = None
|
cfg_node = None
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-create
|
name: db-create
|
||||||
description: Создание информационной базы 1С. Используй когда нужно создать базу, новую ИБ, пустую базу
|
description: Создание информационной базы 1С. Используй когда пользователь просит создать базу, новую ИБ, пустую базу
|
||||||
argument-hint: <path|name>
|
argument-hint: <path|name>
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -25,20 +25,20 @@ allowed-tools:
|
|||||||
## Параметры подключения
|
## Параметры подключения
|
||||||
|
|
||||||
Прочитай `.v8-project.json` из корня проекта для `v8path` (путь к платформе).
|
Прочитай `.v8-project.json` из корня проекта для `v8path` (путь к платформе).
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
После создания базы предложи зарегистрировать через `/db-list add`.
|
После создания базы предложи зарегистрировать через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-create/scripts/db-create.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-create/scripts/db-create.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Путь к файловой базе |
|
| `-InfoBasePath <путь>` | * | Путь к файловой базе |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -48,23 +48,31 @@ python ".opencode/skills/db-create/scripts/db-create.py" <параметры>
|
|||||||
|
|
||||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
## После создания
|
## После создания
|
||||||
|
|
||||||
Предложи зарегистрировать базу в `.v8-project.json` (через `/db-list add`)
|
1. Прочитай лог-файл и покажи результат
|
||||||
|
2. Предложи зарегистрировать базу в `.v8-project.json` (через `/db-list add`)
|
||||||
3. Если указан шаблон `/UseTemplate` — предупреди что конфигурация будет загружена из шаблона
|
3. Если указан шаблон `/UseTemplate` — предупреди что конфигурация будет загружена из шаблона
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Создать файловую базу
|
# Создать файловую базу
|
||||||
python ".opencode/skills/db-create/scripts/db-create.py" -InfoBasePath "C:\Bases\NewDB"
|
powershell.exe -NoProfile -File .claude/skills/db-create/scripts/db-create.ps1 -InfoBasePath "C:\Bases\NewDB"
|
||||||
|
|
||||||
# Создать серверную базу
|
# Создать серверную базу
|
||||||
python ".opencode/skills/db-create/scripts/db-create.py" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test"
|
powershell.exe -NoProfile -File .claude/skills/db-create/scripts/db-create.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test"
|
||||||
|
|
||||||
# Создать из шаблона CF
|
# Создать из шаблона CF
|
||||||
python ".opencode/skills/db-create/scripts/db-create.py" -InfoBasePath "C:\Bases\NewDB" -UseTemplate "C:\Templates\config.cf"
|
powershell.exe -NoProfile -File .claude/skills/db-create/scripts/db-create.ps1 -InfoBasePath "C:\Bases\NewDB" -UseTemplate "C:\Templates\config.cf"
|
||||||
|
|
||||||
# Создать и добавить в список баз
|
# Создать и добавить в список баз
|
||||||
python ".opencode/skills/db-create/scripts/db-create.py" -InfoBasePath "C:\Bases\NewDB" -AddToList -ListName "Новая база"
|
powershell.exe -NoProfile -File .claude/skills/db-create/scripts/db-create.ps1 -InfoBasePath "C:\Bases\NewDB" -AddToList -ListName "Новая база"
|
||||||
```
|
```
|
||||||
+6
-92
@@ -1,6 +1,5 @@
|
|||||||
# db-create v1.6 — Create 1C information base
|
# db-create v1.0 — Create 1C information base
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Создание информационной базы 1С
|
Создание информационной базы 1С
|
||||||
@@ -68,85 +67,25 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
|
|
||||||
# --- Validate connection ---
|
# --- Validate connection ---
|
||||||
if ($engine -eq "ibcmd") {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
if (-not $InfoBasePath) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -162,31 +101,6 @@ $tempDir = Join-Path $env:TEMP "db_create_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only) ---
|
|
||||||
$arguments = @("infobase", "create", "--db-path=$InfoBasePath", "--create-database")
|
|
||||||
if ($UseTemplate) {
|
|
||||||
if ([System.IO.Path]::GetExtension($UseTemplate) -ieq ".dt") {
|
|
||||||
$arguments += "--restore=$UseTemplate"
|
|
||||||
} else {
|
|
||||||
$arguments += "--load=$UseTemplate", "--apply"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Information base created successfully: $InfoBasePath" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error creating information base (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("CREATEINFOBASE")
|
$arguments = @("CREATEINFOBASE")
|
||||||
|
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-create v1.0 — Create 1C information base
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
found = sorted(glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe"))
|
||||||
|
if found:
|
||||||
|
return found[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Create 1C information base",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="")
|
||||||
|
parser.add_argument("-InfoBasePath", default="")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="")
|
||||||
|
parser.add_argument("-InfoBaseRef", default="")
|
||||||
|
parser.add_argument("-UseTemplate", default="")
|
||||||
|
parser.add_argument("-AddToList", action="store_true")
|
||||||
|
parser.add_argument("-ListName", default="")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
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)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_create_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["CREATEINFOBASE"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments.append(f'Srvr="{args.InfoBaseServer}";Ref="{args.InfoBaseRef}"')
|
||||||
|
else:
|
||||||
|
arguments.append(f'File="{args.InfoBasePath}"')
|
||||||
|
|
||||||
|
# --- Template ---
|
||||||
|
if args.UseTemplate:
|
||||||
|
arguments.extend(["/UseTemplate", args.UseTemplate])
|
||||||
|
|
||||||
|
# --- Add to list ---
|
||||||
|
if args.AddToList:
|
||||||
|
if args.ListName:
|
||||||
|
arguments.extend(["/AddToList", args.ListName])
|
||||||
|
else:
|
||||||
|
arguments.append("/AddToList")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "create_log.txt")
|
||||||
|
arguments.extend(["/Out", out_file])
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
print(f"Information base created successfully: {args.InfoBaseServer}/{args.InfoBaseRef}")
|
||||||
|
else:
|
||||||
|
print(f"Information base created successfully: {args.InfoBasePath}")
|
||||||
|
else:
|
||||||
|
print(f"Error creating information base (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.isdir(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-dump-cf
|
name: db-dump-cf
|
||||||
description: Выгрузка конфигурации 1С в CF-файл. Используй когда нужно выгрузить конфигурацию в CF, сохранить конфигурацию, сделать бэкап CF
|
description: Выгрузка конфигурации 1С в CF-файл. Используй когда пользователь просит выгрузить конфигурацию в CF, сохранить конфигурацию, сделать бэкап CF
|
||||||
argument-hint: "[database] [output.cf]"
|
argument-hint: "[database] [output.cf]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -28,21 +28,21 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-dump-cf/scripts/db-dump-cf.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-dump-cf/scripts/db-dump-cf.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -54,15 +54,26 @@ python ".opencode/skills/db-dump-cf/scripts/db-dump-cf.py" <параметры>
|
|||||||
|
|
||||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
|
## После выполнения
|
||||||
|
|
||||||
|
Прочитай лог-файл и покажи результат. Если есть ошибки — покажи содержимое лога.
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Выгрузка конфигурации (файловая база)
|
# Выгрузка конфигурации (файловая база)
|
||||||
python ".opencode/skills/db-dump-cf/scripts/db-dump-cf.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\config.cf"
|
powershell.exe -NoProfile -File .claude/skills/db-dump-cf/scripts/db-dump-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "C:\backup\config.cf"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/db-dump-cf/scripts/db-dump-cf.py" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "config.cf"
|
powershell.exe -NoProfile -File .claude/skills/db-dump-cf/scripts/db-dump-cf.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -OutputFile "config.cf"
|
||||||
|
|
||||||
# Выгрузка расширения
|
# Выгрузка расширения
|
||||||
python ".opencode/skills/db-dump-cf/scripts/db-dump-cf.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "ext.cfe" -Extension "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/db-dump-cf/scripts/db-dump-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -OutputFile "ext.cfe" -Extension "МоёРасширение"
|
||||||
```
|
```
|
||||||
+6
-93
@@ -1,6 +1,5 @@
|
|||||||
# db-dump-cf v1.6 — Dump 1C configuration to CF file
|
# db-dump-cf v1.0 — Dump 1C configuration to CF file
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Выгрузка конфигурации 1С в CF-файл
|
Выгрузка конфигурации 1С в CF-файл
|
||||||
@@ -77,85 +76,25 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
|
|
||||||
# --- Validate connection ---
|
# --- Validate connection ---
|
||||||
if ($engine -eq "ibcmd") {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
if (-not $InfoBasePath) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -171,32 +110,6 @@ $tempDir = Join-Path $env:TEMP "db_dump_cf_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only) ---
|
|
||||||
if ($AllExtensions) {
|
|
||||||
Write-Host "Error: ibcmd config save does not support -AllExtensions (use -Extension)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
$arguments = @("infobase", "config", "save", "--db-path=$InfoBasePath")
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
$arguments += "$OutputFile"
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Configuration dumped successfully to: $OutputFile" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error dumping configuration (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-dump-cf v1.0 — Dump 1C configuration to CF file
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
found = sorted(glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe"))
|
||||||
|
if found:
|
||||||
|
return found[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Dump 1C configuration to CF file",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="")
|
||||||
|
parser.add_argument("-InfoBasePath", default="")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="")
|
||||||
|
parser.add_argument("-InfoBaseRef", default="")
|
||||||
|
parser.add_argument("-UserName", default="")
|
||||||
|
parser.add_argument("-Password", default="")
|
||||||
|
parser.add_argument("-OutputFile", required=True)
|
||||||
|
parser.add_argument("-Extension", default="")
|
||||||
|
parser.add_argument("-AllExtensions", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Ensure output directory exists ---
|
||||||
|
out_dir = os.path.dirname(args.OutputFile)
|
||||||
|
if out_dir and not os.path.isdir(out_dir):
|
||||||
|
os.makedirs(out_dir, exist_ok=True)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_dump_cf_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
|
||||||
|
else:
|
||||||
|
arguments.extend(["/F", args.InfoBasePath])
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments.extend(["/DumpCfg", args.OutputFile])
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if args.Extension:
|
||||||
|
arguments.extend(["-Extension", args.Extension])
|
||||||
|
elif args.AllExtensions:
|
||||||
|
arguments.append("-AllExtensions")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "dump_cf_log.txt")
|
||||||
|
arguments.extend(["/Out", out_file])
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print(f"Configuration dumped successfully to: {args.OutputFile}")
|
||||||
|
else:
|
||||||
|
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.isdir(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-dump-xml
|
name: db-dump-xml
|
||||||
description: Выгрузка конфигурации 1С в XML-файлы. Используй когда нужно выгрузить конфигурацию в файлы, XML, исходники, DumpConfigToFiles
|
description: Выгрузка конфигурации 1С в XML-файлы. Используй когда пользователь просит выгрузить конфигурацию в файлы, XML, исходники, DumpConfigToFiles
|
||||||
argument-hint: "[database] [outputDir]"
|
argument-hint: "[database] [outputDir]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -29,7 +29,7 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
Если в записи базы указан `configSrc` — используй как каталог выгрузки по умолчанию.
|
Если в записи базы указан `configSrc` — используй как каталог выгрузки по умолчанию.
|
||||||
@@ -37,14 +37,14 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-dump-xml/scripts/db-dump-xml.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -68,23 +68,30 @@ python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" <параметры
|
|||||||
| `Partial` | Частичная — выбранные объекты из параметра `-Objects` |
|
| `Partial` | Частичная — выбранные объекты из параметра `-Objects` |
|
||||||
| `UpdateInfo` | Обновить только ConfigDumpInfo.xml без выгрузки файлов |
|
| `UpdateInfo` | Обновить только ConfigDumpInfo.xml без выгрузки файлов |
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
> Если пользователь просит выгрузить конкретные объекты — используй `-Mode Partial` с `-Objects`.
|
> Если пользователь просит выгрузить конкретные объекты — используй `-Mode Partial` с `-Objects`.
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Полная выгрузка (файловая база)
|
# Полная выгрузка (файловая база)
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" -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/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
|
||||||
|
|
||||||
# Инкрементальная выгрузка
|
# Инкрементальная выгрузка
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Changes
|
powershell.exe -NoProfile -File .claude/skills/db-dump-xml/scripts/db-dump-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Changes
|
||||||
|
|
||||||
# Частичная выгрузка
|
# Частичная выгрузка
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Objects "Справочник.Номенклатура,Документ.Заказ"
|
powershell.exe -NoProfile -File .claude/skills/db-dump-xml/scripts/db-dump-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Objects "Справочник.Номенклатура,Документ.Заказ"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
powershell.exe -NoProfile -File .claude/skills/db-dump-xml/scripts/db-dump-xml.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Dev" -UserName "Admin" -Password "secret" -ConfigDir "C:\WS\cfsrc" -Mode Full
|
||||||
|
|
||||||
# Выгрузка расширения
|
# Выгрузка расширения
|
||||||
python ".opencode/skills/db-dump-xml/scripts/db-dump-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/db-dump-xml/scripts/db-dump-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||||
```
|
```
|
||||||
+6
-105
@@ -1,6 +1,5 @@
|
|||||||
# db-dump-xml v1.8 — Dump 1C configuration to XML files
|
# db-dump-xml v1.0 — Dump 1C configuration to XML files
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Выгрузка конфигурации 1С в XML-файлы
|
Выгрузка конфигурации 1С в XML-файлы
|
||||||
@@ -100,85 +99,25 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
|
|
||||||
# --- Validate connection ---
|
# --- Validate connection ---
|
||||||
if ($engine -eq "ibcmd") {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
if (-not $InfoBasePath) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -200,44 +139,6 @@ $tempDir = Join-Path $env:TEMP "db_dump_xml_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only; hierarchical Full/Changes) ---
|
|
||||||
if ($Format -eq "Plain") {
|
|
||||||
Write-Host "Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
if ($AllExtensions) {
|
|
||||||
$arguments = @("infobase", "config", "export", "all-extensions", "$ConfigDir", "--db-path=$InfoBasePath")
|
|
||||||
} elseif ($Mode -eq "UpdateInfo") {
|
|
||||||
Write-Host "Error: ibcmd config export does not support Mode UpdateInfo; use 1cv8" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
} elseif ($Mode -eq "Partial") {
|
|
||||||
$objList = @($Objects -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
|
||||||
$arguments = @("infobase", "config", "export", "objects") + $objList
|
|
||||||
$arguments += "--out=$ConfigDir", "--db-path=$InfoBasePath"
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
} else {
|
|
||||||
$arguments = @("infobase", "config", "export", "--db-path=$InfoBasePath")
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
$arguments += "$ConfigDir"
|
|
||||||
}
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Configuration exported successfully to: $ConfigDir" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error exporting configuration (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-dump-xml v1.0 — Dump 1C configuration to XML files
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
candidates = glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
||||||
|
if candidates:
|
||||||
|
candidates.sort()
|
||||||
|
return candidates[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Dump 1C configuration to XML files",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
|
||||||
|
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
|
||||||
|
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("-ConfigDir", required=True, help="Directory for configuration dump")
|
||||||
|
parser.add_argument(
|
||||||
|
"-Mode",
|
||||||
|
default="Changes",
|
||||||
|
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("-Extension", default="", help="Extension name to dump")
|
||||||
|
parser.add_argument("-AllExtensions", action="store_true", help="Dump all extensions")
|
||||||
|
parser.add_argument(
|
||||||
|
"-Format",
|
||||||
|
default="Hierarchical",
|
||||||
|
choices=["Hierarchical", "Plain"],
|
||||||
|
help="Dump format (default: Hierarchical)",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# --- Resolve V8Path ---
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Validate Partial mode ---
|
||||||
|
if args.Mode == "Partial" and not args.Objects:
|
||||||
|
print("Error: -Objects required for Partial mode", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Create output dir if needed ---
|
||||||
|
if not os.path.exists(args.ConfigDir):
|
||||||
|
os.makedirs(args.ConfigDir, exist_ok=True)
|
||||||
|
print(f"Created output directory: {args.ConfigDir}")
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_dump_xml_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
|
||||||
|
else:
|
||||||
|
arguments += ["/F", args.InfoBasePath]
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments += ["/DumpConfigToFiles", args.ConfigDir]
|
||||||
|
arguments += ["-Format", args.Format]
|
||||||
|
|
||||||
|
if args.Mode == "Full":
|
||||||
|
print("Executing full configuration dump...")
|
||||||
|
elif args.Mode == "Changes":
|
||||||
|
print("Executing incremental configuration dump...")
|
||||||
|
arguments.append("-update")
|
||||||
|
arguments.append("-force")
|
||||||
|
elif args.Mode == "Partial":
|
||||||
|
print("Executing partial configuration dump...")
|
||||||
|
object_list = [obj.strip() for obj in args.Objects.split(",") if obj.strip()]
|
||||||
|
|
||||||
|
list_file = os.path.join(temp_dir, "dump_list.txt")
|
||||||
|
with open(list_file, "w", encoding="utf-8-sig") as f:
|
||||||
|
f.write("\n".join(object_list))
|
||||||
|
|
||||||
|
arguments += ["-listFile", list_file]
|
||||||
|
print(f"Objects to dump: {len(object_list)}")
|
||||||
|
for obj in object_list:
|
||||||
|
print(f" {obj}")
|
||||||
|
elif args.Mode == "UpdateInfo":
|
||||||
|
print("Updating ConfigDumpInfo.xml...")
|
||||||
|
arguments.append("-configDumpInfoOnly")
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if args.Extension:
|
||||||
|
arguments += ["-Extension", args.Extension]
|
||||||
|
elif args.AllExtensions:
|
||||||
|
arguments.append("-AllExtensions")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "dump_log.txt")
|
||||||
|
arguments += ["/Out", out_file]
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print("Dump completed successfully")
|
||||||
|
print(f"Configuration dumped to: {args.ConfigDir}")
|
||||||
|
else:
|
||||||
|
print(f"Error dumping configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-list
|
name: db-list
|
||||||
description: Управление реестром баз данных 1С (.v8-project.json). Используй когда нужно работать с реестром баз — список баз, зарегистрировать базу в реестре, какие базы есть
|
description: Управление реестром баз данных 1С (.v8-project.json). Используй когда пользователь говорит про базы данных, список баз, "добавь базу", "какие базы есть"
|
||||||
argument-hint: "[add|remove|show]"
|
argument-hint: "[add|remove|show]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Read
|
- Read
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-load-cf
|
name: db-load-cf
|
||||||
description: Загрузка конфигурации 1С из CF-файла. Используй когда нужно загрузить конфигурацию из CF, восстановить из бэкапа CF
|
description: Загрузка конфигурации 1С из CF-файла. Используй когда пользователь просит загрузить конфигурацию из CF, восстановить из бэкапа CF
|
||||||
argument-hint: <input.cf> [database]
|
argument-hint: <input.cf> [database]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -29,21 +29,21 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-load-cf/scripts/db-load-cf.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-load-cf/scripts/db-load-cf.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -55,19 +55,27 @@ python ".opencode/skills/db-load-cf/scripts/db-load-cf.py" <параметры>
|
|||||||
|
|
||||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
## После выполнения
|
## После выполнения
|
||||||
|
|
||||||
**Предложи выполнить `/db-update`** — загрузка CF обновляет только «основную» конфигурацию конфигуратора, для применения к БД нужен `/UpdateDBCfg`
|
1. Прочитай лог-файл и покажи результат
|
||||||
|
2. **Предложи выполнить `/db-update`** — загрузка CF обновляет только «основную» конфигурацию конфигуратора, для применения к БД нужен `/UpdateDBCfg`
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Файловая база
|
# Файловая база
|
||||||
python ".opencode/skills/db-load-cf/scripts/db-load-cf.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\config.cf"
|
powershell.exe -NoProfile -File .claude/skills/db-load-cf/scripts/db-load-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "C:\backup\config.cf"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/db-load-cf/scripts/db-load-cf.py" -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "config.cf"
|
powershell.exe -NoProfile -File .claude/skills/db-load-cf/scripts/db-load-cf.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyApp_Test" -UserName "Admin" -Password "secret" -InputFile "config.cf"
|
||||||
|
|
||||||
# Загрузка расширения
|
# Загрузка расширения
|
||||||
python ".opencode/skills/db-load-cf/scripts/db-load-cf.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "ext.cfe" -Extension "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/db-load-cf/scripts/db-load-cf.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -InputFile "ext.cfe" -Extension "МоёРасширение"
|
||||||
```
|
```
|
||||||
+6
-93
@@ -1,6 +1,5 @@
|
|||||||
# db-load-cf v1.6 — Load 1C configuration from CF file
|
# db-load-cf v1.0 — Load 1C configuration from CF file
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Загрузка конфигурации 1С из CF-файла
|
Загрузка конфигурации 1С из CF-файла
|
||||||
@@ -77,85 +76,25 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
|
|
||||||
# --- Validate connection ---
|
# --- Validate connection ---
|
||||||
if ($engine -eq "ibcmd") {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
if (-not $InfoBasePath) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -171,32 +110,6 @@ $tempDir = Join-Path $env:TEMP "db_load_cf_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only) ---
|
|
||||||
if ($AllExtensions) {
|
|
||||||
Write-Host "Error: ibcmd config load does not support -AllExtensions (use -Extension)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
$arguments = @("infobase", "config", "load", "--db-path=$InfoBasePath")
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
$arguments += "$InputFile"
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Configuration loaded successfully from: $InputFile" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error loading configuration (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-load-cf v1.0 — Load 1C configuration from CF file
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
found = sorted(glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe"))
|
||||||
|
if found:
|
||||||
|
return found[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Load 1C configuration from CF file",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="")
|
||||||
|
parser.add_argument("-InfoBasePath", default="")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="")
|
||||||
|
parser.add_argument("-InfoBaseRef", default="")
|
||||||
|
parser.add_argument("-UserName", default="")
|
||||||
|
parser.add_argument("-Password", default="")
|
||||||
|
parser.add_argument("-InputFile", required=True)
|
||||||
|
parser.add_argument("-Extension", default="")
|
||||||
|
parser.add_argument("-AllExtensions", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
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)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_load_cf_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
|
||||||
|
else:
|
||||||
|
arguments.extend(["/F", args.InfoBasePath])
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments.extend(["/LoadCfg", args.InputFile])
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if args.Extension:
|
||||||
|
arguments.extend(["-Extension", args.Extension])
|
||||||
|
elif args.AllExtensions:
|
||||||
|
arguments.append("-AllExtensions")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "load_cf_log.txt")
|
||||||
|
arguments.extend(["/Out", out_file])
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print(f"Configuration loaded successfully from: {args.InputFile}")
|
||||||
|
else:
|
||||||
|
print(f"Error loading configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.isdir(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-load-git
|
name: db-load-git
|
||||||
description: Загрузка изменений из Git в базу 1С. Используй когда нужно загрузить изменения из гита, обновить базу из репозитория, partial load из коммита
|
description: Загрузка изменений из Git в базу 1С. Используй когда пользователь просит загрузить изменения из гита, обновить базу из репозитория, partial load из коммита
|
||||||
argument-hint: "[database] [source]"
|
argument-hint: "[database] [source]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -30,7 +30,7 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
Если в записи базы указан `configSrc` — используй как каталог конфигурации.
|
Если в записи базы указан `configSrc` — используй как каталог конфигурации.
|
||||||
@@ -38,14 +38,14 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-load-git/scripts/db-load-git.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-load-git/scripts/db-load-git.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -64,14 +64,15 @@ python ".opencode/skills/db-load-git/scripts/db-load-git.py" <параметры
|
|||||||
|
|
||||||
## После выполнения
|
## После выполнения
|
||||||
|
|
||||||
Если `-UpdateDB` не был указан — **предложить `/db-update`** для применения изменений к БД
|
1. Показать список загруженных файлов и результат из лога
|
||||||
|
2. Если `-UpdateDB` не был указан — **предложить `/db-update`** для применения изменений к БД
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Все незафиксированные изменения
|
# Все незафиксированные изменения
|
||||||
python ".opencode/skills/db-load-git/scripts/db-load-git.py" -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/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
|
||||||
|
|
||||||
# Из диапазона коммитов
|
# Из диапазона коммитов
|
||||||
python ".opencode/skills/db-load-git/scripts/db-load-git.py" -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source Commit -CommitRange "HEAD~3..HEAD"
|
powershell.exe -NoProfile -File .claude/skills/db-load-git/scripts/db-load-git.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\WS\cfsrc" -Source Commit -CommitRange "HEAD~3..HEAD"
|
||||||
```
|
```
|
||||||
+23
-141
@@ -1,6 +1,5 @@
|
|||||||
# db-load-git v1.11 — Load Git changes into 1C database
|
# db-load-git v1.3 — Load Git changes into 1C database
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Загрузка изменений из Git в базу 1С
|
Загрузка изменений из Git в базу 1С
|
||||||
@@ -121,86 +120,27 @@ function Get-ObjectXmlFromSubFile {
|
|||||||
|
|
||||||
# --- Resolve V8Path (skip if DryRun) ---
|
# --- Resolve V8Path (skip if DryRun) ---
|
||||||
if (-not $DryRun) {
|
if (-not $DryRun) {
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine + validate connection (skip if DryRun) ---
|
# --- Validate connection (skip if DryRun) ---
|
||||||
$engine = "1cv8"
|
|
||||||
if (-not $DryRun) {
|
if (-not $DryRun) {
|
||||||
function Invoke-IbcmdProcess {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$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
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -227,15 +167,6 @@ try {
|
|||||||
}
|
}
|
||||||
|
|
||||||
# --- Get changed files from Git ---
|
# --- Get changed files from Git ---
|
||||||
# Все git-вызовы для сбора путей идут через один хелпер с -c core.quotePath=false,
|
|
||||||
# иначе кириллические пути возвращаются в octal-виде и не распознаются (зеркало run_git в .py).
|
|
||||||
function Invoke-GitLines {
|
|
||||||
param([string[]]$GitArgs)
|
|
||||||
$out = git -c core.quotePath=false @GitArgs 2>&1
|
|
||||||
if ($LASTEXITCODE -eq 0) { return $out }
|
|
||||||
return @()
|
|
||||||
}
|
|
||||||
|
|
||||||
$changedFiles = @()
|
$changedFiles = @()
|
||||||
$ConfigDir = (Resolve-Path $ConfigDir).Path.TrimEnd('\')
|
$ConfigDir = (Resolve-Path $ConfigDir).Path.TrimEnd('\')
|
||||||
$configDirNormalized = $ConfigDir.Replace('\', '/')
|
$configDirNormalized = $ConfigDir.Replace('\', '/')
|
||||||
@@ -245,22 +176,29 @@ try {
|
|||||||
switch ($Source) {
|
switch ($Source) {
|
||||||
"Staged" {
|
"Staged" {
|
||||||
Write-Host "Getting staged changes..."
|
Write-Host "Getting staged changes..."
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('diff', '--cached', '--name-only', '--relative')
|
$raw = git diff --cached --name-only --relative 2>&1
|
||||||
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
}
|
}
|
||||||
"Unstaged" {
|
"Unstaged" {
|
||||||
Write-Host "Getting unstaged changes..."
|
Write-Host "Getting unstaged changes..."
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('diff', '--name-only', '--relative')
|
$raw = git diff --name-only --relative 2>&1
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('ls-files', '--others', '--exclude-standard')
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
|
$raw = git ls-files --others --exclude-standard 2>&1
|
||||||
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
}
|
}
|
||||||
"Commit" {
|
"Commit" {
|
||||||
Write-Host "Getting changes from $CommitRange..."
|
Write-Host "Getting changes from $CommitRange..."
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('diff', '--name-only', '--relative', $CommitRange)
|
$raw = git diff --name-only --relative $CommitRange 2>&1
|
||||||
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
}
|
}
|
||||||
"All" {
|
"All" {
|
||||||
Write-Host "Getting all uncommitted changes..."
|
Write-Host "Getting all uncommitted changes..."
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('diff', '--cached', '--name-only', '--relative')
|
$raw = git diff --cached --name-only --relative 2>&1
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('diff', '--name-only', '--relative')
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
$changedFiles += Invoke-GitLines -GitArgs @('ls-files', '--others', '--exclude-standard')
|
$raw = git diff --name-only --relative 2>&1
|
||||||
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
|
$raw = git ls-files --others --exclude-standard 2>&1
|
||||||
|
if ($LASTEXITCODE -eq 0) { $changedFiles += $raw }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -278,16 +216,13 @@ Write-Host "Git changes detected: $($changedFiles.Count) files"
|
|||||||
|
|
||||||
# --- Filter and map to config files ---
|
# --- Filter and map to config files ---
|
||||||
$configFiles = @()
|
$configFiles = @()
|
||||||
$supportSkipped = @()
|
|
||||||
|
|
||||||
foreach ($file in $changedFiles) {
|
foreach ($file in $changedFiles) {
|
||||||
$file = $file.Trim().Replace('\', '/')
|
$file = $file.Trim().Replace('\', '/')
|
||||||
if ([string]::IsNullOrWhiteSpace($file)) { continue }
|
if ([string]::IsNullOrWhiteSpace($file)) { continue }
|
||||||
|
|
||||||
# Skip service files (not partially loadable). Support-state files are tracked
|
# Skip service files
|
||||||
# to warn the user: support changes apply only via a full load.
|
if ($file -eq "ConfigDumpInfo.xml") { continue }
|
||||||
if ($file -match 'ParentConfigurations\.bin$') { $supportSkipped += $file; continue }
|
|
||||||
if ($file -eq "ConfigDumpInfo.xml" -or $file -match '(^|/)ConfigDumpInfo\.xml$') { continue }
|
|
||||||
|
|
||||||
$fullPath = Join-Path $ConfigDir $file
|
$fullPath = Join-Path $ConfigDir $file
|
||||||
|
|
||||||
@@ -330,12 +265,6 @@ foreach ($file in $changedFiles) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($supportSkipped.Count -gt 0) {
|
|
||||||
Write-Host "[ВНИМАНИЕ] Состояние поддержки изменено в коммите, но частично не загружается (исключено):" -ForegroundColor Yellow
|
|
||||||
foreach ($sf in $supportSkipped) { Write-Host " - $sf" -ForegroundColor Yellow }
|
|
||||||
Write-Host " Смена состояния поддержки применяется только полной загрузкой (db-load-xml -Mode Full)." -ForegroundColor Yellow
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($configFiles.Count -eq 0) {
|
if ($configFiles.Count -eq 0) {
|
||||||
Write-Host "No configuration files found in changes"
|
Write-Host "No configuration files found in changes"
|
||||||
exit 0
|
exit 0
|
||||||
@@ -356,53 +285,6 @@ $tempDir = Join-Path $env:TEMP "db_load_git_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only; import specific files) ---
|
|
||||||
if ($Format -eq "Plain") {
|
|
||||||
Write-Host "Error: ibcmd config import supports hierarchical format only (use -Format Hierarchical or 1cv8)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
if ($AllExtensions) {
|
|
||||||
Write-Host "Error: ibcmd config import does not support -AllExtensions (use -Extension or 1cv8)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
$arguments = @("infobase", "config", "import", "files") + $configFiles
|
|
||||||
$arguments += "--base-dir=$ConfigDir", "--db-path=$InfoBasePath"
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -ne 0) {
|
|
||||||
Write-Host "Error loading changes (code: $exitCode)" -ForegroundColor Red
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
Write-Host "Changes loaded successfully ($($configFiles.Count) files)" -ForegroundColor Green
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
if ($UpdateDB) {
|
|
||||||
$applyArgs = @("infobase", "config", "apply", "--db-path=$InfoBasePath", "--force")
|
|
||||||
if ($UserName) { $applyArgs += "--user=$UserName" }
|
|
||||||
if ($Password) { $applyArgs += "--password=$Password" }
|
|
||||||
$applyArgs += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($applyArgs -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $applyArgs
|
|
||||||
$applyOut = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Database configuration updated successfully" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error updating database configuration (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($applyOut) { Write-Host ($applyOut | Out-String) }
|
|
||||||
}
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Write list file (UTF-8 with BOM) ---
|
# --- Write list file (UTF-8 with BOM) ---
|
||||||
$listFile = Join-Path $tempDir "load_list.txt"
|
$listFile = Join-Path $tempDir "load_list.txt"
|
||||||
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||||
+16
-151
@@ -1,11 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# db-load-git v1.11 — Load Git changes into 1C database
|
# db-load-git v1.3 — Load Git changes into 1C database
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import atexit
|
|
||||||
import glob
|
import glob
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
import re
|
import re
|
||||||
@@ -15,90 +13,26 @@ import sys
|
|||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
def _find_project_v8path():
|
|
||||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
|
||||||
d = os.getcwd()
|
|
||||||
while True:
|
|
||||||
pf = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pf):
|
|
||||||
try:
|
|
||||||
with open(pf, encoding="utf-8-sig") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
v = data.get("v8path")
|
|
||||||
if v:
|
|
||||||
return v
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return None
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
return None
|
|
||||||
d = parent
|
|
||||||
|
|
||||||
|
|
||||||
def _version_dir(p):
|
|
||||||
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
|
|
||||||
parent = os.path.dirname(p)
|
|
||||||
if os.path.basename(parent).lower() == "bin":
|
|
||||||
parent = os.path.dirname(parent)
|
|
||||||
return os.path.basename(parent)
|
|
||||||
|
|
||||||
|
|
||||||
def _version_key(p):
|
|
||||||
"""Numeric sort key from version dir name."""
|
|
||||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_v8path(v8path):
|
def resolve_v8path(v8path):
|
||||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
"""Resolve path to 1cv8.exe."""
|
||||||
if not v8path:
|
if not v8path:
|
||||||
v8path = _find_project_v8path()
|
candidates = glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
||||||
if not v8path:
|
|
||||||
if os.name == "nt":
|
|
||||||
candidates = (
|
|
||||||
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
|
||||||
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
|
|
||||||
candidates = glob.glob("/opt/1cv8/*/1cv8")
|
|
||||||
if candidates:
|
if candidates:
|
||||||
v8path = max(candidates, key=_version_key)
|
candidates.sort()
|
||||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
return candidates[-1]
|
||||||
else:
|
else:
|
||||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if os.path.isdir(v8path):
|
elif os.path.isdir(v8path):
|
||||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
|
||||||
v8path = os.path.join(v8path, exe)
|
|
||||||
if not os.path.isfile(v8path):
|
if not os.path.isfile(v8path):
|
||||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
return v8path
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
IBCMD_NOUSER_HINT = (
|
|
||||||
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
|
|
||||||
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
|
|
||||||
"call may block instead of failing. If it does not return promptly, abort and "
|
|
||||||
"re-run with -UserName and -Password.\n"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
|
||||||
"""Run an ibcmd command non-interactively.
|
|
||||||
|
|
||||||
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
|
|
||||||
On Windows without -UserName ibcmd reads the console directly and may still block —
|
|
||||||
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.stderr.flush()
|
|
||||||
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
|
|
||||||
|
|
||||||
|
|
||||||
def get_object_xml_from_subfile(relative_path):
|
def get_object_xml_from_subfile(relative_path):
|
||||||
"""Map sub-file path (BSL, HTML, etc.) to object XML path."""
|
"""Map sub-file path (BSL, HTML, etc.) to object XML path."""
|
||||||
parts = re.split(r"[\\/]", relative_path)
|
parts = re.split(r"[\\/]", relative_path)
|
||||||
@@ -110,7 +44,7 @@ def get_object_xml_from_subfile(relative_path):
|
|||||||
def run_git(config_dir, git_args):
|
def run_git(config_dir, git_args):
|
||||||
"""Run a git command in config_dir and return output lines on success."""
|
"""Run a git command in config_dir and return output lines on success."""
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
["git", "-c", "core.quotePath=false"] + git_args,
|
["git"] + git_args,
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
@@ -159,15 +93,9 @@ def main():
|
|||||||
if not args.DryRun:
|
if not args.DryRun:
|
||||||
v8path = resolve_v8path(args.V8Path)
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
# --- Detect engine + validate connection (skip if DryRun) ---
|
# --- Validate connection (skip if DryRun) ---
|
||||||
engine = "1cv8"
|
|
||||||
if not args.DryRun:
|
if not args.DryRun:
|
||||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
if engine == "ibcmd":
|
|
||||||
if not args.InfoBasePath:
|
|
||||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath)", file=sys.stderr)
|
|
||||||
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", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
@@ -218,19 +146,14 @@ def main():
|
|||||||
|
|
||||||
# --- Filter and map to config files ---
|
# --- Filter and map to config files ---
|
||||||
config_files = []
|
config_files = []
|
||||||
support_skipped = []
|
|
||||||
|
|
||||||
for file in changed_files:
|
for file in changed_files:
|
||||||
file = file.strip().replace("\\", "/")
|
file = file.strip().replace("\\", "/")
|
||||||
if not file:
|
if not file:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Skip service files (not partially loadable). Support-state files are
|
# Skip service files
|
||||||
# tracked to warn: support changes apply only via a full load.
|
if file == "ConfigDumpInfo.xml":
|
||||||
if file.endswith("ParentConfigurations.bin"):
|
|
||||||
support_skipped.append(file)
|
|
||||||
continue
|
|
||||||
if file == "ConfigDumpInfo.xml" or file.endswith("/ConfigDumpInfo.xml"):
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
full_path = os.path.join(args.ConfigDir, file)
|
full_path = os.path.join(args.ConfigDir, file)
|
||||||
@@ -263,12 +186,6 @@ def main():
|
|||||||
if rel_path not in config_files:
|
if rel_path not in config_files:
|
||||||
config_files.append(rel_path)
|
config_files.append(rel_path)
|
||||||
|
|
||||||
if support_skipped:
|
|
||||||
print("[ВНИМАНИЕ] Состояние поддержки изменено в коммите, но частично не загружается (исключено):", file=sys.stderr)
|
|
||||||
for sf in support_skipped:
|
|
||||||
print(f" - {sf}", file=sys.stderr)
|
|
||||||
print(" Смена состояния поддержки применяется только полной загрузкой (db-load-xml -Mode Full).", file=sys.stderr)
|
|
||||||
|
|
||||||
if len(config_files) == 0:
|
if len(config_files) == 0:
|
||||||
print("No configuration files found in changes")
|
print("No configuration files found in changes")
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
@@ -288,58 +205,6 @@ def main():
|
|||||||
os.makedirs(temp_dir, exist_ok=True)
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
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)
|
|
||||||
sys.exit(1)
|
|
||||||
if args.AllExtensions:
|
|
||||||
print("Error: ibcmd config import does not support -AllExtensions (use -Extension or 1cv8)", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
arguments = ["infobase", "config", "import", "files"] + config_files
|
|
||||||
arguments += [f"--base-dir={args.ConfigDir}", f"--db-path={args.InfoBasePath}"]
|
|
||||||
if args.Extension:
|
|
||||||
arguments.append(f"--extension={args.Extension}")
|
|
||||||
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
|
|
||||||
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
|
|
||||||
if args.UserName:
|
|
||||||
arguments.append(f"--user={args.UserName}")
|
|
||||||
if args.Password:
|
|
||||||
arguments.append(f"--password={args.Password}")
|
|
||||||
arguments.append(f"--data={ib_data}")
|
|
||||||
print(f"Running: ibcmd {' '.join(arguments)}")
|
|
||||||
result = run_ibcmd([v8path] + arguments, bool(args.UserName))
|
|
||||||
if result.returncode != 0:
|
|
||||||
print(f"Error loading changes (code: {result.returncode})", file=sys.stderr)
|
|
||||||
if result.stdout:
|
|
||||||
print(result.stdout)
|
|
||||||
if result.stderr:
|
|
||||||
print(result.stderr, file=sys.stderr)
|
|
||||||
sys.exit(result.returncode)
|
|
||||||
print(f"Changes loaded successfully ({len(config_files)} files)")
|
|
||||||
if result.stdout:
|
|
||||||
print(result.stdout)
|
|
||||||
exit_code = 0
|
|
||||||
if args.UpdateDB:
|
|
||||||
apply_args = ["infobase", "config", "apply", f"--db-path={args.InfoBasePath}", "--force"]
|
|
||||||
if args.UserName:
|
|
||||||
apply_args.append(f"--user={args.UserName}")
|
|
||||||
if args.Password:
|
|
||||||
apply_args.append(f"--password={args.Password}")
|
|
||||||
apply_args.append(f"--data={ib_data}")
|
|
||||||
print(f"Running: ibcmd {' '.join(apply_args)}")
|
|
||||||
ar = run_ibcmd([v8path] + apply_args, bool(args.UserName))
|
|
||||||
exit_code = ar.returncode
|
|
||||||
if exit_code == 0:
|
|
||||||
print("Database configuration updated successfully")
|
|
||||||
else:
|
|
||||||
print(f"Error updating database configuration (code: {exit_code})", file=sys.stderr)
|
|
||||||
if ar.stdout:
|
|
||||||
print(ar.stdout)
|
|
||||||
if ar.stderr:
|
|
||||||
print(ar.stderr, file=sys.stderr)
|
|
||||||
sys.exit(exit_code)
|
|
||||||
|
|
||||||
# --- Write list file (UTF-8 with BOM) ---
|
# --- Write list file (UTF-8 with BOM) ---
|
||||||
list_file = os.path.join(temp_dir, "load_list.txt")
|
list_file = os.path.join(temp_dir, "load_list.txt")
|
||||||
with open(list_file, "w", encoding="utf-8-sig") as f:
|
with open(list_file, "w", encoding="utf-8-sig") as f:
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-load-xml
|
name: db-load-xml
|
||||||
description: Загрузка конфигурации 1С из XML-файлов. Используй когда нужно загрузить конфигурацию из файлов, XML, исходников, LoadConfigFromFiles
|
description: Загрузка конфигурации 1С из XML-файлов. Используй когда пользователь просит загрузить конфигурацию из файлов, XML, исходников, LoadConfigFromFiles
|
||||||
argument-hint: <configDir> [database]
|
argument-hint: <configDir> [database]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -30,7 +30,7 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
Если в записи базы указан `configSrc` — используй как каталог загрузки по умолчанию.
|
Если в записи базы указан `configSrc` — используй как каталог загрузки по умолчанию.
|
||||||
@@ -38,14 +38,14 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-load-xml/scripts/db-load-xml.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-load-xml/scripts/db-load-xml.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -80,22 +80,30 @@ Documents/Заказ.xml
|
|||||||
Documents/Заказ/Forms/ФормаДокумента.xml
|
Documents/Заказ/Forms/ФормаДокумента.xml
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
## После выполнения
|
## После выполнения
|
||||||
|
|
||||||
Если `-UpdateDB` не был указан — **предложи выполнить `/db-update`** для применения изменений к БД
|
1. Прочитай лог и покажи результат
|
||||||
|
2. Если `-UpdateDB` не был указан — **предложи выполнить `/db-update`** для применения изменений к БД
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Полная загрузка
|
# Полная загрузка
|
||||||
python ".opencode/skills/db-load-xml/scripts/db-load-xml.py" -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/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
|
||||||
|
|
||||||
# Частичная загрузка конкретных файлов
|
# Частичная загрузка конкретных файлов
|
||||||
python ".opencode/skills/db-load-xml/scripts/db-load-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
|
powershell.exe -NoProfile -File .claude/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"
|
||||||
|
|
||||||
# Загрузка расширения
|
# Загрузка расширения
|
||||||
python ".opencode/skills/db-load-xml/scripts/db-load-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/db-load-xml/scripts/db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\ext_src" -Mode Full -Extension "МоёРасширение"
|
||||||
|
|
||||||
# Загрузка + обновление БД в одном запуске
|
# Загрузка + обновление БД в одном запуске
|
||||||
python ".opencode/skills/db-load-xml/scripts/db-load-xml.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full -UpdateDB
|
powershell.exe -NoProfile -File .claude/skills/db-load-xml/scripts/db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -ConfigDir "C:\WS\cfsrc" -Mode Full -UpdateDB
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
# db-load-xml v1.1 — Load 1C configuration from XML files
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Загрузка конфигурации 1С из XML-файлов
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Загружает конфигурацию в информационную базу из XML-файлов.
|
||||||
|
Поддерживает полную и частичную загрузку.
|
||||||
|
|
||||||
|
.PARAMETER V8Path
|
||||||
|
Путь к каталогу bin платформы или к 1cv8.exe
|
||||||
|
|
||||||
|
.PARAMETER InfoBasePath
|
||||||
|
Путь к файловой информационной базе
|
||||||
|
|
||||||
|
.PARAMETER InfoBaseServer
|
||||||
|
Сервер 1С (для серверной базы)
|
||||||
|
|
||||||
|
.PARAMETER InfoBaseRef
|
||||||
|
Имя базы на сервере
|
||||||
|
|
||||||
|
.PARAMETER UserName
|
||||||
|
Имя пользователя 1С
|
||||||
|
|
||||||
|
.PARAMETER Password
|
||||||
|
Пароль пользователя
|
||||||
|
|
||||||
|
.PARAMETER ConfigDir
|
||||||
|
Каталог XML-исходников конфигурации
|
||||||
|
|
||||||
|
.PARAMETER Mode
|
||||||
|
Режим загрузки: Full или Partial (по умолчанию Full)
|
||||||
|
|
||||||
|
.PARAMETER Files
|
||||||
|
Относительные пути файлов через запятую (для режима Partial)
|
||||||
|
|
||||||
|
.PARAMETER ListFile
|
||||||
|
Путь к файлу со списком файлов (альтернатива -Files, для режима Partial)
|
||||||
|
|
||||||
|
.PARAMETER Extension
|
||||||
|
Имя расширения для загрузки
|
||||||
|
|
||||||
|
.PARAMETER AllExtensions
|
||||||
|
Загрузить все расширения
|
||||||
|
|
||||||
|
.PARAMETER Format
|
||||||
|
Формат файлов: Hierarchical или Plain (по умолчанию Hierarchical)
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
.\db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Full
|
||||||
|
|
||||||
|
.EXAMPLE
|
||||||
|
.\db-load-xml.ps1 -InfoBasePath "C:\Bases\MyDB" -ConfigDir "C:\src" -Mode Partial -Files "Catalogs/Номенклатура.xml,Catalogs/Номенклатура/Ext/ObjectModule.bsl"
|
||||||
|
#>
|
||||||
|
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$V8Path,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$InfoBasePath,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$InfoBaseServer,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$InfoBaseRef,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$UserName,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$Password,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$true)]
|
||||||
|
[string]$ConfigDir,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[ValidateSet("Full", "Partial")]
|
||||||
|
[string]$Mode = "Full",
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$Files,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$ListFile,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[string]$Extension,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[switch]$AllExtensions,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[ValidateSet("Hierarchical", "Plain")]
|
||||||
|
[string]$Format = "Hierarchical",
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[switch]$UpdateDB
|
||||||
|
)
|
||||||
|
|
||||||
|
$OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
|
# --- Resolve V8Path ---
|
||||||
|
if (-not $V8Path) {
|
||||||
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
|
if ($found) {
|
||||||
|
$V8Path = $found.FullName
|
||||||
|
} else {
|
||||||
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not (Test-Path $V8Path)) {
|
||||||
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Validate config dir ---
|
||||||
|
if (-not (Test-Path $ConfigDir)) {
|
||||||
|
Write-Host "Error: config directory not found: $ConfigDir" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 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
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
$tempDir = Join-Path $env:TEMP "db_load_xml_$(Get-Random)"
|
||||||
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
|
try {
|
||||||
|
# --- Build arguments ---
|
||||||
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
|
if ($InfoBaseServer -and $InfoBaseRef) {
|
||||||
|
$arguments += "/S", "`"$InfoBaseServer/$InfoBaseRef`""
|
||||||
|
} else {
|
||||||
|
$arguments += "/F", "`"$InfoBasePath`""
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($UserName) { $arguments += "/N`"$UserName`"" }
|
||||||
|
if ($Password) { $arguments += "/P`"$Password`"" }
|
||||||
|
|
||||||
|
$arguments += "/LoadConfigFromFiles", "`"$ConfigDir`""
|
||||||
|
|
||||||
|
if ($Mode -eq "Full") {
|
||||||
|
Write-Host "Executing full configuration load..."
|
||||||
|
} else {
|
||||||
|
Write-Host "Executing partial configuration load..."
|
||||||
|
|
||||||
|
# Build list file
|
||||||
|
$generatedListFile = $null
|
||||||
|
if ($ListFile) {
|
||||||
|
# Use provided list file
|
||||||
|
if (-not (Test-Path $ListFile)) {
|
||||||
|
Write-Host "Error: list file not found: $ListFile" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$generatedListFile = $ListFile
|
||||||
|
} else {
|
||||||
|
# Generate from -Files parameter
|
||||||
|
$fileList = $Files -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ }
|
||||||
|
$generatedListFile = Join-Path $tempDir "load_list.txt"
|
||||||
|
$utf8Bom = New-Object System.Text.UTF8Encoding($true)
|
||||||
|
[System.IO.File]::WriteAllLines($generatedListFile, $fileList, $utf8Bom)
|
||||||
|
|
||||||
|
Write-Host "Files to load: $($fileList.Count)"
|
||||||
|
foreach ($f in $fileList) { Write-Host " $f" }
|
||||||
|
}
|
||||||
|
|
||||||
|
$arguments += "-listFile", "`"$generatedListFile`""
|
||||||
|
$arguments += "-partial"
|
||||||
|
$arguments += "-updateConfigDumpInfo"
|
||||||
|
}
|
||||||
|
|
||||||
|
$arguments += "-Format", $Format
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if ($Extension) {
|
||||||
|
$arguments += "-Extension", "`"$Extension`""
|
||||||
|
} elseif ($AllExtensions) {
|
||||||
|
$arguments += "-AllExtensions"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- UpdateDB ---
|
||||||
|
if ($UpdateDB) {
|
||||||
|
$arguments += "/UpdateDBCfg"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
$outFile = Join-Path $tempDir "load_log.txt"
|
||||||
|
$arguments += "/Out", "`"$outFile`""
|
||||||
|
$arguments += "/DisableStartupDialogs"
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
Write-Host "Running: 1cv8.exe $($arguments -join ' ')"
|
||||||
|
$process = Start-Process -FilePath $V8Path -ArgumentList $arguments -NoNewWindow -Wait -PassThru
|
||||||
|
$exitCode = $process.ExitCode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if ($exitCode -eq 0) {
|
||||||
|
Write-Host "Load completed successfully" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host "Error loading configuration (code: $exitCode)" -ForegroundColor Red
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Test-Path $outFile) {
|
||||||
|
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||||
|
if ($logContent) {
|
||||||
|
Write-Host "--- Log ---"
|
||||||
|
Write-Host $logContent
|
||||||
|
Write-Host "--- End ---"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
exit $exitCode
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (Test-Path $tempDir) {
|
||||||
|
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-load-xml v1.1 — Load 1C configuration from XML files
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
candidates = glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
||||||
|
if candidates:
|
||||||
|
candidates.sort()
|
||||||
|
return candidates[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Load 1C configuration from XML files",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
|
||||||
|
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
|
||||||
|
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("-ConfigDir", required=True, help="Directory with XML configuration sources")
|
||||||
|
parser.add_argument(
|
||||||
|
"-Mode",
|
||||||
|
default="Full",
|
||||||
|
choices=["Full", "Partial"],
|
||||||
|
help="Load mode (default: Full)",
|
||||||
|
)
|
||||||
|
parser.add_argument("-Files", default="", help="Comma-separated relative file paths (for Partial mode)")
|
||||||
|
parser.add_argument("-ListFile", default="", help="Path to file list (alternative to -Files, for Partial mode)")
|
||||||
|
parser.add_argument("-Extension", default="", help="Extension name to load")
|
||||||
|
parser.add_argument("-AllExtensions", action="store_true", help="Load all extensions")
|
||||||
|
parser.add_argument(
|
||||||
|
"-Format",
|
||||||
|
default="Hierarchical",
|
||||||
|
choices=["Hierarchical", "Plain"],
|
||||||
|
help="File format (default: Hierarchical)",
|
||||||
|
)
|
||||||
|
parser.add_argument("-UpdateDB", action="store_true", help="Also update database configuration after load")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# --- Resolve V8Path ---
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
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)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Validate Partial mode ---
|
||||||
|
if args.Mode == "Partial" and not args.Files and not args.ListFile:
|
||||||
|
print("Error: -Files or -ListFile required for Partial mode", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_load_xml_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
|
||||||
|
else:
|
||||||
|
arguments += ["/F", args.InfoBasePath]
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments += ["/LoadConfigFromFiles", args.ConfigDir]
|
||||||
|
|
||||||
|
if args.Mode == "Full":
|
||||||
|
print("Executing full configuration load...")
|
||||||
|
else:
|
||||||
|
print("Executing partial configuration load...")
|
||||||
|
|
||||||
|
# Build list file
|
||||||
|
generated_list_file = None
|
||||||
|
if args.ListFile:
|
||||||
|
# Use provided list file
|
||||||
|
if not os.path.isfile(args.ListFile):
|
||||||
|
print(f"Error: list file not found: {args.ListFile}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
generated_list_file = args.ListFile
|
||||||
|
else:
|
||||||
|
# Generate from -Files parameter
|
||||||
|
file_list = [f.strip() for f in args.Files.split(",") if f.strip()]
|
||||||
|
generated_list_file = os.path.join(temp_dir, "load_list.txt")
|
||||||
|
with open(generated_list_file, "w", encoding="utf-8-sig") as f:
|
||||||
|
f.write("\n".join(file_list))
|
||||||
|
|
||||||
|
print(f"Files to load: {len(file_list)}")
|
||||||
|
for fl in file_list:
|
||||||
|
print(f" {fl}")
|
||||||
|
|
||||||
|
arguments += ["-listFile", generated_list_file]
|
||||||
|
arguments.append("-partial")
|
||||||
|
arguments.append("-updateConfigDumpInfo")
|
||||||
|
|
||||||
|
arguments += ["-Format", args.Format]
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if args.Extension:
|
||||||
|
arguments += ["-Extension", args.Extension]
|
||||||
|
elif args.AllExtensions:
|
||||||
|
arguments.append("-AllExtensions")
|
||||||
|
|
||||||
|
# --- UpdateDB ---
|
||||||
|
if args.UpdateDB:
|
||||||
|
arguments.append("/UpdateDBCfg")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "load_log.txt")
|
||||||
|
arguments += ["/Out", out_file]
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print("Load completed successfully")
|
||||||
|
else:
|
||||||
|
print(f"Error loading configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-run
|
name: db-run
|
||||||
description: Запуск 1С:Предприятие. Используй когда нужно запустить 1С, открыть базу, запустить предприятие
|
description: Запуск 1С:Предприятие. Используй когда пользователь просит запустить 1С, открыть базу, запустить предприятие
|
||||||
argument-hint: "[database]"
|
argument-hint: "[database]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -29,14 +29,14 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-run/scripts/db-run.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -63,14 +63,14 @@ python ".opencode/skills/db-run/scripts/db-run.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Простой запуск
|
# Простой запуск
|
||||||
python ".opencode/skills/db-run/scripts/db-run.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin"
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin"
|
||||||
|
|
||||||
# Запуск с обработкой
|
# Запуск с обработкой
|
||||||
python ".opencode/skills/db-run/scripts/db-run.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -Execute "C:\epf\МояОбработка.epf"
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -Execute "C:\epf\МояОбработка.epf"
|
||||||
|
|
||||||
# Открыть по навигационной ссылке
|
# Открыть по навигационной ссылке
|
||||||
python ".opencode/skills/db-run/scripts/db-run.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -URL "e1cib/data/Справочник.Номенклатура"
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -URL "e1cib/data/Справочник.Номенклатура"
|
||||||
|
|
||||||
# Серверная база с параметром запуска
|
# Серверная база с параметром запуска
|
||||||
python ".opencode/skills/db-run/scripts/db-run.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -CParam "ЗапуститьОбновление"
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -CParam "ЗапуститьОбновление"
|
||||||
```
|
```
|
||||||
+5
-31
@@ -1,6 +1,5 @@
|
|||||||
# db-run v1.2 — Launch 1C:Enterprise
|
# db-run v1.0 — Launch 1C:Enterprise
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Запуск 1С:Предприятие
|
Запуск 1С:Предприятие
|
||||||
@@ -80,45 +79,20 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
+10
-57
@@ -1,75 +1,28 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# db-run v1.2 — Launch 1C:Enterprise
|
# db-run v1.0 — Launch 1C:Enterprise
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import glob
|
import glob
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
|
|
||||||
def _find_project_v8path():
|
|
||||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
|
||||||
d = os.getcwd()
|
|
||||||
while True:
|
|
||||||
pf = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pf):
|
|
||||||
try:
|
|
||||||
with open(pf, encoding="utf-8-sig") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
v = data.get("v8path")
|
|
||||||
if v:
|
|
||||||
return v
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return None
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
return None
|
|
||||||
d = parent
|
|
||||||
|
|
||||||
|
|
||||||
def _version_dir(p):
|
|
||||||
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
|
|
||||||
parent = os.path.dirname(p)
|
|
||||||
if os.path.basename(parent).lower() == "bin":
|
|
||||||
parent = os.path.dirname(parent)
|
|
||||||
return os.path.basename(parent)
|
|
||||||
|
|
||||||
|
|
||||||
def _version_key(p):
|
|
||||||
"""Numeric sort key from version dir name."""
|
|
||||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_v8path(v8path):
|
def resolve_v8path(v8path):
|
||||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
"""Resolve path to 1cv8.exe."""
|
||||||
if not v8path:
|
if not v8path:
|
||||||
v8path = _find_project_v8path()
|
found = sorted(glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe"))
|
||||||
if not v8path:
|
if found:
|
||||||
if os.name == "nt":
|
return found[-1]
|
||||||
candidates = (
|
|
||||||
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
|
||||||
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
candidates = glob.glob("/opt/1cv8/*/1cv8")
|
|
||||||
if candidates:
|
|
||||||
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)
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if os.path.isdir(v8path):
|
elif os.path.isdir(v8path):
|
||||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
|
||||||
v8path = os.path.join(v8path, exe)
|
|
||||||
if not os.path.isfile(v8path):
|
if not os.path.isfile(v8path):
|
||||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
return v8path
|
return v8path
|
||||||
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: db-update
|
name: db-update
|
||||||
description: Обновление конфигурации базы данных 1С. Используй когда нужно обновить БД, применить конфигурацию, UpdateDBCfg
|
description: Обновление конфигурации базы данных 1С. Используй когда пользователь просит обновить БД, применить конфигурацию, UpdateDBCfg
|
||||||
argument-hint: "[database]"
|
argument-hint: "[database]"
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -28,21 +28,21 @@ allowed-tools:
|
|||||||
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
2. Если указал базу по имени — ищи по id / alias / name в `.v8-project.json`
|
||||||
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
3. Если не указал — сопоставь текущую ветку Git с `databases[].branches`
|
||||||
4. Если ветка не совпала — используй `default`
|
4. Если ветка не совпала — используй `default`
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если файла нет — предложи `/db-list add`.
|
Если файла нет — предложи `/db-list add`.
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/db-update/scripts/db-update.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-update/scripts/db-update.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -66,6 +66,13 @@ python ".opencode/skills/db-update/scripts/db-update.py" <параметры>
|
|||||||
| `-BackgroundSuspend` | Приостановить |
|
| `-BackgroundSuspend` | Приостановить |
|
||||||
| `-BackgroundResume` | Возобновить |
|
| `-BackgroundResume` | Возобновить |
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
## Предупреждения
|
## Предупреждения
|
||||||
|
|
||||||
- Если обновление **не динамическое** — потребуется **монопольный доступ** к базе (все пользователи должны выйти)
|
- Если обновление **не динамическое** — потребуется **монопольный доступ** к базе (все пользователи должны выйти)
|
||||||
@@ -76,11 +83,11 @@ python ".opencode/skills/db-update/scripts/db-update.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Обычное обновление (файловая база)
|
# Обычное обновление (файловая база)
|
||||||
python ".opencode/skills/db-update/scripts/db-update.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin"
|
powershell.exe -NoProfile -File .claude/skills/db-update/scripts/db-update.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin"
|
||||||
|
|
||||||
# Динамическое обновление (серверная база)
|
# Динамическое обновление (серверная база)
|
||||||
python ".opencode/skills/db-update/scripts/db-update.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -Dynamic "+"
|
powershell.exe -NoProfile -File .claude/skills/db-update/scripts/db-update.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -Dynamic "+"
|
||||||
|
|
||||||
# Обновление расширения
|
# Обновление расширения
|
||||||
python ".opencode/skills/db-update/scripts/db-update.py" -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -Extension "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/db-update/scripts/db-update.ps1 -InfoBasePath "C:\Bases\MyDB" -UserName "Admin" -Extension "МоёРасширение"
|
||||||
```
|
```
|
||||||
+6
-94
@@ -1,6 +1,5 @@
|
|||||||
# db-update v1.6 — Update 1C database configuration
|
# db-update v1.0 — Update 1C database configuration
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Обновление конфигурации базы данных 1С
|
Обновление конфигурации базы данных 1С
|
||||||
@@ -90,85 +89,25 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
|
|
||||||
# --- Validate connection ---
|
# --- Validate connection ---
|
||||||
if ($engine -eq "ibcmd") {
|
if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
||||||
if (-not $InfoBasePath) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
} elseif (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|
||||||
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
Write-Host "Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
@@ -178,33 +117,6 @@ $tempDir = Join-Path $env:TEMP "db_update_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch (file infobase only) ---
|
|
||||||
if ($AllExtensions) {
|
|
||||||
Write-Host "Error: ibcmd config apply does not support -AllExtensions (use -Extension)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
$arguments = @("infobase", "config", "apply", "--db-path=$InfoBasePath", "--force")
|
|
||||||
if ($Dynamic -eq "+") { $arguments += "--dynamic=auto" }
|
|
||||||
elseif ($Dynamic -eq "-") { $arguments += "--dynamic=disable" }
|
|
||||||
if ($Extension) { $arguments += "--extension=$Extension" }
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "Database configuration updated successfully" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error updating database configuration (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-update v1.0 — Update 1C database configuration
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
found = sorted(glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe"))
|
||||||
|
if found:
|
||||||
|
return found[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Update 1C database configuration",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="")
|
||||||
|
parser.add_argument("-InfoBasePath", default="")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="")
|
||||||
|
parser.add_argument("-InfoBaseRef", default="")
|
||||||
|
parser.add_argument("-UserName", default="")
|
||||||
|
parser.add_argument("-Password", default="")
|
||||||
|
parser.add_argument("-Extension", default="")
|
||||||
|
parser.add_argument("-AllExtensions", action="store_true")
|
||||||
|
parser.add_argument("-Dynamic", default="", choices=["", "+", "-"])
|
||||||
|
parser.add_argument("-Server", action="store_true")
|
||||||
|
parser.add_argument("-WarningsAsErrors", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: specify -InfoBasePath or -InfoBaseServer + -InfoBaseRef", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"db_update_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments.extend(["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"])
|
||||||
|
else:
|
||||||
|
arguments.extend(["/F", args.InfoBasePath])
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments.append("/UpdateDBCfg")
|
||||||
|
|
||||||
|
# --- Options ---
|
||||||
|
if args.Dynamic:
|
||||||
|
arguments.append(f"-Dynamic{args.Dynamic}")
|
||||||
|
if args.Server:
|
||||||
|
arguments.append("-Server")
|
||||||
|
if args.WarningsAsErrors:
|
||||||
|
arguments.append("-WarningsAsErrors")
|
||||||
|
|
||||||
|
# --- Extensions ---
|
||||||
|
if args.Extension:
|
||||||
|
arguments.extend(["-Extension", args.Extension])
|
||||||
|
elif args.AllExtensions:
|
||||||
|
arguments.append("-AllExtensions")
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "update_log.txt")
|
||||||
|
arguments.extend(["/Out", out_file])
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print("Database configuration updated successfully")
|
||||||
|
else:
|
||||||
|
print(f"Error updating database configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.isdir(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
---
|
||||||
|
name: epf-add-form
|
||||||
|
description: Добавить управляемую форму к внешней обработке 1С
|
||||||
|
argument-hint: <ProcessorName> <FormName> [Synonym]
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Write
|
||||||
|
- Edit
|
||||||
|
- Glob
|
||||||
|
- Grep
|
||||||
|
---
|
||||||
|
|
||||||
|
# /epf-add-form — Добавление формы
|
||||||
|
|
||||||
|
Создаёт управляемую форму и регистрирует её в корневом XML обработки.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```
|
||||||
|
/epf-add-form <ProcessorName> <FormName> [Synonym] [--main]
|
||||||
|
```
|
||||||
|
|
||||||
|
| Параметр | Обязательный | По умолчанию | Описание |
|
||||||
|
|---------------|:------------:|--------------|-------------------------------------------|
|
||||||
|
| ProcessorName | да | — | Имя обработки (должна существовать) |
|
||||||
|
| FormName | да | — | Имя формы |
|
||||||
|
| Synonym | нет | = FormName | Синоним формы |
|
||||||
|
| --main | нет | авто | Установить как форму по умолчанию (автоматически для первой формы) |
|
||||||
|
| SrcDir | нет | `src` | Каталог исходников |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/epf-add-form/scripts/add-form.ps1 -ProcessorName "<ProcessorName>" -FormName "<FormName>" [-Synonym "<Synonym>"] [-Main] [-SrcDir "<SrcDir>"]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<SrcDir>/<ProcessorName>/Forms/
|
||||||
|
├── <FormName>.xml # Метаданные формы (1 UUID)
|
||||||
|
└── <FormName>/
|
||||||
|
└── Ext/
|
||||||
|
├── Form.xml # Описание формы (logform namespace)
|
||||||
|
└── Form/
|
||||||
|
└── Module.bsl # BSL-модуль с 4 регионами
|
||||||
|
```
|
||||||
|
|
||||||
|
## Что модифицируется
|
||||||
|
|
||||||
|
- `<SrcDir>/<ProcessorName>.xml` — добавляется `<Form>` в `ChildObjects`, обновляется `DefaultForm` (автоматически если это первая форма, или явно при `--main`)
|
||||||
|
|
||||||
|
## Детали
|
||||||
|
|
||||||
|
- FormType: Managed
|
||||||
|
- UsePurposes: PlatformApplication, MobilePlatformApplication
|
||||||
|
- AutoCommandBar с id=-1
|
||||||
|
- Реквизит "Объект" с MainAttribute=true
|
||||||
|
- BSL-модуль содержит 5 регионов: ОбработчикиСобытийФормы, ОбработчикиСобытийЭлементовФормы, ОбработчикиКомандФормы, ОбработчикиОповещений, СлужебныеПроцедурыИФункции
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
# epf-add-form v1.0 — Add managed form to 1C processor
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$ProcessorName,
|
||||||
|
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$FormName,
|
||||||
|
|
||||||
|
[string]$Synonym = $FormName,
|
||||||
|
|
||||||
|
[switch]$Main,
|
||||||
|
|
||||||
|
[string]$SrcDir = "src"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
# --- Проверки ---
|
||||||
|
|
||||||
|
$rootXmlPath = Join-Path $SrcDir "$ProcessorName.xml"
|
||||||
|
if (-not (Test-Path $rootXmlPath)) {
|
||||||
|
Write-Error "Корневой файл обработки не найден: $rootXmlPath. Сначала выполните epf-init."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$processorDir = Join-Path $SrcDir $ProcessorName
|
||||||
|
$formsDir = Join-Path $processorDir "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)
|
||||||
|
$encNoBom = New-Object System.Text.UTF8Encoding($false)
|
||||||
|
|
||||||
|
# --- 1. Метаданные формы (Forms/<FormName>.xml) ---
|
||||||
|
|
||||||
|
$formUuid = [guid]::NewGuid().ToString()
|
||||||
|
|
||||||
|
$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="2.17">
|
||||||
|
<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>
|
||||||
|
<ExtendedPresentation/>
|
||||||
|
</Properties>
|
||||||
|
</Form>
|
||||||
|
</MetaDataObject>
|
||||||
|
"@
|
||||||
|
|
||||||
|
[System.IO.File]::WriteAllText($formMetaPath, $formMetaXml, $encBom)
|
||||||
|
|
||||||
|
# --- 2. Описание формы (Forms/<FormName>/Ext/Form.xml) ---
|
||||||
|
|
||||||
|
$formXmlPath = Join-Path $formExtDir "Form.xml"
|
||||||
|
|
||||||
|
$formXml = @"
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Form 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" version="2.17">
|
||||||
|
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||||
|
<Autofill>true</Autofill>
|
||||||
|
</AutoCommandBar>
|
||||||
|
<ChildItems/>
|
||||||
|
<Attributes>
|
||||||
|
<Attribute name="Объект" id="1">
|
||||||
|
<Type>
|
||||||
|
<v8:Type>cfg:ExternalDataProcessorObject.$ProcessorName</v8:Type>
|
||||||
|
</Type>
|
||||||
|
<MainAttribute>true</MainAttribute>
|
||||||
|
</Attribute>
|
||||||
|
</Attributes>
|
||||||
|
</Form>
|
||||||
|
"@
|
||||||
|
|
||||||
|
[System.IO.File]::WriteAllText($formXmlPath, $formXml, $encBom)
|
||||||
|
|
||||||
|
# --- 3. BSL-модуль (Forms/<FormName>/Ext/Form/Module.bsl) ---
|
||||||
|
|
||||||
|
$modulePath = Join-Path $formModuleDir "Module.bsl"
|
||||||
|
|
||||||
|
$moduleBsl = @"
|
||||||
|
#Область ОбработчикиСобытийФормы
|
||||||
|
|
||||||
|
#КонецОбласти
|
||||||
|
|
||||||
|
#Область ОбработчикиСобытийЭлементовФормы
|
||||||
|
|
||||||
|
#КонецОбласти
|
||||||
|
|
||||||
|
#Область ОбработчикиКомандФормы
|
||||||
|
|
||||||
|
#КонецОбласти
|
||||||
|
|
||||||
|
#Область ОбработчикиОповещений
|
||||||
|
|
||||||
|
#КонецОбласти
|
||||||
|
|
||||||
|
#Область СлужебныеПроцедурыИФункции
|
||||||
|
|
||||||
|
#КонецОбласти
|
||||||
|
"@
|
||||||
|
|
||||||
|
[System.IO.File]::WriteAllText($modulePath, $moduleBsl, $encBom)
|
||||||
|
|
||||||
|
# --- 4. Модификация корневого 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")
|
||||||
|
|
||||||
|
$childObjects = $xmlDoc.SelectSingleNode("//md:ChildObjects", $nsMgr)
|
||||||
|
if (-not $childObjects) {
|
||||||
|
Write-Error "Не найден элемент ChildObjects в $rootXmlPath"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Добавить <Form> перед первым <Template>, или в конец
|
||||||
|
$formElem = $xmlDoc.CreateElement("Form", "http://v8.1c.ru/8.3/MDClasses")
|
||||||
|
$formElem.InnerText = $FormName
|
||||||
|
|
||||||
|
$firstTemplate = $childObjects.SelectSingleNode("md:Template", $nsMgr)
|
||||||
|
if ($firstTemplate) {
|
||||||
|
# Вставить перед Template, добавив перенос строки + табуляцию
|
||||||
|
$whitespace = $xmlDoc.CreateWhitespace("`n`t`t`t")
|
||||||
|
$childObjects.InsertBefore($whitespace, $firstTemplate) | Out-Null
|
||||||
|
$childObjects.InsertBefore($formElem, $whitespace) | Out-Null
|
||||||
|
} else {
|
||||||
|
# Добавить в конец ChildObjects
|
||||||
|
# Если 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
|
||||||
|
# Вставить перед закрывающим whitespace (если есть), или в конец
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Обновить DefaultForm: явно при -Main, или автоматически если это первая форма
|
||||||
|
$existingForms = $childObjects.SelectNodes("md:Form", $nsMgr)
|
||||||
|
$isFirstForm = ($existingForms.Count -eq 1)
|
||||||
|
|
||||||
|
if ($Main -or $isFirstForm) {
|
||||||
|
$defaultForm = $xmlDoc.SelectSingleNode("//md:DefaultForm", $nsMgr)
|
||||||
|
if ($defaultForm) {
|
||||||
|
$defaultForm.InnerText = "ExternalDataProcessor.$ProcessorName.Form.$FormName"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Сохранить с BOM
|
||||||
|
$settings = New-Object System.Xml.XmlWriterSettings
|
||||||
|
$settings.Encoding = $encBom
|
||||||
|
$settings.Indent = $false # Preserve original whitespace
|
||||||
|
|
||||||
|
$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"
|
||||||
|
Write-Host " Метаданные: $formMetaPath"
|
||||||
|
Write-Host " Описание: $formXmlPath"
|
||||||
|
Write-Host " Модуль: $modulePath"
|
||||||
|
if ($Main -or $isFirstForm) {
|
||||||
|
Write-Host " DefaultForm обновлён"
|
||||||
|
}
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# add-form v1.0 — Add managed form to 1C external data processor
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from lxml import etree
|
||||||
|
|
||||||
|
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
||||||
|
|
||||||
|
|
||||||
|
def save_xml_with_bom(tree, path):
|
||||||
|
"""Save XML tree to file with UTF-8 BOM."""
|
||||||
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
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 processor", allow_abbrev=False)
|
||||||
|
parser.add_argument("-ProcessorName", required=True)
|
||||||
|
parser.add_argument("-FormName", required=True)
|
||||||
|
parser.add_argument("-Synonym", default=None)
|
||||||
|
parser.add_argument("-Main", action="store_true")
|
||||||
|
parser.add_argument("-SrcDir", default="src")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
processor_name = args.ProcessorName
|
||||||
|
form_name = args.FormName
|
||||||
|
synonym = args.Synonym if args.Synonym is not None else form_name
|
||||||
|
is_main = args.Main
|
||||||
|
src_dir = args.SrcDir
|
||||||
|
|
||||||
|
# --- Checks ---
|
||||||
|
|
||||||
|
root_xml_path = os.path.join(src_dir, f"{processor_name}.xml")
|
||||||
|
if not os.path.exists(root_xml_path):
|
||||||
|
print(f"Корневой файл обработки не найден: {root_xml_path}. Сначала выполните epf-init.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
processor_dir = os.path.join(src_dir, processor_name)
|
||||||
|
forms_dir = os.path.join(processor_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)
|
||||||
|
|
||||||
|
# --- Create directories ---
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
# --- 1. Form metadata (Forms/<FormName>.xml) ---
|
||||||
|
|
||||||
|
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"'
|
||||||
|
' version="2.17">\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'
|
||||||
|
'\t\t</Properties>\n'
|
||||||
|
'\t</Form>\n'
|
||||||
|
'</MetaDataObject>'
|
||||||
|
)
|
||||||
|
|
||||||
|
write_text_with_bom(form_meta_path, form_meta_xml)
|
||||||
|
|
||||||
|
# --- 2. Form description (Forms/<FormName>/Ext/Form.xml) ---
|
||||||
|
|
||||||
|
form_xml_path = os.path.join(form_ext_dir, "Form.xml")
|
||||||
|
|
||||||
|
form_xml = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||||
|
'<Form 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"'
|
||||||
|
' version="2.17">\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="\u041e\u0431\u044a\u0435\u043a\u0442" id="1">\n'
|
||||||
|
'\t\t\t<Type>\n'
|
||||||
|
f'\t\t\t\t<v8:Type>cfg:ExternalDataProcessorObject.{processor_name}</v8:Type>\n'
|
||||||
|
'\t\t\t</Type>\n'
|
||||||
|
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
||||||
|
'\t\t</Attribute>\n'
|
||||||
|
'\t</Attributes>\n'
|
||||||
|
'</Form>'
|
||||||
|
)
|
||||||
|
|
||||||
|
write_text_with_bom(form_xml_path, form_xml)
|
||||||
|
|
||||||
|
# --- 3. BSL module (Forms/<FormName>/Ext/Form/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'
|
||||||
|
)
|
||||||
|
|
||||||
|
write_text_with_bom(module_path, module_bsl)
|
||||||
|
|
||||||
|
# --- 4. 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()
|
||||||
|
|
||||||
|
ns = "http://v8.1c.ru/8.3/MDClasses"
|
||||||
|
child_objects = root.find(".//md:ChildObjects", NSMAP)
|
||||||
|
if child_objects is None:
|
||||||
|
print(f"Не найден элемент ChildObjects в {root_xml_path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Add <Form> before first <Template>, or at end
|
||||||
|
form_elem = etree.Element(f"{{{ns}}}Form")
|
||||||
|
form_elem.text = form_name
|
||||||
|
|
||||||
|
first_template = child_objects.find("md:Template", NSMAP)
|
||||||
|
if first_template is not None:
|
||||||
|
# Insert before Template, adding newline + indent
|
||||||
|
idx = list(child_objects).index(first_template)
|
||||||
|
child_objects.insert(idx, form_elem)
|
||||||
|
# Set whitespace: form_elem gets same tail pattern
|
||||||
|
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"
|
||||||
|
|
||||||
|
# Update DefaultForm: explicitly with -Main, or automatically if this is the first form
|
||||||
|
existing_forms = child_objects.findall("md:Form", NSMAP)
|
||||||
|
is_first_form = len(existing_forms) == 1
|
||||||
|
|
||||||
|
if is_main or is_first_form:
|
||||||
|
default_form = root.find(".//md:DefaultForm", NSMAP)
|
||||||
|
if default_form is not None:
|
||||||
|
default_form.text = f"ExternalDataProcessor.{processor_name}.Form.{form_name}"
|
||||||
|
|
||||||
|
# Save with BOM
|
||||||
|
save_xml_with_bom(tree, root_xml_full)
|
||||||
|
|
||||||
|
print(f"[OK] Создана форма: {form_name}")
|
||||||
|
print(f" Метаданные: {form_meta_path}")
|
||||||
|
print(f" Описание: {form_xml_path}")
|
||||||
|
print(f" Модуль: {module_path}")
|
||||||
|
if is_main or is_first_form:
|
||||||
|
print(" DefaultForm обновлён")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+3
-2
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: epf-bsp-add-command
|
name: epf-bsp-add-command
|
||||||
description: Определить команду в БСП‑описании обработки (`СведенияОВнешнейОбработке`) — открытие формы, вызов клиентского/серверного метода, заполнение объекта и т.п. Используй когда нужно зарегистрировать команду в дополнительной обработке БСП
|
description: Добавить команду в дополнительную обработку БСП
|
||||||
argument-hint: <ProcessorName> <Идентификатор> [ТипКоманды] [Представление]
|
argument-hint: <ProcessorName> <Идентификатор> [ТипКоманды] [Представление]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Read
|
- Read
|
||||||
@@ -191,6 +191,7 @@ allowed-tools:
|
|||||||
НоваяКоманда.Идентификатор = "ЗаказПокупателя";
|
НоваяКоманда.Идентификатор = "ЗаказПокупателя";
|
||||||
НоваяКоманда.Использование = ДополнительныеОтчетыИОбработкиКлиентСервер.ТипКомандыВызовСерверногоМетода();
|
НоваяКоманда.Использование = ДополнительныеОтчетыИОбработкиКлиентСервер.ТипКомандыВызовСерверногоМетода();
|
||||||
НоваяКоманда.ПоказыватьОповещение = Ложь;
|
НоваяКоманда.ПоказыватьОповещение = Ложь;
|
||||||
|
НоваяКоманда.Модификатор = "ПечатьMXL";
|
||||||
```
|
```
|
||||||
|
|
||||||
И в существующую процедуру `ВыполнитьКоманду` добавится блок обработки.
|
И в существующую процедуру `Печать` добавится блок обработки.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: epf-bsp-init
|
name: epf-bsp-init
|
||||||
description: Сформировать функцию `СведенияОВнешнейОбработке` в модуле объекта обработки — описание для подключения через подсистему БСП «Дополнительные отчёты и обработки». Используй когда нужно сделать обработку совместимой с БСП, подключаемой через «Дополнительные отчёты и обработки»
|
description: Добавить функцию регистрации БСП (СведенияОВнешнейОбработке) в модуль объекта обработки
|
||||||
argument-hint: <ProcessorName> <Вид>
|
argument-hint: <ProcessorName> <Вид>
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Read
|
- Read
|
||||||
@@ -203,6 +203,6 @@ allowed-tools:
|
|||||||
## Дальнейшие шаги
|
## Дальнейшие шаги
|
||||||
|
|
||||||
- Добавить ещё команду: `/epf-bsp-add-command`
|
- Добавить ещё команду: `/epf-bsp-add-command`
|
||||||
- Добавить форму: `/form-add`
|
- Добавить форму: `/epf-add-form`
|
||||||
- Добавить макет: `/template-add`
|
- Добавить макет: `/template-add`
|
||||||
- Собрать EPF: `/epf-build`
|
- Собрать EPF: `/epf-build`
|
||||||
@@ -34,20 +34,20 @@ allowed-tools:
|
|||||||
5. Если ветка не совпала — используй `default`
|
5. Если ветка не совпала — используй `default`
|
||||||
6. Если `.v8-project.json` нет или база не найдена — не указывай параметры подключения: скрипт автоматически создаст временную базу. Для EPF со ссылочными типами (CatalogRef, DocumentRef и т.д.) генерируются заглушки метаданных. Временная база удаляется после сборки.
|
6. Если `.v8-project.json` нет или база не найдена — не указывай параметры подключения: скрипт автоматически создаст временную базу. Для EPF со ссылочными типами (CatalogRef, DocumentRef и т.д.) генерируются заглушки метаданных. Временная база удаляется после сборки.
|
||||||
|
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -62,8 +62,8 @@ python ".opencode/skills/epf-build/scripts/epf-build.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Сборка обработки (файловая база)
|
# Сборка обработки (файловая база)
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" -InfoBasePath "C:\Bases\MyDB" -SourceFile "src/МояОбработка.xml" -OutputFile "build/МояОбработка.epf"
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 -InfoBasePath "C:\Bases\MyDB" -SourceFile "src/МояОбработка.xml" -OutputFile "build/МояОбработка.epf"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -SourceFile "src/МояОбработка.xml" -OutputFile "build/МояОбработка.epf"
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -SourceFile "src/МояОбработка.xml" -OutputFile "build/МояОбработка.epf"
|
||||||
```
|
```
|
||||||
+5
-86
@@ -1,6 +1,5 @@
|
|||||||
# epf-build v1.6 — Build external data processor or report (EPF/ERF) from XML sources
|
# epf-build v1.0 — Build external data processor or report (EPF/ERF) from XML sources
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Сборка внешней обработки/отчёта 1С из XML-исходников
|
Сборка внешней обработки/отчёта 1С из XML-исходников
|
||||||
@@ -71,79 +70,20 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$engine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
if ($engine -eq "ibcmd" -and $InfoBaseServer -and $InfoBaseRef) {
|
|
||||||
Write-Host "Error: ibcmd supports file infobases only (use -InfoBasePath or omit for stub)" -ForegroundColor Red
|
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,27 +121,6 @@ $tempDir = Join-Path $env:TEMP "epf_build_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch: build EPF/ERF via config import --out ---
|
|
||||||
$srcDir = Split-Path $SourceFile -Parent
|
|
||||||
$arguments = @("infobase", "config", "import", "$srcDir", "--out=$OutputFile", "--db-path=$InfoBasePath")
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "External data processor/report built successfully: $OutputFile" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error building external data processor/report (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
+11
-105
@@ -1,104 +1,37 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# epf-build v1.6 — Build external data processor or report (EPF/ERF) from XML sources
|
# epf-build v1.0 — Build external data processor or report (EPF/ERF) from XML sources
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import atexit
|
|
||||||
import glob
|
import glob
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import random
|
import random
|
||||||
import re
|
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
def _find_project_v8path():
|
|
||||||
"""Walk up from CWD to find .v8-project.json and read its v8path."""
|
|
||||||
d = os.getcwd()
|
|
||||||
while True:
|
|
||||||
pf = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pf):
|
|
||||||
try:
|
|
||||||
with open(pf, encoding="utf-8-sig") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
v = data.get("v8path")
|
|
||||||
if v:
|
|
||||||
return v
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return None
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
return None
|
|
||||||
d = parent
|
|
||||||
|
|
||||||
|
|
||||||
def _version_dir(p):
|
|
||||||
"""Version dir for both Windows (.../1cv8/<ver>/bin/1cv8.exe) and *nix (.../1cv8/<ver>/1cv8)."""
|
|
||||||
parent = os.path.dirname(p)
|
|
||||||
if os.path.basename(parent).lower() == "bin":
|
|
||||||
parent = os.path.dirname(parent)
|
|
||||||
return os.path.basename(parent)
|
|
||||||
|
|
||||||
|
|
||||||
def _version_key(p):
|
|
||||||
"""Numeric sort key from version dir name."""
|
|
||||||
return [int(x) for x in re.findall(r"\d+", _version_dir(p))]
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_v8path(v8path):
|
def resolve_v8path(v8path):
|
||||||
"""Resolve path to a 1C executable (1cv8; ibcmd only when given explicitly)."""
|
"""Resolve path to 1cv8.exe."""
|
||||||
if not v8path:
|
if not v8path:
|
||||||
v8path = _find_project_v8path()
|
candidates = glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
||||||
if not v8path:
|
|
||||||
if os.name == "nt":
|
|
||||||
candidates = (
|
|
||||||
glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
|
||||||
+ glob.glob(r"C:\Program Files (x86)\1cv8\*\bin\1cv8.exe")
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
# PY-only: PS-порт на *nix не исполняется, поэтому *nix-раскладки нет в .ps1.
|
|
||||||
candidates = glob.glob("/opt/1cv8/*/1cv8")
|
|
||||||
if candidates:
|
if candidates:
|
||||||
v8path = max(candidates, key=_version_key)
|
candidates.sort()
|
||||||
print(f"Auto-selected platform {_version_dir(v8path)}: {v8path}")
|
return candidates[-1]
|
||||||
else:
|
else:
|
||||||
print("Error: 1C executable not found. Specify -V8Path", file=sys.stderr)
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
if os.path.isdir(v8path):
|
elif os.path.isdir(v8path):
|
||||||
# PY-only: на *nix исполняемый называется "1cv8" (без .exe); ibcmd — только явным путём.
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
exe = "1cv8.exe" if os.name == "nt" else "1cv8"
|
|
||||||
v8path = os.path.join(v8path, exe)
|
|
||||||
if not os.path.isfile(v8path):
|
if not os.path.isfile(v8path):
|
||||||
print(f"Error: 1C executable not found at {v8path}", file=sys.stderr)
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
return v8path
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
IBCMD_NOUSER_HINT = (
|
|
||||||
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
|
|
||||||
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
|
|
||||||
"call may block instead of failing. If it does not return promptly, abort and "
|
|
||||||
"re-run with -UserName and -Password.\n"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
|
||||||
"""Run an ibcmd command non-interactively.
|
|
||||||
|
|
||||||
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
|
|
||||||
On Windows without -UserName ibcmd reads the console directly and may still block —
|
|
||||||
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.stderr.flush()
|
|
||||||
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
sys.stdout.reconfigure(encoding="utf-8")
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
sys.stderr.reconfigure(encoding="utf-8")
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
@@ -118,10 +51,6 @@ def main():
|
|||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
v8path = resolve_v8path(args.V8Path)
|
v8path = resolve_v8path(args.V8Path)
|
||||||
engine = "ibcmd" if os.path.basename(v8path).lower().startswith("ibcmd") else "1cv8"
|
|
||||||
if engine == "ibcmd" and args.InfoBaseServer and args.InfoBaseRef:
|
|
||||||
print("Error: ibcmd supports file infobases only (use -InfoBasePath or omit for stub)", file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# --- Auto-create stub database if no connection specified ---
|
# --- Auto-create stub database if no connection specified ---
|
||||||
auto_created_base = None
|
auto_created_base = None
|
||||||
@@ -155,29 +84,6 @@ def main():
|
|||||||
os.makedirs(temp_dir, exist_ok=True)
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if engine == "ibcmd":
|
|
||||||
# --- ibcmd branch: build EPF/ERF via config import --out ---
|
|
||||||
src_dir = os.path.dirname(os.path.abspath(args.SourceFile))
|
|
||||||
arguments = ["infobase", "config", "import", src_dir, f"--out={args.OutputFile}", f"--db-path={args.InfoBasePath}"]
|
|
||||||
ib_data = tempfile.mkdtemp(prefix="ibcmd_data_")
|
|
||||||
atexit.register(shutil.rmtree, ib_data, ignore_errors=True)
|
|
||||||
if args.UserName:
|
|
||||||
arguments.append(f"--user={args.UserName}")
|
|
||||||
if args.Password:
|
|
||||||
arguments.append(f"--password={args.Password}")
|
|
||||||
arguments.append(f"--data={ib_data}")
|
|
||||||
print(f"Running: ibcmd {' '.join(arguments)}")
|
|
||||||
result = run_ibcmd([v8path] + arguments, warn_no_user=False)
|
|
||||||
if result.returncode == 0:
|
|
||||||
print(f"External data processor/report built successfully: {args.OutputFile}")
|
|
||||||
else:
|
|
||||||
print(f"Error building external data processor/report (code: {result.returncode})", file=sys.stderr)
|
|
||||||
if result.stdout:
|
|
||||||
print(result.stdout)
|
|
||||||
if result.stderr:
|
|
||||||
print(result.stderr, file=sys.stderr)
|
|
||||||
sys.exit(result.returncode)
|
|
||||||
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
arguments = ["DESIGNER"]
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
+1
-52
@@ -1,4 +1,4 @@
|
|||||||
# stub-db-create v1.3 — Create temp 1C infobase with metadata stubs for EPF/ERF build
|
# stub-db-create v1.0 — Create temp 1C infobase with metadata stubs for EPF/ERF build
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -1252,57 +1252,6 @@ $propsXml </Properties>$childObjLine
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 5a. Stub via ibcmd (one call: create [--import --apply]) ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$stubEngine = if ((Split-Path $V8Path -Leaf) -match '^ibcmd') { "ibcmd" } else { "1cv8" }
|
|
||||||
if ($stubEngine -eq "ibcmd") {
|
|
||||||
Write-Host "Creating infobase (ibcmd): $TempBasePath"
|
|
||||||
$ibData = Join-Path $env:TEMP "stub_data_$(Get-Random)"
|
|
||||||
New-Item -ItemType Directory -Path $ibData -Force | Out-Null
|
|
||||||
$ibArgs = @("infobase", "create", "--db-path=$TempBasePath", "--create-database")
|
|
||||||
if ($hasRefTypes) { $ibArgs += "--import=$(Join-Path $TempBasePath 'cfg')", "--apply", "--force" }
|
|
||||||
$ibArgs += "--data=$ibData"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $ibArgs
|
|
||||||
$ibOut = $__ib.Output
|
|
||||||
$ibRc = $__ib.ExitCode
|
|
||||||
Remove-Item -Path $ibData -Recurse -Force -ErrorAction SilentlyContinue
|
|
||||||
if ($ibRc -ne 0) {
|
|
||||||
if ($ibOut) { Write-Host ($ibOut | Out-String) }
|
|
||||||
Write-Error "Failed to create stub infobase (code: $ibRc)"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
if ($hasRefTypes) { Remove-Item -Path (Join-Path $TempBasePath "cfg") -Recurse -Force -ErrorAction SilentlyContinue }
|
|
||||||
Write-Host "[OK] Stub database created: $TempBasePath"
|
|
||||||
Write-Host $TempBasePath
|
|
||||||
exit 0
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 5. Create infobase ---
|
# --- 5. Create infobase ---
|
||||||
Write-Host "Creating infobase: $TempBasePath"
|
Write-Host "Creating infobase: $TempBasePath"
|
||||||
$createArgs = "CREATEINFOBASE File=`"$TempBasePath`" /DisableStartupDialogs"
|
$createArgs = "CREATEINFOBASE File=`"$TempBasePath`" /DisableStartupDialogs"
|
||||||
+1
-48
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# stub-db-create v1.3 — Create temp 1C infobase with metadata stubs for EPF/ERF build
|
# stub-db-create v1.0 — Create temp 1C infobase with metadata stubs for EPF/ERF build
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -12,27 +12,6 @@ import tempfile
|
|||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
IBCMD_NOUSER_HINT = (
|
|
||||||
"[ibcmd] No -UserName/-Password given; the infobase may require authentication. "
|
|
||||||
"On Windows ibcmd reads credentials from the console (stdin is ignored), so this "
|
|
||||||
"call may block instead of failing. If it does not return promptly, abort and "
|
|
||||||
"re-run with -UserName and -Password.\n"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run_ibcmd(cmd, has_username=False, warn_no_user=True):
|
|
||||||
"""Run an ibcmd command non-interactively.
|
|
||||||
|
|
||||||
input="" closes stdin (EOF) so ibcmd's auth prompt fast-fails instead of hanging.
|
|
||||||
On Windows without -UserName ibcmd reads the console directly and may still block —
|
|
||||||
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.stderr.flush()
|
|
||||||
return subprocess.run(cmd, input="", capture_output=True, encoding="utf-8", errors="replace")
|
|
||||||
|
|
||||||
|
|
||||||
def new_uuid():
|
def new_uuid():
|
||||||
return str(uuid.uuid4())
|
return str(uuid.uuid4())
|
||||||
|
|
||||||
@@ -1055,32 +1034,6 @@ def main():
|
|||||||
if register_columns:
|
if register_columns:
|
||||||
print('WARNING: Register column categories (Dimension/Resource/Attribute) are guessed. Form field bindings may not survive round-trip through a real database.')
|
print('WARNING: Register column categories (Dimension/Resource/Attribute) are guessed. Form field bindings may not survive round-trip through a real database.')
|
||||||
|
|
||||||
# Stub via ibcmd (one call: create [--import --apply])
|
|
||||||
stub_engine = "ibcmd" if os.path.basename(args.V8Path).lower().startswith("ibcmd") else "1cv8"
|
|
||||||
if stub_engine == "ibcmd":
|
|
||||||
import shutil
|
|
||||||
print(f'Creating infobase (ibcmd): {temp_base}')
|
|
||||||
ib_data = tempfile.mkdtemp(prefix="stub_data_")
|
|
||||||
ib_args = [args.V8Path, 'infobase', 'create', f'--db-path={temp_base}', '--create-database']
|
|
||||||
if has_ref_types:
|
|
||||||
ib_args += [f'--import={os.path.join(temp_base, "cfg")}', '--apply', '--force']
|
|
||||||
ib_args.append(f'--data={ib_data}')
|
|
||||||
result = run_ibcmd(ib_args, warn_no_user=False)
|
|
||||||
shutil.rmtree(ib_data, ignore_errors=True)
|
|
||||||
if result.returncode != 0:
|
|
||||||
if result.stdout:
|
|
||||||
print(result.stdout)
|
|
||||||
if result.stderr:
|
|
||||||
print(result.stderr, file=sys.stderr)
|
|
||||||
print(f'Failed to create stub infobase (code: {result.returncode})', file=sys.stderr)
|
|
||||||
sys.exit(1)
|
|
||||||
if has_ref_types:
|
|
||||||
import shutil
|
|
||||||
shutil.rmtree(os.path.join(temp_base, 'cfg'), ignore_errors=True)
|
|
||||||
print(f'[OK] Stub database created: {temp_base}')
|
|
||||||
print(temp_base)
|
|
||||||
sys.exit(0)
|
|
||||||
|
|
||||||
# Create infobase
|
# Create infobase
|
||||||
print(f'Creating infobase: {temp_base}')
|
print(f'Creating infobase: {temp_base}')
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
@@ -33,20 +33,20 @@ allowed-tools:
|
|||||||
5. Если ветка не совпала — используй `default`
|
5. Если ветка не совпала — используй `default`
|
||||||
6. Если `.v8-project.json` нет или база не найдена — **сообщи пользователю об ошибке**. Для dump база обязательна: в пустой базе ссылочные типы (CatalogRef, DocumentRef и т.д.) безвозвратно сбрасываются в строки. Предложи указать базу или зарегистрировать через `/db-list add`.
|
6. Если `.v8-project.json` нет или база не найдена — **сообщи пользователю об ошибке**. Для dump база обязательна: в пустой базе ссылочные типы (CatalogRef, DocumentRef и т.д.) безвозвратно сбрасываются в строки. Предложи указать базу или зарегистрировать через `/db-list add`.
|
||||||
|
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|----------|:------------:|----------|
|
|----------|:------------:|----------|
|
||||||
| `-V8Path <путь>` | нет | Каталог bin платформы, или полный путь к `1cv8.exe` / `ibcmd.exe` |
|
| `-V8Path <путь>` | нет | Каталог bin платформы (или полный путь к 1cv8.exe) |
|
||||||
| `-InfoBasePath <путь>` | * | Файловая база |
|
| `-InfoBasePath <путь>` | * | Файловая база |
|
||||||
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
| `-InfoBaseServer <сервер>` | * | Сервер 1С (для серверной базы) |
|
||||||
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
| `-InfoBaseRef <имя>` | * | Имя базы на сервере |
|
||||||
@@ -62,8 +62,8 @@ python ".opencode/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Разборка обработки (файловая база)
|
# Разборка обработки (файловая база)
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" -InfoBasePath "C:\Bases\MyDB" -InputFile "build/МояОбработка.epf" -OutputDir "src"
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 -InfoBasePath "C:\Bases\MyDB" -InputFile "build/МояОбработка.epf" -OutputDir "src"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -InputFile "build/МояОбработка.epf" -OutputDir "src"
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -InputFile "build/МояОбработка.epf" -OutputDir "src"
|
||||||
```
|
```
|
||||||
+5
-91
@@ -1,6 +1,5 @@
|
|||||||
# epf-dump v1.6 — Dump external data processor or report (EPF/ERF) to XML sources
|
# epf-dump v1.0 — Dump external data processor or report (EPF/ERF) to XML sources
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# NB: *nix-раскладку платформы (/opt/1cv8/<ver>/1cv8, без .exe) знает только .py-порт — PS на *nix не исполняется.
|
|
||||||
<#
|
<#
|
||||||
.SYNOPSIS
|
.SYNOPSIS
|
||||||
Разборка внешней обработки/отчёта 1С в XML-исходники
|
Разборка внешней обработки/отчёта 1С в XML-исходники
|
||||||
@@ -78,45 +77,20 @@ $OutputEncoding = [System.Text.Encoding]::UTF8
|
|||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve V8Path ---
|
# --- Resolve V8Path ---
|
||||||
function Find-ProjectV8Path {
|
|
||||||
$dir = (Get-Location).Path
|
|
||||||
while ($dir) {
|
|
||||||
$pf = Join-Path $dir ".v8-project.json"
|
|
||||||
if (Test-Path $pf) {
|
|
||||||
try {
|
|
||||||
$j = Get-Content $pf -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
||||||
if ($j.v8path) { return [string]$j.v8path }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
$parent = Split-Path $dir -Parent
|
|
||||||
if (-not $parent -or $parent -eq $dir) { break }
|
|
||||||
$dir = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $V8Path) {
|
if (-not $V8Path) {
|
||||||
$V8Path = Find-ProjectV8Path
|
$found = Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" -ErrorAction SilentlyContinue | Sort-Object FullName -Descending | Select-Object -First 1
|
||||||
}
|
|
||||||
if (-not $V8Path) {
|
|
||||||
$found = Get-ChildItem @("C:\Program Files\1cv8\*\bin\1cv8.exe", "C:\Program Files (x86)\1cv8\*\bin\1cv8.exe") -ErrorAction SilentlyContinue |
|
|
||||||
Sort-Object { try { [version]$_.Directory.Parent.Name } catch { [version]"0.0" } } -Descending |
|
|
||||||
Select-Object -First 1
|
|
||||||
if ($found) {
|
if ($found) {
|
||||||
$V8Path = $found.FullName
|
$V8Path = $found.FullName
|
||||||
Write-Host "Auto-selected platform $($found.Directory.Parent.Name): $V8Path" -ForegroundColor Yellow
|
|
||||||
} else {
|
} else {
|
||||||
Write-Host "Error: 1C executable not found. Specify -V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found. Specify -V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
}
|
} elseif (Test-Path $V8Path -PathType Container) {
|
||||||
if (Test-Path $V8Path -PathType Container) {
|
|
||||||
$V8Path = Join-Path $V8Path "1cv8.exe"
|
$V8Path = Join-Path $V8Path "1cv8.exe"
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not (Test-Path $V8Path)) {
|
if (-not (Test-Path $V8Path)) {
|
||||||
Write-Host "Error: 1C executable not found at $V8Path" -ForegroundColor Red
|
Write-Host "Error: 1cv8.exe not found at $V8Path" -ForegroundColor Red
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,46 +101,6 @@ if (-not $InfoBasePath -and (-not $InfoBaseServer -or -not $InfoBaseRef)) {
|
|||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Detect engine (ibcmd vs 1cv8) by exe name ---
|
|
||||||
function Invoke-IbcmdProcess {
|
|
||||||
# Run ibcmd non-interactively: a closed stdin pipe (EOF) makes ibcmd's auth prompt
|
|
||||||
# fast-fail instead of hanging. Returns @{ Output; ExitCode }. cp866 decodes ibcmd's
|
|
||||||
# native OEM output. The 1cv8/DESIGNER branch keeps using Start-Process.
|
|
||||||
param([string]$Exe, [string[]]$IbArgs)
|
|
||||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
|
||||||
$psi.FileName = $Exe
|
|
||||||
$psi.Arguments = ($IbArgs | ForEach-Object { if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ } }) -join ' '
|
|
||||||
$psi.UseShellExecute = $false
|
|
||||||
$psi.CreateNoWindow = $true
|
|
||||||
$psi.RedirectStandardInput = $true
|
|
||||||
$psi.RedirectStandardOutput = $true
|
|
||||||
$psi.RedirectStandardError = $true
|
|
||||||
try {
|
|
||||||
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
$psi.StandardErrorEncoding = [System.Text.Encoding]::GetEncoding(866)
|
|
||||||
} catch {}
|
|
||||||
$p = [System.Diagnostics.Process]::Start($psi)
|
|
||||||
$p.StandardInput.Close()
|
|
||||||
$out = $p.StandardOutput.ReadToEnd()
|
|
||||||
$err = $p.StandardError.ReadToEnd()
|
|
||||||
$p.WaitForExit()
|
|
||||||
if ($err) { $out += $err }
|
|
||||||
return [pscustomobject]@{ Output = $out; ExitCode = $p.ExitCode }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
$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
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
if ($Format -eq "Plain") {
|
|
||||||
Write-Host "Error: ibcmd config export supports hierarchical format only (use -Format Hierarchical or 1cv8)" -ForegroundColor Red
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Validate input file ---
|
# --- Validate input file ---
|
||||||
if (-not (Test-Path $InputFile)) {
|
if (-not (Test-Path $InputFile)) {
|
||||||
Write-Host "Error: input file not found: $InputFile" -ForegroundColor Red
|
Write-Host "Error: input file not found: $InputFile" -ForegroundColor Red
|
||||||
@@ -183,26 +117,6 @@ $tempDir = Join-Path $env:TEMP "epf_dump_$(Get-Random)"
|
|||||||
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
New-Item -ItemType Directory -Path $tempDir -Force | Out-Null
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if ($engine -eq "ibcmd") {
|
|
||||||
# --- ibcmd branch: dump EPF/ERF via config export --file ---
|
|
||||||
$arguments = @("infobase", "config", "export", "--file=$InputFile", "$OutputDir", "--db-path=$InfoBasePath")
|
|
||||||
if ($UserName) { $arguments += "--user=$UserName" }
|
|
||||||
if ($Password) { $arguments += "--password=$Password" }
|
|
||||||
$arguments += "--data=$tempDir"
|
|
||||||
Write-Host "Running: ibcmd $($arguments -join ' ')"
|
|
||||||
$__ib = Invoke-IbcmdProcess $V8Path $arguments
|
|
||||||
$output = $__ib.Output
|
|
||||||
$exitCode = $__ib.ExitCode
|
|
||||||
if ($exitCode -eq 0) {
|
|
||||||
Write-Host "External data processor/report dumped successfully to: $OutputDir" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host "Error dumping external data processor/report (code: $exitCode)" -ForegroundColor Red
|
|
||||||
}
|
|
||||||
if ($output) { Write-Host ($output | Out-String) }
|
|
||||||
exit $exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 1cv8 branch ---
|
|
||||||
# --- Build arguments ---
|
# --- Build arguments ---
|
||||||
$arguments = @("DESIGNER")
|
$arguments = @("DESIGNER")
|
||||||
|
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# epf-dump v1.0 — Dump external data processor or report (EPF/ERF) to XML sources
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_v8path(v8path):
|
||||||
|
"""Resolve path to 1cv8.exe."""
|
||||||
|
if not v8path:
|
||||||
|
candidates = glob.glob(r"C:\Program Files\1cv8\*\bin\1cv8.exe")
|
||||||
|
if candidates:
|
||||||
|
candidates.sort()
|
||||||
|
return candidates[-1]
|
||||||
|
else:
|
||||||
|
print("Error: 1cv8.exe not found. Specify -V8Path", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
elif os.path.isdir(v8path):
|
||||||
|
v8path = os.path.join(v8path, "1cv8.exe")
|
||||||
|
|
||||||
|
if not os.path.isfile(v8path):
|
||||||
|
print(f"Error: 1cv8.exe not found at {v8path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
return v8path
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Dump external data processor or report (EPF/ERF) to XML sources",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-V8Path", default="", help="Path to 1cv8.exe or its bin directory")
|
||||||
|
parser.add_argument("-InfoBasePath", default="", help="Path to file infobase")
|
||||||
|
parser.add_argument("-InfoBaseServer", default="", help="1C server (for server infobase)")
|
||||||
|
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("-InputFile", required=True, help="Path to EPF/ERF file")
|
||||||
|
parser.add_argument("-OutputDir", required=True, help="Directory for dumped XML sources")
|
||||||
|
parser.add_argument(
|
||||||
|
"-Format",
|
||||||
|
default="Hierarchical",
|
||||||
|
choices=["Hierarchical", "Plain"],
|
||||||
|
help="Dump format (default: Hierarchical)",
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# --- Resolve V8Path ---
|
||||||
|
v8path = resolve_v8path(args.V8Path)
|
||||||
|
|
||||||
|
# --- Validate database connection ---
|
||||||
|
if not args.InfoBasePath and (not args.InfoBaseServer or not args.InfoBaseRef):
|
||||||
|
print("Error: database connection required. Specify -InfoBasePath or -InfoBaseServer/-InfoBaseRef", file=sys.stderr)
|
||||||
|
print("Dump in an empty database loses reference types (CatalogRef, DocumentRef, etc.) irreversibly.")
|
||||||
|
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)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Ensure output directory exists ---
|
||||||
|
if not os.path.exists(args.OutputDir):
|
||||||
|
os.makedirs(args.OutputDir, exist_ok=True)
|
||||||
|
|
||||||
|
# --- Temp dir ---
|
||||||
|
temp_dir = os.path.join(tempfile.gettempdir(), f"epf_dump_{random.randint(0, 999999)}")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# --- Build arguments ---
|
||||||
|
arguments = ["DESIGNER"]
|
||||||
|
|
||||||
|
if args.InfoBaseServer and args.InfoBaseRef:
|
||||||
|
arguments += ["/S", f"{args.InfoBaseServer}/{args.InfoBaseRef}"]
|
||||||
|
else:
|
||||||
|
arguments += ["/F", args.InfoBasePath]
|
||||||
|
|
||||||
|
if args.UserName:
|
||||||
|
arguments.append(f"/N{args.UserName}")
|
||||||
|
if args.Password:
|
||||||
|
arguments.append(f"/P{args.Password}")
|
||||||
|
|
||||||
|
arguments += ["/DumpExternalDataProcessorOrReportToFiles", args.OutputDir, args.InputFile]
|
||||||
|
arguments += ["-Format", args.Format]
|
||||||
|
|
||||||
|
# --- Output ---
|
||||||
|
out_file = os.path.join(temp_dir, "dump_log.txt")
|
||||||
|
arguments += ["/Out", out_file]
|
||||||
|
arguments.append("/DisableStartupDialogs")
|
||||||
|
|
||||||
|
# --- Execute ---
|
||||||
|
print(f"Running: 1cv8.exe {' '.join(arguments)}")
|
||||||
|
result = subprocess.run(
|
||||||
|
[v8path] + arguments,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
exit_code = result.returncode
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
if exit_code == 0:
|
||||||
|
print(f"Dump completed successfully to: {args.OutputDir}")
|
||||||
|
else:
|
||||||
|
print(f"Error dumping (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: epf-init
|
name: epf-init
|
||||||
description: Создать пустую внешнюю обработку 1С (scaffold XML-исходников). Используй когда нужно создать новую внешнюю обработку с нуля
|
description: Создать пустую внешнюю обработку 1С (scaffold XML-исходников)
|
||||||
argument-hint: <Name> [Synonym]
|
argument-hint: <Name> [Synonym]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -30,12 +30,26 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/epf-init/scripts/init.py" -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"]
|
powershell.exe -NoProfile -File .claude/skills/epf-init/scripts/init.ps1 -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<SrcDir>/
|
||||||
|
├── <Name>.xml # Корневой файл метаданных (4 UUID)
|
||||||
|
└── <Name>/
|
||||||
|
└── Ext/
|
||||||
|
└── ObjectModule.bsl # Модуль объекта с 3 регионами
|
||||||
|
```
|
||||||
|
|
||||||
|
- Корневой XML содержит `MetaDataObject/ExternalDataProcessor` с пустыми `DefaultForm` и `ChildObjects`
|
||||||
|
- ClassId фиксирован: `c3831ec8-d8d5-4f93-8a22-f9bfae07327f`
|
||||||
|
- Файл создаётся в UTF-8 с BOM
|
||||||
|
|
||||||
## Дальнейшие шаги
|
## Дальнейшие шаги
|
||||||
|
|
||||||
- Добавить форму: `/form-add`
|
- Добавить форму: `/epf-add-form`
|
||||||
- Добавить макет: `/template-add`
|
- Добавить макет: `/template-add`
|
||||||
- Добавить справку: `/help-add`
|
- Добавить справку: `/help-add`
|
||||||
- Собрать EPF: `/epf-build`
|
- Собрать EPF: `/epf-build`
|
||||||
+1
-3
@@ -1,4 +1,4 @@
|
|||||||
# epf-init v1.1 — Init 1C external data processor scaffold
|
# epf-init v1.0 — Init 1C external data processor scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -10,8 +10,6 @@ param(
|
|||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
|
|
||||||
$uuid1 = [guid]::NewGuid().ToString()
|
$uuid1 = [guid]::NewGuid().ToString()
|
||||||
$uuid2 = [guid]::NewGuid().ToString()
|
$uuid2 = [guid]::NewGuid().ToString()
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# epf-init v1.1 — Init 1C external data processor scaffold
|
# epf-init v1.0 — Init 1C external data processor scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Generates minimal XML source files for a 1C external data processor."""
|
"""Generates minimal XML source files for a 1C external data processor."""
|
||||||
import sys, os, argparse, uuid
|
import sys, os, argparse, uuid
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
name: epf-validate
|
||||||
|
description: Валидация внешней обработки 1С (EPF). Используй после создания или модификации обработки для проверки корректности
|
||||||
|
argument-hint: <ObjectPath> [-Detailed] [-MaxErrors 30]
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Glob
|
||||||
|
---
|
||||||
|
|
||||||
|
# /epf-validate — валидация внешней обработки (EPF)
|
||||||
|
|
||||||
|
Проверяет структурную корректность XML-исходников внешней обработки: корневую структуру, InternalInfo, свойства, ChildObjects, реквизиты, табличные части, уникальность имён, наличие файлов форм и макетов. Также работает для внешних отчётов (ERF).
|
||||||
|
|
||||||
|
## Параметры
|
||||||
|
|
||||||
|
| Параметр | Обяз. | Умолч. | Описание |
|
||||||
|
|------------|:-----:|---------|-------------------------------------------------|
|
||||||
|
| ObjectPath | да | — | Путь к корневому XML или каталогу обработки |
|
||||||
|
| Detailed | нет | — | Показывать [OK] для каждой проверки |
|
||||||
|
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||||
|
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МояОбработка"
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МояОбработка/МояОбработка.xml"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
| # | Проверка | Серьёзность |
|
||||||
|
|----|-------------------------------------------------------|--------------|
|
||||||
|
| 1 | Root structure: MetaDataObject/ExternalDataProcessor | ERROR |
|
||||||
|
| 2 | InternalInfo: ClassId, ContainedObject, GeneratedType | ERROR / WARN |
|
||||||
|
| 3 | Properties: Name (identifier), Synonym | ERROR / WARN |
|
||||||
|
| 4 | ChildObjects: допустимые типы, порядок | ERROR / WARN |
|
||||||
|
| 5 | Cross-references: DefaultForm → Form, AuxiliaryForm | ERROR / WARN |
|
||||||
|
| 6 | Attributes: UUID, Name, Type | ERROR |
|
||||||
|
| 7 | TabularSections: UUID, Name, GeneratedType, Attributes | ERROR / WARN |
|
||||||
|
| 8 | Уникальность имён (Attribute, TS, Form, Template, Command) | ERROR |
|
||||||
|
| 9 | Файлы: формы (.xml + Ext/Form.xml), макеты | ERROR |
|
||||||
|
| 10 | Дескрипторы форм: корневая структура, uuid, Name, FormType | ERROR / WARN |
|
||||||
|
|
||||||
|
Exit code: 0 = OK, 1 = есть ошибки. По умолчанию краткий вывод. `-Detailed` для поштучной детализации.
|
||||||
+3
-4
@@ -1,9 +1,8 @@
|
|||||||
# epf-validate v1.2 — Validate 1C external data processor / report structure
|
# epf-validate v1.1 — Validate 1C external data processor / report structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# Works for both EPF (ExternalDataProcessor) and ERF (ExternalReport) — auto-detects
|
# Works for both EPF (ExternalDataProcessor) and ERF (ExternalReport) — auto-detects
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$ObjectPath,
|
[string]$ObjectPath,
|
||||||
|
|
||||||
[switch]$Detailed,
|
[switch]$Detailed,
|
||||||
@@ -185,8 +184,8 @@ if ($root.NamespaceURI -ne $expectedNs) {
|
|||||||
$version = $root.GetAttribute("version")
|
$version = $root.GetAttribute("version")
|
||||||
if (-not $version) {
|
if (-not $version) {
|
||||||
Report-Warn "1. Missing version attribute on MetaDataObject"
|
Report-Warn "1. Missing version attribute on MetaDataObject"
|
||||||
} elseif ($version -ne "2.17" -and $version -ne "2.20" -and $version -ne "2.21") {
|
} elseif ($version -ne "2.17" -and $version -ne "2.20") {
|
||||||
Report-Warn "1. Unusual version '$version' (expected 2.17, 2.20 or 2.21)"
|
Report-Warn "1. Unusual version '$version' (expected 2.17 or 2.20)"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Detect type: ExternalDataProcessor or ExternalReport
|
# Detect type: ExternalDataProcessor or ExternalReport
|
||||||
+4
-4
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# epf-validate v1.2 — Validate 1C external data processor / report structure
|
# epf-validate v1.1 — Validate 1C external data processor / report structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
# Works for both EPF (ExternalDataProcessor) and ERF (ExternalReport) — auto-detects
|
# Works for both EPF (ExternalDataProcessor) and ERF (ExternalReport) — auto-detects
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ def main():
|
|||||||
sys.stdout.reconfigure(encoding="utf-8")
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
sys.stderr.reconfigure(encoding="utf-8")
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
parser = argparse.ArgumentParser(description="Validate 1C external data processor/report structure", allow_abbrev=False)
|
parser = argparse.ArgumentParser(description="Validate 1C external data processor/report structure", allow_abbrev=False)
|
||||||
parser.add_argument("-ObjectPath", "-Path", required=True)
|
parser.add_argument("-ObjectPath", required=True)
|
||||||
parser.add_argument("-Detailed", action="store_true")
|
parser.add_argument("-Detailed", action="store_true")
|
||||||
parser.add_argument("-MaxErrors", type=int, default=30)
|
parser.add_argument("-MaxErrors", type=int, default=30)
|
||||||
parser.add_argument("-OutFile", default=None)
|
parser.add_argument("-OutFile", default=None)
|
||||||
@@ -165,8 +165,8 @@ def main():
|
|||||||
version = root.get("version", "")
|
version = root.get("version", "")
|
||||||
if not version:
|
if not version:
|
||||||
report_warn("1. Missing version attribute on MetaDataObject")
|
report_warn("1. Missing version attribute on MetaDataObject")
|
||||||
elif version not in ("2.17", "2.20", "2.21"):
|
elif version not in ("2.17", "2.20"):
|
||||||
report_warn(f"1. Unusual version '{version}' (expected 2.17, 2.20 or 2.21)")
|
report_warn(f"1. Unusual version '{version}' (expected 2.17 or 2.20)")
|
||||||
|
|
||||||
# Detect type
|
# Detect type
|
||||||
child_elements = []
|
child_elements = []
|
||||||
@@ -34,7 +34,7 @@ allowed-tools:
|
|||||||
5. Если ветка не совпала — используй `default`
|
5. Если ветка не совпала — используй `default`
|
||||||
6. Если `.v8-project.json` нет или база не найдена — не указывай параметры подключения: скрипт автоматически создаст временную базу. Для ERF со ссылочными типами (CatalogRef, DocumentRef и т.д.) генерируются заглушки метаданных. Временная база удаляется после сборки.
|
6. Если `.v8-project.json` нет или база не найдена — не указывай параметры подключения: скрипт автоматически создаст временную базу. Для ERF со ссылочными типами (CatalogRef, DocumentRef и т.д.) генерируются заглушки метаданных. Временная база удаляется после сборки.
|
||||||
|
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
@@ -42,7 +42,7 @@ allowed-tools:
|
|||||||
Используй общий скрипт из epf-build:
|
Используй общий скрипт из epf-build:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -64,8 +64,8 @@ python ".opencode/skills/epf-build/scripts/epf-build.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Сборка отчёта (файловая база)
|
# Сборка отчёта (файловая база)
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" -InfoBasePath "C:\Bases\MyDB" -SourceFile "src/МойОтчёт.xml" -OutputFile "build/МойОтчёт.erf"
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 -InfoBasePath "C:\Bases\MyDB" -SourceFile "src/МойОтчёт.xml" -OutputFile "build/МойОтчёт.erf"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/epf-build/scripts/epf-build.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -SourceFile "src/МойОтчёт.xml" -OutputFile "build/МойОтчёт.erf"
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -SourceFile "src/МойОтчёт.xml" -OutputFile "build/МойОтчёт.erf"
|
||||||
```
|
```
|
||||||
@@ -33,7 +33,7 @@ allowed-tools:
|
|||||||
5. Если ветка не совпала — используй `default`
|
5. Если ветка не совпала — используй `default`
|
||||||
6. Если `.v8-project.json` нет или база не найдена — **сообщи пользователю об ошибке**. Для dump база обязательна: в пустой базе ссылочные типы (CatalogRef, DocumentRef и т.д.) безвозвратно сбрасываются в строки. Предложи указать базу или зарегистрировать через `/db-list add`.
|
6. Если `.v8-project.json` нет или база не найдена — **сообщи пользователю об ошибке**. Для dump база обязательна: в пустой базе ссылочные типы (CatalogRef, DocumentRef и т.д.) безвозвратно сбрасываются в строки. Предложи указать базу или зарегистрировать через `/db-list add`.
|
||||||
|
|
||||||
Если `v8path` не задан — скрипт сам попытается определить платформу (`.v8-project.json` → Program Files).
|
Если `v8path` не задан — автоопределение: `Get-ChildItem "C:\Program Files\1cv8\*\bin\1cv8.exe" | Sort -Desc | Select -First 1`
|
||||||
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
Если использованная база не зарегистрирована — после выполнения предложи добавить через `/db-list add`.
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
@@ -41,7 +41,7 @@ allowed-tools:
|
|||||||
Используй общий скрипт из epf-dump:
|
Используй общий скрипт из epf-dump:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -64,8 +64,8 @@ python ".opencode/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Разборка отчёта (файловая база)
|
# Разборка отчёта (файловая база)
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" -InfoBasePath "C:\Bases\MyDB" -InputFile "build/МойОтчёт.erf" -OutputDir "src"
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 -InfoBasePath "C:\Bases\MyDB" -InputFile "build/МойОтчёт.erf" -OutputDir "src"
|
||||||
|
|
||||||
# Серверная база
|
# Серверная база
|
||||||
python ".opencode/skills/epf-dump/scripts/epf-dump.py" -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -InputFile "build/МойОтчёт.erf" -OutputDir "src"
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 -InfoBaseServer "srv01" -InfoBaseRef "MyDB" -UserName "Admin" -Password "secret" -InputFile "build/МойОтчёт.erf" -OutputDir "src"
|
||||||
```
|
```
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: erf-init
|
name: erf-init
|
||||||
description: Создать пустой внешний отчёт 1С (scaffold XML-исходников). Используй когда нужно создать новый внешний отчёт с нуля
|
description: Создать пустой внешний отчёт 1С (scaffold XML-исходников)
|
||||||
argument-hint: <Name> [Synonym] [--with-skd]
|
argument-hint: <Name> [Synonym] [--with-skd]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -31,9 +31,35 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/erf-init/scripts/init.py" -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"] [-WithSKD]
|
powershell.exe -NoProfile -File .claude/skills/erf-init/scripts/init.ps1 -Name "<Name>" [-Synonym "<Synonym>"] [-SrcDir "<SrcDir>"] [-WithSKD]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<SrcDir>/
|
||||||
|
├── <Name>.xml # Корневой файл метаданных (4 UUID)
|
||||||
|
└── <Name>/
|
||||||
|
└── Ext/
|
||||||
|
└── ObjectModule.bsl # Модуль объекта с 3 регионами
|
||||||
|
```
|
||||||
|
|
||||||
|
При `--WithSKD` дополнительно:
|
||||||
|
|
||||||
|
```
|
||||||
|
<SrcDir>/<Name>/
|
||||||
|
Templates/
|
||||||
|
├── ОсновнаяСхемаКомпоновкиДанных.xml # Метаданные макета
|
||||||
|
└── ОсновнаяСхемаКомпоновкиДанных/
|
||||||
|
└── Ext/
|
||||||
|
└── Template.xml # Пустая СКД
|
||||||
|
```
|
||||||
|
|
||||||
|
- Корневой XML содержит `MetaDataObject/ExternalReport` с пустыми `DefaultForm`, `MainDataCompositionSchema` и `ChildObjects`
|
||||||
|
- При `--WithSKD` — `MainDataCompositionSchema` заполняется ссылкой на макет, `ChildObjects` содержит `<Template>`
|
||||||
|
- ClassId фиксирован: `e41aff26-25cf-4bb6-b6c1-3f478a75f374`
|
||||||
|
- Файл создаётся в UTF-8 с BOM
|
||||||
|
|
||||||
## Дальнейшие шаги
|
## Дальнейшие шаги
|
||||||
|
|
||||||
- Добавить форму: `/form-add`
|
- Добавить форму: `/form-add`
|
||||||
+1
-3
@@ -1,4 +1,4 @@
|
|||||||
# erf-init v1.1 — Init 1C external report scaffold
|
# erf-init v1.0 — Init 1C external report scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -12,8 +12,6 @@ param(
|
|||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
|
|
||||||
$uuid1 = [guid]::NewGuid().ToString()
|
$uuid1 = [guid]::NewGuid().ToString()
|
||||||
$uuid2 = [guid]::NewGuid().ToString()
|
$uuid2 = [guid]::NewGuid().ToString()
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# erf-init v1.1 — Init 1C external report scaffold
|
# erf-init v1.0 — Init 1C external report scaffold
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
"""Generates minimal XML source files for a 1C external report."""
|
"""Generates minimal XML source files for a 1C external report."""
|
||||||
import sys, os, argparse, uuid
|
import sys, os, argparse, uuid
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
---
|
||||||
|
name: erf-validate
|
||||||
|
description: Валидация внешнего отчёта 1С (ERF). Используй после создания или модификации отчёта для проверки корректности
|
||||||
|
argument-hint: <ObjectPath> [-Detailed] [-MaxErrors 30]
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Glob
|
||||||
|
---
|
||||||
|
|
||||||
|
# /erf-validate — валидация внешнего отчёта (ERF)
|
||||||
|
|
||||||
|
Проверяет структурную корректность XML-исходников внешнего отчёта: корневую структуру, InternalInfo, свойства (включая MainDataCompositionSchema), ChildObjects, реквизиты, табличные части, уникальность имён, наличие файлов форм и макетов.
|
||||||
|
|
||||||
|
Использует тот же скрипт, что и `/epf-validate` — автоопределение по типу элемента (ExternalReport).
|
||||||
|
|
||||||
|
## Параметры
|
||||||
|
|
||||||
|
| Параметр | Обяз. | Умолч. | Описание |
|
||||||
|
|------------|:-----:|---------|-------------------------------------------------|
|
||||||
|
| ObjectPath | да | — | Путь к корневому XML или каталогу отчёта |
|
||||||
|
| Detailed | нет | — | Показывать [OK] для каждой проверки |
|
||||||
|
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||||
|
| OutFile | нет | — | Записать результат в файл (UTF-8 BOM) |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МойОтчёт"
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МойОтчёт/МойОтчёт.xml"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
| # | Проверка | Серьёзность |
|
||||||
|
|----|-------------------------------------------------------|--------------|
|
||||||
|
| 1 | Root structure: MetaDataObject/ExternalReport | ERROR |
|
||||||
|
| 2 | InternalInfo: ClassId, ContainedObject, GeneratedType | ERROR / WARN |
|
||||||
|
| 3 | Properties: Name, Synonym, MainDataCompositionSchema | ERROR / WARN |
|
||||||
|
| 4 | ChildObjects: допустимые типы, порядок | ERROR / WARN |
|
||||||
|
| 5 | Cross-references: DefaultForm, MainDCS → Template | ERROR / WARN |
|
||||||
|
| 6 | Attributes: UUID, Name, Type | ERROR |
|
||||||
|
| 7 | TabularSections: UUID, Name, GeneratedType, Attributes | ERROR / WARN |
|
||||||
|
| 8 | Уникальность имён (Attribute, TS, Form, Template, Command) | ERROR |
|
||||||
|
| 9 | Файлы: формы (.xml + Ext/Form.xml), макеты | ERROR |
|
||||||
|
| 10 | Дескрипторы форм: корневая структура, uuid, Name, FormType | ERROR / WARN |
|
||||||
|
|
||||||
|
Exit code: 0 = OK, 1 = есть ошибки. По умолчанию краткий вывод. `-Detailed` для поштучной детализации.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
name: form-add
|
name: form-add
|
||||||
description: Добавить пустую управляемую форму к объекту 1С. Используй когда нужно создать у объекта новую форму
|
description: Добавить управляемую форму к объекту конфигурации 1С
|
||||||
argument-hint: <ObjectPath> <FormName> [Purpose] [--set-default]
|
argument-hint: <ObjectPath> <FormName> [Purpose] [--set-default]
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
@@ -32,7 +32,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/form-add/scripts/form-add.py" -ObjectPath "<ObjectPath>" -FormName "<FormName>" [-Purpose "<Purpose>"] [-Synonym "<Synonym>"] [-SetDefault]
|
powershell.exe -NoProfile -File .claude/skills/form-add/scripts/form-add.ps1 -ObjectPath "<ObjectPath>" -FormName "<FormName>" [-Purpose "<Purpose>"] [-Synonym "<Synonym>"] [-SetDefault]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Purpose — назначение формы
|
## Purpose — назначение формы
|
||||||
@@ -44,6 +44,26 @@ python ".opencode/skills/form-add/scripts/form-add.py" -ObjectPath "<ObjectPath>
|
|||||||
| Choice | Document, Catalog, ChartOf*, ExchangePlan, BusinessProcess, Task | Список (DynamicList) | DefaultChoiceForm |
|
| Choice | Document, Catalog, ChartOf*, ExchangePlan, BusinessProcess, Task | Список (DynamicList) | DefaultChoiceForm |
|
||||||
| Record | InformationRegister | Запись (InformationRegisterRecordManager) | DefaultRecordForm |
|
| Record | InformationRegister | Запись (InformationRegisterRecordManager) | DefaultRecordForm |
|
||||||
|
|
||||||
|
## Что создаётся
|
||||||
|
|
||||||
|
```
|
||||||
|
<ObjectDir>/Forms/
|
||||||
|
├── <FormName>.xml # Метаданные формы (UUID)
|
||||||
|
└── <FormName>/
|
||||||
|
└── Ext/
|
||||||
|
├── Form.xml # Описание формы (logform namespace)
|
||||||
|
└── Form/
|
||||||
|
└── Module.bsl # BSL-модуль с 5 регионами + ПриСозданииНаСервере
|
||||||
|
```
|
||||||
|
|
||||||
|
## Что модифицируется
|
||||||
|
|
||||||
|
- `<ObjectPath>` — добавляется `<Form>` в `ChildObjects` (перед `<Template>` или `<TabularSection>`), обновляется Default*Form (автоматически если пустое, или явно при `--set-default`)
|
||||||
|
|
||||||
|
## Поддерживаемые типы объектов
|
||||||
|
|
||||||
|
Document, Catalog, DataProcessor, Report, ExternalDataProcessor, ExternalReport, InformationRegister, ChartOfAccounts, ChartOfCharacteristicTypes, ExchangePlan, BusinessProcess, Task
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```
|
```
|
||||||
+24
-173
@@ -1,4 +1,4 @@
|
|||||||
# form-add v1.7 — Add managed form to 1C config object
|
# form-add v1.0 — Add managed form to 1C config object
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -15,167 +15,15 @@ param(
|
|||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$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 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 {}
|
|
||||||
$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 (-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) {
|
|
||||||
$head = [System.IO.File]::ReadAllText($cfgPath, [System.Text.Encoding]::UTF8).Substring(0, [Math]::Min(2000, (Get-Item $cfgPath).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: Определение типа объекта ---
|
# --- Фаза 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)) {
|
if (-not (Test-Path $ObjectPath)) {
|
||||||
Write-Error "Файл объекта не найден: $ObjectPath"
|
Write-Error "Файл объекта не найден: $ObjectPath"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
$objectXmlFull = Resolve-Path $ObjectPath
|
$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 = New-Object System.Xml.XmlDocument
|
||||||
$xmlDoc.PreserveWhitespace = $true
|
$xmlDoc.PreserveWhitespace = $true
|
||||||
$xmlDoc.Load($objectXmlFull.Path)
|
$xmlDoc.Load($objectXmlFull.Path)
|
||||||
@@ -194,7 +42,7 @@ if (-not $metaDataObject) {
|
|||||||
$supportedTypes = @(
|
$supportedTypes = @(
|
||||||
"Document", "Catalog", "DataProcessor", "Report",
|
"Document", "Catalog", "DataProcessor", "Report",
|
||||||
"ExternalDataProcessor", "ExternalReport",
|
"ExternalDataProcessor", "ExternalReport",
|
||||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
"InformationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||||
"ExchangePlan", "BusinessProcess", "Task"
|
"ExchangePlan", "BusinessProcess", "Task"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -291,15 +139,9 @@ $encBom = New-Object System.Text.UTF8Encoding($true)
|
|||||||
|
|
||||||
$formUuid = [guid]::NewGuid().ToString()
|
$formUuid = [guid]::NewGuid().ToString()
|
||||||
|
|
||||||
# ExtendedPresentation — only for DataProcessor, Report, ExternalDataProcessor, ExternalReport forms
|
|
||||||
$extPresentationLine = ""
|
|
||||||
if ($objectType -in $processorLikeTypes) {
|
|
||||||
$extPresentationLine = "`n`t`t`t<ExtendedPresentation/>"
|
|
||||||
}
|
|
||||||
|
|
||||||
$formMetaXml = @"
|
$formMetaXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?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)">
|
<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">
|
||||||
<Form uuid="$formUuid">
|
<Form uuid="$formUuid">
|
||||||
<Properties>
|
<Properties>
|
||||||
<Name>$FormName</Name>
|
<Name>$FormName</Name>
|
||||||
@@ -315,7 +157,8 @@ $formMetaXml = @"
|
|||||||
<UsePurposes>
|
<UsePurposes>
|
||||||
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>
|
||||||
<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>
|
<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>
|
||||||
</UsePurposes>$extPresentationLine
|
</UsePurposes>
|
||||||
|
<ExtendedPresentation/>
|
||||||
</Properties>
|
</Properties>
|
||||||
</Form>
|
</Form>
|
||||||
</MetaDataObject>
|
</MetaDataObject>
|
||||||
@@ -336,10 +179,13 @@ if ($Purpose -eq "List" -or $Purpose -eq "Choice") {
|
|||||||
|
|
||||||
$formXml = @"
|
$formXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Form $formNsDecl version="$($script:formatVersion)">
|
<Form $formNsDecl version="2.17">
|
||||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||||
<Autofill>true</Autofill>
|
<Autofill>true</Autofill>
|
||||||
</AutoCommandBar>
|
</AutoCommandBar>
|
||||||
|
<Events>
|
||||||
|
<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
|
||||||
|
</Events>
|
||||||
<ChildItems/>
|
<ChildItems/>
|
||||||
<Attributes>
|
<Attributes>
|
||||||
<Attribute name="Список" id="1">
|
<Attribute name="Список" id="1">
|
||||||
@@ -361,10 +207,13 @@ if ($Purpose -eq "List" -or $Purpose -eq "Choice") {
|
|||||||
|
|
||||||
$formXml = @"
|
$formXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Form $formNsDecl version="$($script:formatVersion)">
|
<Form $formNsDecl version="2.17">
|
||||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||||
<Autofill>true</Autofill>
|
<Autofill>true</Autofill>
|
||||||
</AutoCommandBar>
|
</AutoCommandBar>
|
||||||
|
<Events>
|
||||||
|
<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
|
||||||
|
</Events>
|
||||||
<ChildItems/>
|
<ChildItems/>
|
||||||
<Attributes>
|
<Attributes>
|
||||||
<Attribute name="$mainAttrName" id="1">
|
<Attribute name="$mainAttrName" id="1">
|
||||||
@@ -395,30 +244,27 @@ if ($Purpose -eq "List" -or $Purpose -eq "Choice") {
|
|||||||
"BusinessProcess" = "BusinessProcessObject"
|
"BusinessProcess" = "BusinessProcessObject"
|
||||||
"Task" = "TaskObject"
|
"Task" = "TaskObject"
|
||||||
"InformationRegister" = "InformationRegisterRecordManager"
|
"InformationRegister" = "InformationRegisterRecordManager"
|
||||||
"AccumulationRegister" = "AccumulationRegisterRecordSet"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$mainAttrType = "$($attrTypeMap[$objectType]).$objectName"
|
$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 = @"
|
$formXml = @"
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Form $formNsDecl version="$($script:formatVersion)">
|
<Form $formNsDecl version="2.17">
|
||||||
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
<AutoCommandBar name="ФормаКоманднаяПанель" id="-1">
|
||||||
<Autofill>true</Autofill>
|
<Autofill>true</Autofill>
|
||||||
</AutoCommandBar>
|
</AutoCommandBar>
|
||||||
|
<Events>
|
||||||
|
<Event name="OnCreateAtServer">ПриСозданииНаСервере</Event>
|
||||||
|
</Events>
|
||||||
<ChildItems/>
|
<ChildItems/>
|
||||||
<Attributes>
|
<Attributes>
|
||||||
<Attribute name="$mainAttrName" id="1">
|
<Attribute name="$mainAttrName" id="1">
|
||||||
<Type>
|
<Type>
|
||||||
<v8:Type>cfg:$mainAttrType</v8:Type>
|
<v8:Type>cfg:$mainAttrType</v8:Type>
|
||||||
</Type>
|
</Type>
|
||||||
<MainAttribute>true</MainAttribute>$savedDataLine
|
<MainAttribute>true</MainAttribute>
|
||||||
|
<SavedData>true</SavedData>
|
||||||
</Attribute>
|
</Attribute>
|
||||||
</Attributes>
|
</Attributes>
|
||||||
</Form>
|
</Form>
|
||||||
@@ -438,6 +284,11 @@ $modulePath = Join-Path $formModuleDir "Module.bsl"
|
|||||||
$moduleBsl = @"
|
$moduleBsl = @"
|
||||||
#Область ОбработчикиСобытийФормы
|
#Область ОбработчикиСобытийФормы
|
||||||
|
|
||||||
|
&НаСервере
|
||||||
|
Процедура ПриСозданииНаСервере(Отказ, СтандартнаяОбработка)
|
||||||
|
|
||||||
|
КонецПроцедуры
|
||||||
|
|
||||||
#КонецОбласти
|
#КонецОбласти
|
||||||
|
|
||||||
#Область ОбработчикиСобытийЭлементовФормы
|
#Область ОбработчикиСобытийЭлементовФормы
|
||||||
+25
-209
@@ -1,204 +1,24 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-add v1.7 — Add managed form to 1C config object
|
# form-add v1.0 — Add managed form to 1C config object
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from lxml import etree
|
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_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)
|
|
||||||
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 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 = {
|
NSMAP = {
|
||||||
"md": "http://v8.1c.ru/8.3/MDClasses",
|
"md": "http://v8.1c.ru/8.3/MDClasses",
|
||||||
"v8": "http://v8.1c.ru/8.1/data/core",
|
"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 save_xml_with_bom(tree, path):
|
def save_xml_with_bom(tree, path):
|
||||||
"""Save XML tree to file with UTF-8 BOM."""
|
"""Save XML tree to file with UTF-8 BOM."""
|
||||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
if not xml_bytes.endswith(b"\n"):
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
with open(path, "wb") as f:
|
with open(path, "wb") as f:
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
@@ -229,25 +49,13 @@ def main():
|
|||||||
|
|
||||||
# --- Phase 1: Determine object type ---
|
# --- 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):
|
if os.path.isdir(object_path):
|
||||||
dir_name = os.path.basename(object_path.rstrip("/\\"))
|
object_path = object_path.rstrip("/\\") + ".xml"
|
||||||
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):
|
if not os.path.isfile(object_path):
|
||||||
print(f"Файл объекта не найден: {object_path}", file=sys.stderr)
|
print(f"Файл объекта не найден: {object_path}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
object_xml_full = os.path.abspath(object_path)
|
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)
|
parser_xml = etree.XMLParser(remove_blank_text=False)
|
||||||
tree = etree.parse(object_xml_full, parser_xml)
|
tree = etree.parse(object_xml_full, parser_xml)
|
||||||
root = tree.getroot()
|
root = tree.getroot()
|
||||||
@@ -255,7 +63,7 @@ def main():
|
|||||||
supported_types = [
|
supported_types = [
|
||||||
"Document", "Catalog", "DataProcessor", "Report",
|
"Document", "Catalog", "DataProcessor", "Report",
|
||||||
"ExternalDataProcessor", "ExternalReport",
|
"ExternalDataProcessor", "ExternalReport",
|
||||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
"InformationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||||
"ExchangePlan", "BusinessProcess", "Task",
|
"ExchangePlan", "BusinessProcess", "Task",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -352,7 +160,7 @@ def main():
|
|||||||
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
|
||||||
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
|
||||||
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
|
||||||
f' version="{format_version}">\n'
|
' version="2.17">\n'
|
||||||
f'\t<Form uuid="{form_uuid}">\n'
|
f'\t<Form uuid="{form_uuid}">\n'
|
||||||
'\t\t<Properties>\n'
|
'\t\t<Properties>\n'
|
||||||
f'\t\t\t<Name>{form_name}</Name>\n'
|
f'\t\t\t<Name>{form_name}</Name>\n'
|
||||||
@@ -369,8 +177,8 @@ def main():
|
|||||||
'\t\t\t\t<v8:Value xsi:type="app:ApplicationUsePurpose">PlatformApplication</v8:Value>\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\t<v8:Value xsi:type="app:ApplicationUsePurpose">MobilePlatformApplication</v8:Value>\n'
|
||||||
'\t\t\t</UsePurposes>\n'
|
'\t\t\t</UsePurposes>\n'
|
||||||
+ ('\t\t\t<ExtendedPresentation/>\n' if object_type in processor_like_types else '')
|
'\t\t\t<ExtendedPresentation/>\n'
|
||||||
+ '\t\t</Properties>\n'
|
'\t\t</Properties>\n'
|
||||||
'\t</Form>\n'
|
'\t</Form>\n'
|
||||||
'</MetaDataObject>'
|
'</MetaDataObject>'
|
||||||
)
|
)
|
||||||
@@ -406,10 +214,13 @@ def main():
|
|||||||
|
|
||||||
form_xml = (
|
form_xml = (
|
||||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
f'<Form {form_ns_decl} version="2.17">\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<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\t<Autofill>true</Autofill>\n'
|
||||||
'\t</AutoCommandBar>\n'
|
'\t</AutoCommandBar>\n'
|
||||||
|
'\t<Events>\n'
|
||||||
|
'\t\t<Event name="OnCreateAtServer">\u041f\u0440\u0438\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0438\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435</Event>\n'
|
||||||
|
'\t</Events>\n'
|
||||||
'\t<ChildItems/>\n'
|
'\t<ChildItems/>\n'
|
||||||
'\t<Attributes>\n'
|
'\t<Attributes>\n'
|
||||||
'\t\t<Attribute name="\u0421\u043f\u0438\u0441\u043e\u043a" id="1">\n'
|
'\t\t<Attribute name="\u0421\u043f\u0438\u0441\u043e\u043a" id="1">\n'
|
||||||
@@ -432,10 +243,13 @@ def main():
|
|||||||
|
|
||||||
form_xml = (
|
form_xml = (
|
||||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
f'<Form {form_ns_decl} version="2.17">\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<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\t<Autofill>true</Autofill>\n'
|
||||||
'\t</AutoCommandBar>\n'
|
'\t</AutoCommandBar>\n'
|
||||||
|
'\t<Events>\n'
|
||||||
|
'\t\t<Event name="OnCreateAtServer">\u041f\u0440\u0438\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0438\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435</Event>\n'
|
||||||
|
'\t</Events>\n'
|
||||||
'\t<ChildItems/>\n'
|
'\t<ChildItems/>\n'
|
||||||
'\t<Attributes>\n'
|
'\t<Attributes>\n'
|
||||||
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
||||||
@@ -466,22 +280,19 @@ def main():
|
|||||||
"BusinessProcess": "BusinessProcessObject",
|
"BusinessProcess": "BusinessProcessObject",
|
||||||
"Task": "TaskObject",
|
"Task": "TaskObject",
|
||||||
"InformationRegister": "InformationRegisterRecordManager",
|
"InformationRegister": "InformationRegisterRecordManager",
|
||||||
"AccumulationRegister": "AccumulationRegisterRecordSet",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main_attr_type = f"{attr_type_map[object_type]}.{object_name}"
|
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 = (
|
form_xml = (
|
||||||
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
f'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||||
f'<Form {form_ns_decl} version="{format_version}">\n'
|
f'<Form {form_ns_decl} version="2.17">\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<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\t<Autofill>true</Autofill>\n'
|
||||||
'\t</AutoCommandBar>\n'
|
'\t</AutoCommandBar>\n'
|
||||||
|
'\t<Events>\n'
|
||||||
|
'\t\t<Event name="OnCreateAtServer">\u041f\u0440\u0438\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0438\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435</Event>\n'
|
||||||
|
'\t</Events>\n'
|
||||||
'\t<ChildItems/>\n'
|
'\t<ChildItems/>\n'
|
||||||
'\t<Attributes>\n'
|
'\t<Attributes>\n'
|
||||||
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
f'\t\t<Attribute name="{main_attr_name}" id="1">\n'
|
||||||
@@ -489,7 +300,7 @@ def main():
|
|||||||
f'\t\t\t\t<v8:Type>cfg:{main_attr_type}</v8:Type>\n'
|
f'\t\t\t\t<v8:Type>cfg:{main_attr_type}</v8:Type>\n'
|
||||||
'\t\t\t</Type>\n'
|
'\t\t\t</Type>\n'
|
||||||
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
'\t\t\t<MainAttribute>true</MainAttribute>\n'
|
||||||
f'{saved_data_line}'
|
'\t\t\t<SavedData>true</SavedData>\n'
|
||||||
'\t\t</Attribute>\n'
|
'\t\t</Attribute>\n'
|
||||||
'\t</Attributes>\n'
|
'\t</Attributes>\n'
|
||||||
'</Form>'
|
'</Form>'
|
||||||
@@ -507,6 +318,11 @@ def main():
|
|||||||
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'
|
'#\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'
|
'\n'
|
||||||
|
'&\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435\n'
|
||||||
|
'\u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u0430 \u041f\u0440\u0438\u0421\u043e\u0437\u0434\u0430\u043d\u0438\u0438\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435(\u041e\u0442\u043a\u0430\u0437, \u0421\u0442\u0430\u043d\u0434\u0430\u0440\u0442\u043d\u0430\u044f\u041e\u0431\u0440\u0430\u0431\u043e\u0442\u043a\u0430)\n'
|
||||||
|
'\n'
|
||||||
|
'\u041a\u043e\u043d\u0435\u0446\u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u044b\n'
|
||||||
|
'\n'
|
||||||
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
'#\u041a\u043e\u043d\u0435\u0446\u041e\u0431\u043b\u0430\u0441\u0442\u0438\n'
|
||||||
'\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'
|
'#\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'
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
name: form-compile
|
name: form-compile
|
||||||
description: Компиляция управляемой формы 1С из JSON-определения или из метаданных объекта. Используй когда нужно создать форму с нуля по описанию элементов или сгенерировать типовую форму
|
description: Компиляция управляемой формы 1С из компактного JSON-определения. Используй когда нужно создать форму с нуля по описанию элементов
|
||||||
argument-hint: <JsonPath> <OutputPath> | -FromObject <OutputPath>
|
argument-hint: <JsonPath> <OutputPath>
|
||||||
allowed-tools:
|
allowed-tools:
|
||||||
- Bash
|
- Bash
|
||||||
- Read
|
- Read
|
||||||
@@ -9,30 +9,29 @@ allowed-tools:
|
|||||||
- Glob
|
- Glob
|
||||||
---
|
---
|
||||||
|
|
||||||
# /form-compile — Генерация Form.xml
|
# /form-compile — Генерация Form.xml из JSON DSL
|
||||||
|
|
||||||
Два режима:
|
Принимает компактное JSON-определение формы (20–50 строк) и генерирует полный корректный Form.xml (100–500+ строк) с namespace-декларациями, автогенерированными companion-элементами, последовательными ID.
|
||||||
1. **JSON DSL** — из JSON-определения формы
|
|
||||||
2. **From object** (`-FromObject`) — автоматически из метаданных объекта 1С по пресету ERP
|
|
||||||
|
|
||||||
> **При проектировании формы с нуля (5+ элементов или нечёткие требования)** — вызовите `/form-patterns` для загрузки справочника. Для простых форм (1–3 поля) — не нужно.
|
> **При проектировании формы с нуля (5+ элементов или нечёткие требования)** — вызовите `/form-patterns` для загрузки справочника: архетипы, конвенции именования, продвинутые паттерны. Для простых форм (1–3 поля, пользователь описал что нужно) — не нужно.
|
||||||
|
|
||||||
|
## Использование
|
||||||
|
|
||||||
|
```
|
||||||
|
/form-compile <JsonPath> <OutputPath>
|
||||||
|
```
|
||||||
|
|
||||||
## Параметры
|
## Параметры
|
||||||
|
|
||||||
| Параметр | Обязательный | Описание |
|
| Параметр | Обязательный | Описание |
|
||||||
|------------|:------------:|---------------------------------|
|
|------------|:------------:|-----------------------------------|
|
||||||
| JsonPath | режим 1 | Путь к JSON-определению формы |
|
| JsonPath | да | Путь к JSON-определению формы |
|
||||||
| OutputPath | да | Путь к выходному Form.xml |
|
| OutputPath | да | Путь к выходному файлу Form.xml |
|
||||||
| FromObject | режим 2 | Флаг (без значения) — генерация по метаданным объекта |
|
|
||||||
|
|
||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Режим JSON DSL
|
powershell.exe -NoProfile -File .claude/skills/form-compile/scripts/form-compile.ps1 -JsonPath "<json>" -OutputPath "<xml>"
|
||||||
python ".opencode/skills/form-compile/scripts/form-compile.py" -JsonPath "<json>" -OutputPath "<Form.xml>"
|
|
||||||
|
|
||||||
# Режим from-object (объект и purpose выводятся из OutputPath; Document и Catalog)
|
|
||||||
python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -OutputPath "<.../TypePlural/ObjectName/Forms/FormName/Ext/Form.xml>"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## JSON DSL — справка
|
## JSON DSL — справка
|
||||||
@@ -61,11 +60,9 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
|
|
||||||
| DSL ключ | XML элемент | Значение ключа |
|
| DSL ключ | XML элемент | Значение ключа |
|
||||||
|--------------|-------------------|---------------------------------------------------|
|
|--------------|-------------------|---------------------------------------------------|
|
||||||
| `"group"` | UsualGroup | ориентация: `"vertical"` / `"horizontalIfPossible"` / `"alwaysHorizontal"` (поведение — отдельный ключ `behavior`) |
|
| `"group"` | UsualGroup | `"horizontal"` / `"vertical"` / `"alwaysHorizontal"` / `"alwaysVertical"` / `"collapsible"` |
|
||||||
| `"columnGroup"` | ColumnGroup | `"horizontal"` / `"vertical"` / `"inCell"` — только внутри `columns` таблицы |
|
|
||||||
| `"input"` | InputField | имя элемента |
|
| `"input"` | InputField | имя элемента |
|
||||||
| `"check"` | CheckBoxField | имя |
|
| `"check"` | CheckBoxField | имя |
|
||||||
| `"radio"` | RadioButtonField | имя |
|
|
||||||
| `"label"` | LabelDecoration | имя (текст задаётся через `title`) |
|
| `"label"` | LabelDecoration | имя (текст задаётся через `title`) |
|
||||||
| `"labelField"` | LabelField | имя |
|
| `"labelField"` | LabelField | имя |
|
||||||
| `"table"` | Table | имя |
|
| `"table"` | Table | имя |
|
||||||
@@ -76,22 +73,21 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
| `"picField"` | PictureField | имя |
|
| `"picField"` | PictureField | имя |
|
||||||
| `"calendar"` | CalendarField | имя |
|
| `"calendar"` | CalendarField | имя |
|
||||||
| `"cmdBar"` | CommandBar | имя |
|
| `"cmdBar"` | CommandBar | имя |
|
||||||
| `"autoCmdBar"` | AutoCommandBar формы | имя — наполняет главную АКП формы (id=-1), не попадает в `<ChildItems>` |
|
|
||||||
| `"popup"` | Popup | имя |
|
| `"popup"` | Popup | имя |
|
||||||
|
|
||||||
### Общие свойства (все типы элементов)
|
### Общие свойства (все типы элементов)
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `name` | Переопределить имя (по умолчанию = значение ключа типа). Имена уникальны во всех коллекциях формы (элементы, реквизиты, команды, колонки) |
|
| `name` | Переопределить имя (по умолчанию = значение ключа типа) |
|
||||||
| `title` | Заголовок элемента |
|
| `title` | Заголовок элемента |
|
||||||
| `tooltip` | Всплывающая подсказка элемента (строка или `{ru,en}`) |
|
|
||||||
| `visible: false` | Скрыть (синоним: `hidden: true`) |
|
| `visible: false` | Скрыть (синоним: `hidden: true`) |
|
||||||
| `enabled: false` | Сделать недоступным (синоним: `disabled: true`) |
|
| `enabled: false` | Сделать недоступным (синоним: `disabled: true`) |
|
||||||
| `readOnly: true` | Только чтение |
|
| `readOnly: true` | Только чтение |
|
||||||
| `events: {...}` | Обработчики событий: `{ "OnChange": "ИмяОбработчика" }`. Тот же формат, что у событий формы. Значение `null` → имя обработчика сгенерируется автоматически |
|
| `on: [...]` | События с автоименованием обработчиков |
|
||||||
|
| `handlers: {...}` | Явное задание имён обработчиков: `{"OnChange": "МоёИмя"}` |
|
||||||
|
|
||||||
### Допустимые имена событий (`events`)
|
### Допустимые имена событий (`on`)
|
||||||
|
|
||||||
Компилятор предупреждает о неизвестных событиях. Имена регистрозависимы — используйте точно как указано.
|
Компилятор предупреждает о неизвестных событиях. Имена регистрозависимы — используйте точно как указано.
|
||||||
|
|
||||||
@@ -99,7 +95,7 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
|
|
||||||
**input / picField**: `OnChange`, `StartChoice`, `ChoiceProcessing`, `AutoComplete`, `TextEditEnd`, `Clearing`, `Creating`, `EditTextChange`
|
**input / picField**: `OnChange`, `StartChoice`, `ChoiceProcessing`, `AutoComplete`, `TextEditEnd`, `Clearing`, `Creating`, `EditTextChange`
|
||||||
|
|
||||||
**check / radio**: `OnChange`
|
**check**: `OnChange`
|
||||||
|
|
||||||
**table**: `OnStartEdit`, `OnEditEnd`, `OnChange`, `Selection`, `ValueChoice`, `BeforeAddRow`, `BeforeDeleteRow`, `AfterDeleteRow`, `BeforeRowChange`, `BeforeEditEnd`, `OnActivateRow`, `OnActivateCell`, `Drag`, `DragStart`, `DragCheck`, `DragEnd`
|
**table**: `OnStartEdit`, `OnEditEnd`, `OnChange`, `Selection`, `ValueChoice`, `BeforeAddRow`, `BeforeDeleteRow`, `AfterDeleteRow`, `BeforeRowChange`, `BeforeEditEnd`, `OnActivateRow`, `OnActivateCell`, `Drag`, `DragStart`, `DragCheck`, `DragEnd`
|
||||||
|
|
||||||
@@ -116,7 +112,7 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
| Ключ | Описание | Пример |
|
| Ключ | Описание | Пример |
|
||||||
|------|----------|--------|
|
|------|----------|--------|
|
||||||
| `path` | DataPath — привязка к данным | `"Объект.Организация"` |
|
| `path` | DataPath — привязка к данным | `"Объект.Организация"` |
|
||||||
| `titleLocation` | Размещение заголовка | `"none"`, `"left"`, `"right"`, `"top"`, `"bottom"`, `"auto"` |
|
| `titleLocation` | Размещение заголовка | `"none"`, `"left"`, `"top"` |
|
||||||
| `multiLine: true` | Многострочное поле | текстовое поле, комментарий |
|
| `multiLine: true` | Многострочное поле | текстовое поле, комментарий |
|
||||||
| `passwordMode: true` | Режим пароля (звёздочки) | поле ввода пароля |
|
| `passwordMode: true` | Режим пароля (звёздочки) | поле ввода пароля |
|
||||||
| `choiceButton: true` | Кнопка выбора ("...") | ссылочное поле |
|
| `choiceButton: true` | Кнопка выбора ("...") | ссылочное поле |
|
||||||
@@ -127,8 +123,7 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
| `skipOnInput: true` | Пропускать при обходе Tab | |
|
| `skipOnInput: true` | Пропускать при обходе Tab | |
|
||||||
| `inputHint` | Подсказка в пустом поле | `"Введите наименование..."` |
|
| `inputHint` | Подсказка в пустом поле | `"Введите наименование..."` |
|
||||||
| `width` / `height` | Размер | числа |
|
| `width` / `height` | Размер | числа |
|
||||||
| `autoMaxWidth: false` | Снять авто-ограничение ширины (поле растянется) | |
|
| `autoMaxWidth: false` | Отключить авто-ширину | для фиксированных полей |
|
||||||
| `maxWidth` / `maxHeight` | Жёсткое ограничение размера | числа; обычно вместе с `autoMaxWidth: false` |
|
|
||||||
| `horizontalStretch: true` | Растягивать по ширине | |
|
| `horizontalStretch: true` | Растягивать по ширине | |
|
||||||
|
|
||||||
### Чекбокс (check)
|
### Чекбокс (check)
|
||||||
@@ -138,37 +133,6 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
| `path` | DataPath |
|
| `path` | DataPath |
|
||||||
| `titleLocation` | Размещение заголовка |
|
| `titleLocation` | Размещение заголовка |
|
||||||
|
|
||||||
### Поле переключателя (radio)
|
|
||||||
|
|
||||||
Радиокнопки или тумблер для выбора одного значения из списка.
|
|
||||||
|
|
||||||
| Ключ | Описание | Пример |
|
|
||||||
|------|----------|--------|
|
|
||||||
| `path` | DataPath — привязка к реквизиту | `"СпособКурса"` |
|
|
||||||
| `radioButtonType` | Вид переключателя | `"Auto"` (по умолчанию), `"RadioButtons"`, `"Tumbler"` |
|
|
||||||
| `columnsCount` | Число колонок раскладки | `1`, `2`, ... |
|
|
||||||
| `titleLocation` | Размещение заголовка | по умолчанию `"none"` |
|
|
||||||
| `choiceList` | Список вариантов: массив `{value, presentation}` | см. ниже |
|
|
||||||
|
|
||||||
`choiceList[*]`:
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
|
||||||
|------|----------|
|
|
||||||
| `value` | Значение варианта. Строка/число/булево; для перечисления — `"Enum.ИмяТипа.EnumValue.ИмяЗначения"` |
|
|
||||||
| `presentation` | Текст рядом с переключателем. Строка (русский) либо объект `{ru, en, ...}` для мультиязычности |
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"radio": "СпособКурса",
|
|
||||||
"path": "Объект.СпособУстановкиКурса",
|
|
||||||
"radioButtonType": "Auto",
|
|
||||||
"choiceList": [
|
|
||||||
{ "value": "Enum.СпособыКурса.EnumValue.Авто", "presentation": { "ru": "Автоматически", "en": "Automatic" } },
|
|
||||||
{ "value": "Enum.СпособыКурса.EnumValue.Ручной", "presentation": "вручную" }
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Надпись-декорация (label)
|
### Надпись-декорация (label)
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
@@ -179,14 +143,12 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
|
|
||||||
### Группа (group)
|
### Группа (group)
|
||||||
|
|
||||||
Значение ключа задаёт **ориентацию**: `"vertical"`, `"horizontalIfPossible"`, `"alwaysHorizontal"`.
|
Значение ключа задаёт ориентацию: `"horizontal"`, `"vertical"`, `"alwaysHorizontal"`, `"alwaysVertical"`, `"collapsible"`.
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `behavior` | Поведение группы: `"collapsible"` (сворачиваемая) / `"popup"` (всплывающая). Опустить = обычная |
|
|
||||||
| `showTitle: true` | Показывать заголовок группы |
|
| `showTitle: true` | Показывать заголовок группы |
|
||||||
| `united: false` | Левый край полей ввода выравнивается только в пределах этой группы (по умолчанию `true` — сквозное выравнивание по самому длинному заголовку, в т.ч. с соседними группами) |
|
| `united: false` | Не объединять рамку |
|
||||||
| `collapsed: true` | Для `behavior: "collapsible"` / `"popup"` — группа создаётся свёрнутой |
|
|
||||||
| `representation` | `"none"`, `"normal"`, `"weak"`, `"strong"` |
|
| `representation` | `"none"`, `"normal"`, `"weak"`, `"strong"` |
|
||||||
| `children: [...]` | Вложенные элементы |
|
| `children: [...]` | Вложенные элементы |
|
||||||
|
|
||||||
@@ -203,52 +165,8 @@ python ".opencode/skills/form-compile/scripts/form-compile.py" -FromObject -Outp
|
|||||||
| `height` | Высота в строках таблицы |
|
| `height` | Высота в строках таблицы |
|
||||||
| `header: false` | Скрыть шапку |
|
| `header: false` | Скрыть шапку |
|
||||||
| `footer: true` | Показать подвал |
|
| `footer: true` | Показать подвал |
|
||||||
| `commandBarLocation` | `"None"`, `"Top"`, `"Bottom"`, `"Auto"` |
|
| `commandBarLocation` | `"None"`, `"Top"`, `"Auto"` |
|
||||||
| `searchStringLocation` | `"None"`, `"Top"`, `"Bottom"`, `"CommandBar"`, `"PullFromTop"`, `"Auto"` |
|
| `searchStringLocation` | `"None"`, `"Top"`, `"Auto"` |
|
||||||
| `choiceMode: true` | Режим выбора (для форм выбора) |
|
|
||||||
| `initialTreeView` | `"ExpandTopLevel"` и др. (иерархические списки) |
|
|
||||||
| `enableDrag: true` | Разрешить перетаскивание |
|
|
||||||
| `enableStartDrag: true` | Разрешить начало перетаскивания |
|
|
||||||
| `rowPictureDataPath` | Путь к картинке строки (напр. `"Список.DefaultPicture"`) |
|
|
||||||
| `tableAutofill: false` | Управление Autofill внутреннего AutoCommandBar |
|
|
||||||
|
|
||||||
Колонки можно группировать через `columnGroup` (см. ниже).
|
|
||||||
|
|
||||||
### Группа колонок (columnGroup)
|
|
||||||
|
|
||||||
Используется только внутри `columns` таблицы. Значение ключа задаёт ориентацию: `"horizontal"`, `"vertical"`, `"inCell"` (склеивает колонки в одну ячейку шапки). Допускается вложение `columnGroup` в `columnGroup`.
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
|
||||||
|------|----------|
|
|
||||||
| `name` | Имя элемента (рекомендуется задавать явно) |
|
|
||||||
| `title` | Заголовок группы |
|
|
||||||
| `showTitle: false` | Скрыть заголовок |
|
|
||||||
| `showInHeader: true/false` | Показывать ли группу в шапке таблицы |
|
|
||||||
| `width` | Ширина |
|
|
||||||
| `horizontalStretch: false` | Растягивание |
|
|
||||||
| `children: [...]` | Колонки внутри группы (`input`, `labelField`, `picField`, вложенный `columnGroup` …) |
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "table": "Список", "path": "Список", "columns": [
|
|
||||||
{ "columnGroup": "horizontal", "name": "ГруппаДата", "title": "Срок", "children": [
|
|
||||||
{ "input": "СрокИсполнения", "path": "Список.СрокИсполнения" },
|
|
||||||
{ "labelField": "Просрочено", "path": "Список.Просрочено" }
|
|
||||||
]},
|
|
||||||
{ "columnGroup": "inCell", "name": "ГруппаИсполнитель", "showInHeader": true, "children": [
|
|
||||||
{ "input": "Исполнитель", "path": "Список.Исполнитель" }
|
|
||||||
]},
|
|
||||||
{ "input": "Комментарий", "path": "Список.Комментарий" }
|
|
||||||
]}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Картинка-поле (picField)
|
|
||||||
|
|
||||||
PictureField, привязанный к булеву/числу, рисует иконку только при заданном `valuesPicture`:
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
|
||||||
|------|----------|
|
|
||||||
| `valuesPicture` | Ref картинки значения: `"StdPicture.Favorites"`, `"CommonPicture.X"` |
|
|
||||||
| `loadTransparent: true` | Скрыть кадр «нет значения» |
|
|
||||||
|
|
||||||
### Страницы (pages + page)
|
### Страницы (pages + page)
|
||||||
|
|
||||||
@@ -270,39 +188,18 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
| `command` | Имя команды формы → `Form.Command.Имя` |
|
| `command` | Имя команды формы → `Form.Command.Имя` |
|
||||||
| `stdCommand` | Стандартная команда: `"Close"` → `Form.StandardCommand.Close`; с точкой: `"Товары.Add"` → `Form.Item.Товары.StandardCommand.Add` |
|
| `stdCommand` | Стандартная команда: `"Close"` → `Form.StandardCommand.Close`; с точкой: `"Товары.Add"` → `Form.Item.Товары.StandardCommand.Add` |
|
||||||
| `defaultButton: true` | Кнопка по умолчанию |
|
| `defaultButton: true` | Кнопка по умолчанию |
|
||||||
| `type` | `"usual"`, `"hyperlink"`. По умолчанию `"usual"`. Конкретный XML-вид (UsualButton/Hyperlink/CommandBarButton/CommandBarHyperlink) подставляется автоматически по контексту |
|
| `type` | `"usual"`, `"hyperlink"`, `"commandBar"` |
|
||||||
| `picture` | Картинка кнопки |
|
| `picture` | Картинка кнопки |
|
||||||
| `representation` | `"Auto"`, `"Text"`, `"Picture"`, `"PictureAndText"` |
|
| `representation` | `"Auto"`, `"Text"`, `"Picture"`, `"PictureAndText"` |
|
||||||
| `locationInCommandBar` | `"Auto"`, `"InCommandBar"`, `"InAdditionalSubmenu"` |
|
| `locationInCommandBar` | `"Auto"`, `"InCommandBar"`, `"InAdditionalSubmenu"` |
|
||||||
|
|
||||||
### Командная панель (cmdBar)
|
### Командная панель (cmdBar)
|
||||||
|
|
||||||
Дополнительная пользовательская панель команд, размещается как обычный элемент в layout формы.
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `autofill: true` | Автозаполнение стандартными командами |
|
| `autofill: true` | Автозаполнение стандартными командами |
|
||||||
| `children: [...]` | Кнопки панели |
|
| `children: [...]` | Кнопки панели |
|
||||||
|
|
||||||
### Главная автокомандная панель формы (autoCmdBar)
|
|
||||||
|
|
||||||
Наполняет встроенную AutoCommandBar формы (id=-1) кастомными кнопками. Указывать только если нужно добавить свои кнопки на главную панель или явно управлять автозаполнением.
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
|
||||||
|------|----------|
|
|
||||||
| `autofill: true/false` | Автозаполнение стандартными командами |
|
|
||||||
| `horizontalAlign` | `"Left"` / `"Center"` / `"Right"` |
|
|
||||||
| `children: [...]` | Кнопки/popup |
|
|
||||||
|
|
||||||
```json
|
|
||||||
{ "autoCmdBar": "ФормаКоманднаяПанель", "autofill": true, "children": [
|
|
||||||
{ "button": "ИзменитьВыделенные", "command": "ИзменитьВыделенные",
|
|
||||||
"locationInCommandBar": "InAdditionalSubmenu" }
|
|
||||||
]}
|
|
||||||
```
|
|
||||||
|
|
||||||
Кнопки основных действий формы и подменю размещают здесь, а не в отдельной группе на форме. Отдельной кнопкой в layout — только если она логически привязана к конкретному полю или группе.
|
|
||||||
|
|
||||||
### Выпадающее меню (popup)
|
### Выпадающее меню (popup)
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
@@ -324,9 +221,6 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{ "name": "Объект", "type": "DataProcessorObject.Загрузка", "main": true }
|
{ "name": "Объект", "type": "DataProcessorObject.Загрузка", "main": true }
|
||||||
{ "name": "Список", "type": "DynamicList", "main": true, "settings": {
|
|
||||||
"mainTable": "Catalog.Номенклатура", "dynamicDataRead": true
|
|
||||||
}}
|
|
||||||
{ "name": "Итого", "type": "decimal(15,2)" }
|
{ "name": "Итого", "type": "decimal(15,2)" }
|
||||||
{ "name": "Таблица", "type": "ValueTable", "columns": [
|
{ "name": "Таблица", "type": "ValueTable", "columns": [
|
||||||
{ "name": "Номенклатура", "type": "CatalogRef.Номенклатура" },
|
{ "name": "Номенклатура", "type": "CatalogRef.Номенклатура" },
|
||||||
@@ -335,7 +229,6 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
```
|
```
|
||||||
|
|
||||||
- `savedData: true` — сохраняемые данные
|
- `savedData: true` — сохраняемые данные
|
||||||
- `main: true` — главный реквизит формы (например, основной `*Object.*`, `DynamicList`, `*RecordSet.*`)
|
|
||||||
|
|
||||||
### Команды (commands)
|
### Команды (commands)
|
||||||
|
|
||||||
@@ -348,8 +241,6 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
|
|
||||||
### Система типов
|
### Система типов
|
||||||
|
|
||||||
**Примитивные:**
|
|
||||||
|
|
||||||
| DSL | XML |
|
| DSL | XML |
|
||||||
|------------------------|----------------------------------------|
|
|------------------------|----------------------------------------|
|
||||||
| `"string"` / `"string(100)"` | `xs:string` + StringQualifiers |
|
| `"string"` / `"string(100)"` | `xs:string` + StringQualifiers |
|
||||||
@@ -357,38 +248,11 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
| `"decimal(10,0,nonneg)"` | с AllowedSign=Nonnegative |
|
| `"decimal(10,0,nonneg)"` | с AllowedSign=Nonnegative |
|
||||||
| `"boolean"` | `xs:boolean` |
|
| `"boolean"` | `xs:boolean` |
|
||||||
| `"date"` / `"dateTime"` / `"time"` | `xs:dateTime` + DateFractions |
|
| `"date"` / `"dateTime"` / `"time"` | `xs:dateTime` + DateFractions |
|
||||||
|
| `"CatalogRef.XXX"` | `cfg:CatalogRef.XXX` |
|
||||||
**Ссылочные и объектные (`cfg:Prefix.Name`):**
|
| `"DocumentRef.XXX"` | `cfg:DocumentRef.XXX` |
|
||||||
|
| `"ValueTable"` | `v8:ValueTable` |
|
||||||
| DSL | Описание |
|
| `"ValueList"` | `v8:ValueListType` |
|
||||||
|-----|----------|
|
| `"Type1 \| Type2"` | составной тип |
|
||||||
| `"CatalogRef.XXX"` / `"CatalogObject.XXX"` | Справочник |
|
|
||||||
| `"DocumentRef.XXX"` / `"DocumentObject.XXX"` | Документ |
|
|
||||||
| `"EnumRef.XXX"` | Перечисление |
|
|
||||||
| `"DataProcessorObject.XXX"` / `"ReportObject.XXX"` | Обработка / Отчёт |
|
|
||||||
| `"InformationRegisterRecordSet.XXX"` | Набор записей регистра сведений |
|
|
||||||
| `"AccumulationRegisterRecordSet.XXX"` | Набор записей регистра накопления |
|
|
||||||
| `"DynamicList"` | Динамический список |
|
|
||||||
|
|
||||||
Также допустимы: `ChartOfAccountsRef/Object`, `ChartOfCharacteristicTypesRef/Object`, `ChartOfCalculationTypesRef/Object`, `ExchangePlanRef/Object`, `BusinessProcessRef/Object`, `TaskRef/Object`, `AccountingRegisterRecordSet`, `InformationRegisterRecordManager`, `ConstantsSet`.
|
|
||||||
|
|
||||||
**Платформенные:**
|
|
||||||
|
|
||||||
| DSL | XML |
|
|
||||||
|-----|-----|
|
|
||||||
| `"ValueTable"` | `v8:ValueTable` |
|
|
||||||
| `"ValueTree"` | `v8:ValueTree` |
|
|
||||||
| `"ValueList"` | `v8:ValueListType` |
|
|
||||||
| `"TypeDescription"` | `v8:TypeDescription` |
|
|
||||||
| `"UUID"` | `v8:UUID` |
|
|
||||||
| `"FormattedString"` | `v8ui:FormattedString` |
|
|
||||||
| `"Picture"` / `"Color"` / `"Font"` | `v8ui:*` |
|
|
||||||
| `"DataCompositionSettings"` | `dcsset:DataCompositionSettings` |
|
|
||||||
| `"Type1 \| Type2"` | составной тип (несколько `<v8:Type>`) |
|
|
||||||
|
|
||||||
**Недопустимые типы (XDTO-ошибка при загрузке):**
|
|
||||||
|
|
||||||
> `FormDataStructure`, `FormDataCollection`, `FormDataTree` — runtime-типы 1С, не существуют в XML-схеме. Вместо них используйте `CatalogObject.XXX`, `DocumentObject.XXX`, `DataProcessorObject.XXX`, `ValueTable`, `ValueTree`.
|
|
||||||
|
|
||||||
## Связки: элемент + реквизит
|
## Связки: элемент + реквизит
|
||||||
|
|
||||||
@@ -441,13 +305,13 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
"events": { "OnCreateAtServer": "ПриСозданииНаСервере" },
|
"events": { "OnCreateAtServer": "ПриСозданииНаСервере" },
|
||||||
"elements": [
|
"elements": [
|
||||||
{ "group": "horizontal", "name": "ГруппаФайл", "children": [
|
{ "group": "horizontal", "name": "ГруппаФайл", "children": [
|
||||||
{ "input": "ИмяФайла", "path": "ИмяФайла", "title": "Файл", "inputHint": "Выберите файл...", "choiceButton": true, "events": { "StartChoice": "ИмяФайлаНачалоВыбора" } },
|
{ "input": "ИмяФайла", "path": "ИмяФайла", "title": "Файл", "inputHint": "Выберите файл...", "choiceButton": true, "on": ["StartChoice"] },
|
||||||
{ "check": "ПерваяСтрокаЗаголовок", "path": "ПерваяСтрокаЗаголовок" }
|
{ "check": "ПерваяСтрокаЗаголовок", "path": "ПерваяСтрокаЗаголовок" }
|
||||||
]},
|
]},
|
||||||
{ "input": "Результат", "path": "Результат", "multiLine": true, "height": 8, "readOnly": true, "title": "Лог" },
|
{ "input": "Результат", "path": "Результат", "multiLine": true, "height": 8, "readOnly": true, "title": "Лог" },
|
||||||
{ "autoCmdBar": "ФормаКоманднаяПанель", "children": [
|
{ "group": "horizontal", "name": "ГруппаКнопок", "children": [
|
||||||
{ "button": "Загрузить", "command": "Загрузить", "defaultButton": true },
|
{ "button": "Загрузить", "command": "Загрузить", "defaultButton": true },
|
||||||
{ "button": "Закрыть", "stdCommand": "Close" }
|
{ "button": "Закрыть", "stdCommand": "Close" }
|
||||||
]}
|
]}
|
||||||
],
|
],
|
||||||
"attributes": [
|
"attributes": [
|
||||||
@@ -501,8 +365,8 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
"title": "Просмотр данных",
|
"title": "Просмотр данных",
|
||||||
"elements": [
|
"elements": [
|
||||||
{ "group": "horizontal", "name": "Фильтр", "children": [
|
{ "group": "horizontal", "name": "Фильтр", "children": [
|
||||||
{ "input": "Период", "path": "Период", "events": { "OnChange": "ПериодПриИзменении" } },
|
{ "input": "Период", "path": "Период", "on": ["OnChange"] },
|
||||||
{ "input": "Организация", "path": "Организация", "events": { "OnChange": "ОрганизацияПриИзменении" } }
|
{ "input": "Организация", "path": "Организация", "on": ["OnChange"] }
|
||||||
]},
|
]},
|
||||||
{ "table": "Данные", "path": "Данные", "changeRowSet": true, "columns": [
|
{ "table": "Данные", "path": "Данные", "changeRowSet": true, "columns": [
|
||||||
{ "input": "Дата", "path": "Данные.Дата" },
|
{ "input": "Дата", "path": "Данные.Дата" },
|
||||||
@@ -523,26 +387,10 @@ PictureField, привязанный к булеву/числу, рисует и
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Продвинутые конструкции (по необходимости)
|
|
||||||
|
|
||||||
Описанного выше хватает для большинства форм. Под конкретную задачу подгрузите файл из `references/`:
|
|
||||||
|
|
||||||
- `dynamic-list.md` — форма списка: источник, отбор, сортировка, группировки, параметры запроса
|
|
||||||
- `appearance.md` — условное и статическое оформление элементов (цвета/шрифты/рамки)
|
|
||||||
- `choice-params.md` — параметры и связи выбора у полей ввода
|
|
||||||
- `command-interface.md` — командный интерфейс формы
|
|
||||||
- `roles-access.md` — пользовательская видимость и доступ по ролям
|
|
||||||
- `companion-panels.md` — контент расширенной подсказки и контекстного меню
|
|
||||||
- `special-fields.md` — поля документа/датчика (HTML, текст, индикатор, ползунок)
|
|
||||||
- `charts.md` — диаграммы и планировщик
|
|
||||||
- `report-form.md` — свойства формы отчёта
|
|
||||||
- `type-system-advanced.md` — наборы и составные типы
|
|
||||||
- `table-advanced.md` — расширенные свойства таблиц
|
|
||||||
- `layout-advanced.md` — тонкая компоновка и геометрия
|
|
||||||
|
|
||||||
## Автогенерация
|
## Автогенерация
|
||||||
|
|
||||||
- **Companion-элементы**: ContextMenu, ExtendedTooltip и др. создаются автоматически
|
- **Companion-элементы**: ContextMenu, ExtendedTooltip и др. создаются автоматически
|
||||||
|
- **Обработчики событий**: `"on": ["OnChange"]` → `ОрганизацияПриИзменении`
|
||||||
- **Namespace**: все 17 namespace-деклараций
|
- **Namespace**: все 17 namespace-деклараций
|
||||||
- **ID**: последовательная нумерация, AutoCommandBar = id="-1"
|
- **ID**: последовательная нумерация, AutoCommandBar = id="-1"
|
||||||
- **Unknown keys**: выводится предупреждение о нераспознанных ключах
|
- **Unknown keys**: выводится предупреждение о нераспознанных ключах
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -29,7 +29,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/form-edit/scripts/form-edit.py" -FormPath "<путь>" -JsonPath "<путь>"
|
powershell.exe -NoProfile -File .claude/skills/form-edit/scripts/form-edit.ps1 -FormPath "<путь>" -JsonPath "<путь>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## JSON формат
|
## JSON формат
|
||||||
@@ -133,6 +133,33 @@ python ".opencode/skills/form-edit/scripts/form-edit.py" -FormPath "<путь>"
|
|||||||
|
|
||||||
Все extension-секции опциональны — без них навык работает как с обычными формами.
|
Все extension-секции опциональны — без них навык работает как с обычными формами.
|
||||||
|
|
||||||
|
## Вывод
|
||||||
|
|
||||||
|
```
|
||||||
|
=== form-edit: Форма ===
|
||||||
|
|
||||||
|
[EXTENSION] BaseForm detected — IDs start at 1000000+
|
||||||
|
|
||||||
|
Added form events:
|
||||||
|
+ OnCreateAtServer[After] -> Расш1_ПриСозданииПосле
|
||||||
|
|
||||||
|
Added elements (into ГруппаШапка, after Контрагент):
|
||||||
|
+ [Input] Склад -> Объект.Склад {OnChange}
|
||||||
|
|
||||||
|
Added attributes:
|
||||||
|
+ СуммаИтого: decimal(15,2) (id=1000000)
|
||||||
|
|
||||||
|
---
|
||||||
|
Total: 1 form event(s), 1 element(s) (+2 companions), 1 attribute(s)
|
||||||
|
Run /form-validate to verify.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Когда использовать
|
||||||
|
|
||||||
|
- **После `/form-compile`**: добавить элементы, которые не были в исходном JSON
|
||||||
|
- **Модификация существующих форм**: добавить поле, реквизит или команду в форму из конфигурации
|
||||||
|
- **Пакетное добавление**: один JSON может содержать элементы + реквизиты + команды
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
|
|
||||||
1. `/form-info` — посмотреть текущую структуру формы
|
1. `/form-info` — посмотреть текущую структуру формы
|
||||||
+4
-175
@@ -1,8 +1,7 @@
|
|||||||
# form-edit v1.3 — Edit 1C managed form elements
|
# form-edit v1.0 — Edit 1C managed form elements
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$FormPath,
|
[string]$FormPath,
|
||||||
|
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -12,124 +11,6 @@ param(
|
|||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[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 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 {}
|
|
||||||
$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 (-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 Form.xml ===
|
# === 1. Load Form.xml ===
|
||||||
|
|
||||||
if (-not (Test-Path $FormPath)) {
|
if (-not (Test-Path $FormPath)) {
|
||||||
@@ -142,7 +23,6 @@ if (-not (Test-Path $JsonPath)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$resolvedFormPath = (Resolve-Path $FormPath).Path
|
$resolvedFormPath = (Resolve-Path $FormPath).Path
|
||||||
Assert-EditAllowed $resolvedFormPath 'editable'
|
|
||||||
$xmlDoc = New-Object System.Xml.XmlDocument
|
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||||
$xmlDoc.PreserveWhitespace = $true
|
$xmlDoc.PreserveWhitespace = $true
|
||||||
try {
|
try {
|
||||||
@@ -410,16 +290,6 @@ function Get-ElementName {
|
|||||||
return "$($el.$typeKey)"
|
return "$($el.$typeKey)"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Уникальность имён внутри JSON-определения (1С: своя коллекция — свой неймспейс).
|
|
||||||
function Assert-EditUnique {
|
|
||||||
param([string]$name, [hashtable]$seen, [string]$ctx)
|
|
||||||
if ($seen.ContainsKey($name)) {
|
|
||||||
Write-Host "[ERROR] Duplicate $ctx '$name' in JSON definition — names must be unique in 1C form"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
$seen[$name] = $true
|
|
||||||
}
|
|
||||||
|
|
||||||
$script:knownEvents = @{
|
$script:knownEvents = @{
|
||||||
"input" = @("OnChange","StartChoice","ChoiceProcessing","AutoComplete","TextEditEnd","Clearing","Creating","EditTextChange")
|
"input" = @("OnChange","StartChoice","ChoiceProcessing","AutoComplete","TextEditEnd","Clearing","Creating","EditTextChange")
|
||||||
"check" = @("OnChange")
|
"check" = @("OnChange")
|
||||||
@@ -993,31 +863,17 @@ if ($def.elements -and $def.elements.Count -gt 0) {
|
|||||||
# Detect indent level
|
# Detect indent level
|
||||||
$childIndent = Get-ChildIndent $targetCI
|
$childIndent = Get-ChildIndent $targetCI
|
||||||
|
|
||||||
# Имена элементов уникальны (требование 1С). Сначала — внутри самого JSON-определения
|
# Check for duplicate element names
|
||||||
# (рекурсивно по children/columns).
|
|
||||||
$elemTypeKeys = @("group","input","check","label","labelField","table","pages","page","button","picture","picField","calendar","cmdBar","popup")
|
|
||||||
function Walk-ElemNames($el, [hashtable]$seen) {
|
|
||||||
$tk = $null
|
|
||||||
foreach ($k in $elemTypeKeys) { if ($el.$k -ne $null) { $tk = $k; break } }
|
|
||||||
if ($tk) { Assert-EditUnique -name (Get-ElementName -el $el -typeKey $tk) -seen $seen -ctx 'element name' }
|
|
||||||
if ($el.children) { foreach ($c in $el.children) { Walk-ElemNames $c $seen } }
|
|
||||||
if ($el.columns) { foreach ($c in $el.columns) { Walk-ElemNames $c $seen } }
|
|
||||||
}
|
|
||||||
$dslElemNames = @{}
|
|
||||||
foreach ($el in $def.elements) { Walk-ElemNames $el $dslElemNames }
|
|
||||||
|
|
||||||
# Затем — против уже существующих элементов формы (дубль = битый XML, форма не откроется)
|
|
||||||
foreach ($el in $def.elements) {
|
foreach ($el in $def.elements) {
|
||||||
$typeKey = $null
|
$typeKey = $null
|
||||||
foreach ($key in $elemTypeKeys) {
|
foreach ($key in @("group","input","check","label","labelField","table","pages","page","button","picture","picField","calendar","cmdBar","popup")) {
|
||||||
if ($el.$key -ne $null) { $typeKey = $key; break }
|
if ($el.$key -ne $null) { $typeKey = $key; break }
|
||||||
}
|
}
|
||||||
if ($typeKey) {
|
if ($typeKey) {
|
||||||
$elName = Get-ElementName -el $el -typeKey $typeKey
|
$elName = Get-ElementName -el $el -typeKey $typeKey
|
||||||
$existing = Find-Element $rootCI $elName
|
$existing = Find-Element $rootCI $elName
|
||||||
if ($existing) {
|
if ($existing) {
|
||||||
Write-Host "[ERROR] Element '$elName' already exists in form (id=$($existing.GetAttribute('id'))) — element names must be unique"
|
Write-Host "[WARN] Element '$elName' already exists in form (id=$($existing.GetAttribute('id')))"
|
||||||
exit 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1096,22 +952,6 @@ if ($def.attributes -and $def.attributes.Count -gt 0) {
|
|||||||
$attrChildIndent = Get-ChildIndent $attrsSection
|
$attrChildIndent = Get-ChildIndent $attrsSection
|
||||||
if (-not $attrChildIndent -or $attrChildIndent -eq "") { $attrChildIndent = "`t`t" }
|
if (-not $attrChildIndent -or $attrChildIndent -eq "") { $attrChildIndent = "`t`t" }
|
||||||
|
|
||||||
# Уникальность имён реквизитов: внутри JSON-определения (+ колонки в пределах реквизита) и
|
|
||||||
# против уже существующих реквизитов формы.
|
|
||||||
$dslAttrNames = @{}
|
|
||||||
foreach ($attr in $def.attributes) {
|
|
||||||
Assert-EditUnique -name "$($attr.name)" -seen $dslAttrNames -ctx 'attribute name'
|
|
||||||
if ($attr.columns) {
|
|
||||||
$dslColNames = @{}
|
|
||||||
foreach ($col in $attr.columns) { Assert-EditUnique -name "$($col.name)" -seen $dslColNames -ctx "column name of '$($attr.name)'" }
|
|
||||||
}
|
|
||||||
$existingAttr = $attrsSection.SelectSingleNode("f:Attribute[@name='$($attr.name)']", $nsMgr)
|
|
||||||
if ($existingAttr) {
|
|
||||||
Write-Host "[ERROR] Attribute '$($attr.name)' already exists in form — attribute names must be unique"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Generate attribute fragments
|
# Generate attribute fragments
|
||||||
$script:xml = New-Object System.Text.StringBuilder 2048
|
$script:xml = New-Object System.Text.StringBuilder 2048
|
||||||
X "<_F $allNsDecl>"
|
X "<_F $allNsDecl>"
|
||||||
@@ -1180,17 +1020,6 @@ if ($def.commands -and $def.commands.Count -gt 0) {
|
|||||||
$cmdChildIndent = Get-ChildIndent $cmdsSection
|
$cmdChildIndent = Get-ChildIndent $cmdsSection
|
||||||
if (-not $cmdChildIndent -or $cmdChildIndent -eq "") { $cmdChildIndent = "`t`t" }
|
if (-not $cmdChildIndent -or $cmdChildIndent -eq "") { $cmdChildIndent = "`t`t" }
|
||||||
|
|
||||||
# Уникальность имён команд: внутри JSON-определения и против существующих команд формы.
|
|
||||||
$dslCmdNames = @{}
|
|
||||||
foreach ($cmd in $def.commands) {
|
|
||||||
Assert-EditUnique -name "$($cmd.name)" -seen $dslCmdNames -ctx 'command name'
|
|
||||||
$existingCmd = $cmdsSection.SelectSingleNode("f:Command[@name='$($cmd.name)']", $nsMgr)
|
|
||||||
if ($existingCmd) {
|
|
||||||
Write-Host "[ERROR] Command '$($cmd.name)' already exists in form — command names must be unique"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Generate command fragments
|
# Generate command fragments
|
||||||
$script:xml = New-Object System.Text.StringBuilder 1024
|
$script:xml = New-Object System.Text.StringBuilder 1024
|
||||||
X "<_F $allNsDecl>"
|
X "<_F $allNsDecl>"
|
||||||
+8
-227
@@ -1,4 +1,4 @@
|
|||||||
# form-edit v1.3 — Edit 1C managed form elements (Python port)
|
# form-edit v1.0 — Edit 1C managed form elements (Python port)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
@@ -11,169 +11,10 @@ from lxml import etree
|
|||||||
sys.stdout.reconfigure(encoding="utf-8")
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
sys.stderr.reconfigure(encoding="utf-8")
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
|
||||||
# ============================================================
|
|
||||||
# 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_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)
|
|
||||||
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 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
|
|
||||||
|
|
||||||
|
|
||||||
# ── arg parsing ──────────────────────────────────────────────
|
# ── arg parsing ──────────────────────────────────────────────
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False)
|
parser = argparse.ArgumentParser(allow_abbrev=False)
|
||||||
parser.add_argument("-FormPath", "-Path", required=True)
|
parser.add_argument("-FormPath", required=True)
|
||||||
parser.add_argument("-JsonPath", required=True)
|
parser.add_argument("-JsonPath", required=True)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
@@ -222,7 +63,6 @@ if not os.path.exists(json_path):
|
|||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
resolved_form_path = os.path.abspath(form_path)
|
resolved_form_path = os.path.abspath(form_path)
|
||||||
assert_edit_allowed(resolved_form_path, "editable")
|
|
||||||
xml_parser = etree.XMLParser(remove_blank_text=False)
|
xml_parser = etree.XMLParser(remove_blank_text=False)
|
||||||
try:
|
try:
|
||||||
tree = etree.parse(resolved_form_path, xml_parser)
|
tree = etree.parse(resolved_form_path, xml_parser)
|
||||||
@@ -525,14 +365,6 @@ def get_element_name(el, type_key):
|
|||||||
return str(el[type_key])
|
return str(el[type_key])
|
||||||
|
|
||||||
|
|
||||||
def _assert_edit_unique(name, seen, ctx):
|
|
||||||
# Уникальность имён внутри JSON-определения (1С: своя коллекция — свой неймспейс).
|
|
||||||
if name in seen:
|
|
||||||
print(f"[ERROR] Duplicate {ctx} '{name}' in JSON definition — names must be unique in 1C form")
|
|
||||||
sys.exit(1)
|
|
||||||
seen.add(name)
|
|
||||||
|
|
||||||
|
|
||||||
known_events = {
|
known_events = {
|
||||||
"input": ["OnChange", "StartChoice", "ChoiceProcessing", "AutoComplete", "TextEditEnd", "Clearing", "Creating", "EditTextChange"],
|
"input": ["OnChange", "StartChoice", "ChoiceProcessing", "AutoComplete", "TextEditEnd", "Clearing", "Creating", "EditTextChange"],
|
||||||
"check": ["OnChange"],
|
"check": ["OnChange"],
|
||||||
@@ -1141,41 +973,14 @@ if elements_list:
|
|||||||
target_ci = root_ci
|
target_ci = root_ci
|
||||||
|
|
||||||
if target_ci is None:
|
if target_ci is None:
|
||||||
# Create ChildItems section in form — insert after Events or AutoCommandBar
|
# Create ChildItems section in form
|
||||||
target_ci = etree.Element(f"{{{FORM_NS}}}ChildItems")
|
target_ci = etree.SubElement(root, f"{{{FORM_NS}}}ChildItems")
|
||||||
insert_after = root.find("f:Events", NS)
|
|
||||||
if insert_after is None:
|
|
||||||
insert_after = root.find("f:AutoCommandBar", NS)
|
|
||||||
if insert_after is not None:
|
|
||||||
idx = list(root).index(insert_after) + 1
|
|
||||||
root.insert(idx, target_ci)
|
|
||||||
else:
|
|
||||||
root.append(target_ci)
|
|
||||||
root_ci = target_ci
|
root_ci = target_ci
|
||||||
|
|
||||||
# Detect indent level
|
# Detect indent level
|
||||||
child_indent = get_child_indent(target_ci)
|
child_indent = get_child_indent(target_ci)
|
||||||
|
|
||||||
# Имена элементов уникальны (требование 1С). Сначала — внутри самого JSON-определения
|
# Check for duplicate element names
|
||||||
# (рекурсивно по children/columns).
|
|
||||||
def _walk_elem_names(el, seen):
|
|
||||||
tk = None
|
|
||||||
for key in ELEMENT_KEYS:
|
|
||||||
if key in el and el[key] is not None:
|
|
||||||
tk = key
|
|
||||||
break
|
|
||||||
if tk:
|
|
||||||
_assert_edit_unique(get_element_name(el, tk), seen, "element name")
|
|
||||||
for c in el.get("children", []):
|
|
||||||
_walk_elem_names(c, seen)
|
|
||||||
for c in el.get("columns", []):
|
|
||||||
_walk_elem_names(c, seen)
|
|
||||||
|
|
||||||
dsl_elem_names = set()
|
|
||||||
for el in elements_list:
|
|
||||||
_walk_elem_names(el, dsl_elem_names)
|
|
||||||
|
|
||||||
# Затем — против уже существующих элементов формы (дубль = битый XML, форма не откроется).
|
|
||||||
for el in elements_list:
|
for el in elements_list:
|
||||||
type_key = None
|
type_key = None
|
||||||
for key in ELEMENT_KEYS:
|
for key in ELEMENT_KEYS:
|
||||||
@@ -1186,8 +991,7 @@ if elements_list:
|
|||||||
el_name = get_element_name(el, type_key)
|
el_name = get_element_name(el, type_key)
|
||||||
existing = find_element(root_ci, el_name) if root_ci is not None else None
|
existing = find_element(root_ci, el_name) if root_ci is not None else None
|
||||||
if existing is not None:
|
if existing is not None:
|
||||||
print(f"[ERROR] Element '{el_name}' already exists in form (id={existing.get('id')}) — element names must be unique")
|
print(f"[WARN] Element '{el_name}' already exists in form (id={existing.get('id')})")
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Remember starting element ID for companion counting
|
# Remember starting element ID for companion counting
|
||||||
start_elem_id = next_elem_id
|
start_elem_id = next_elem_id
|
||||||
@@ -1243,19 +1047,6 @@ if attrs_list:
|
|||||||
if not attr_child_indent:
|
if not attr_child_indent:
|
||||||
attr_child_indent = "\t\t"
|
attr_child_indent = "\t\t"
|
||||||
|
|
||||||
# Уникальность имён реквизитов: внутри JSON-определения (+ колонки в пределах реквизита) и
|
|
||||||
# против уже существующих реквизитов формы.
|
|
||||||
dsl_attr_names = set()
|
|
||||||
for attr in attrs_list:
|
|
||||||
_assert_edit_unique(str(attr["name"]), dsl_attr_names, "attribute name")
|
|
||||||
if attr.get("columns"):
|
|
||||||
dsl_col_names = set()
|
|
||||||
for col in attr["columns"]:
|
|
||||||
_assert_edit_unique(str(col["name"]), dsl_col_names, f"column name of '{attr['name']}'")
|
|
||||||
if attrs_section.find(f"f:Attribute[@name='{attr['name']}']", NS) is not None:
|
|
||||||
print(f"[ERROR] Attribute '{attr['name']}' already exists in form — attribute names must be unique")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
# Generate attribute fragments
|
# Generate attribute fragments
|
||||||
xml_lines.clear()
|
xml_lines.clear()
|
||||||
X(f"<_F {ALL_NS_DECL}>")
|
X(f"<_F {ALL_NS_DECL}>")
|
||||||
@@ -1317,14 +1108,6 @@ if cmds_list:
|
|||||||
if not cmd_child_indent:
|
if not cmd_child_indent:
|
||||||
cmd_child_indent = "\t\t"
|
cmd_child_indent = "\t\t"
|
||||||
|
|
||||||
# Уникальность имён команд: внутри JSON-определения и против существующих команд формы.
|
|
||||||
dsl_cmd_names = set()
|
|
||||||
for cmd in cmds_list:
|
|
||||||
_assert_edit_unique(str(cmd["name"]), dsl_cmd_names, "command name")
|
|
||||||
if cmds_section.find(f"f:Command[@name='{cmd['name']}']", NS) is not None:
|
|
||||||
print(f"[ERROR] Command '{cmd['name']}' already exists in form — command names must be unique")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
xml_lines.clear()
|
xml_lines.clear()
|
||||||
X(f"<_F {ALL_NS_DECL}>")
|
X(f"<_F {ALL_NS_DECL}>")
|
||||||
for cmd in cmds_list:
|
for cmd in cmds_list:
|
||||||
@@ -1459,10 +1242,8 @@ if elem_events_list:
|
|||||||
# ── 13. Save ────────────────────────────────────────────────
|
# ── 13. Save ────────────────────────────────────────────────
|
||||||
|
|
||||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
# Fix XML declaration quotes
|
# Fix encoding declaration case
|
||||||
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
if not xml_bytes.endswith(b"\n"):
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
# Write with BOM
|
# Write with BOM
|
||||||
with open(resolved_form_path, "wb") as f:
|
with open(resolved_form_path, "wb") as f:
|
||||||
f.write(b'\xef\xbb\xbf')
|
f.write(b'\xef\xbb\xbf')
|
||||||
@@ -15,7 +15,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/form-info/scripts/form-info.py" -FormPath "<путь к Form.xml>"
|
powershell.exe -NoProfile -File .claude/skills/form-info/scripts/form-info.ps1 -FormPath "<путь к Form.xml>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Параметры
|
## Параметры
|
||||||
+2
-151
@@ -1,8 +1,7 @@
|
|||||||
# form-info v1.4 — Analyze 1C managed form structure
|
# form-info v1.1 — Analyze 1C managed form structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory=$true)]
|
[Parameter(Mandatory=$true)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$FormPath,
|
[string]$FormPath,
|
||||||
[int]$Limit = 150,
|
[int]$Limit = 150,
|
||||||
[int]$Offset = 0,
|
[int]$Offset = 0,
|
||||||
@@ -12,29 +11,7 @@ param(
|
|||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
# --- Resolve FormPath ---
|
# --- Validate path ---
|
||||||
if (-not [System.IO.Path]::IsPathRooted($FormPath)) {
|
|
||||||
$FormPath = Join-Path (Get-Location).Path $FormPath
|
|
||||||
}
|
|
||||||
# A: Directory → Ext/Form.xml
|
|
||||||
if (Test-Path $FormPath -PathType Container) {
|
|
||||||
$FormPath = Join-Path (Join-Path $FormPath "Ext") "Form.xml"
|
|
||||||
}
|
|
||||||
# B1: Missing Ext/ (Forms/Форма/Form.xml → Forms/Форма/Ext/Form.xml)
|
|
||||||
if (-not (Test-Path $FormPath)) {
|
|
||||||
$fn = [System.IO.Path]::GetFileName($FormPath)
|
|
||||||
if ($fn -eq "Form.xml") {
|
|
||||||
$c = Join-Path (Join-Path (Split-Path $FormPath) "Ext") $fn
|
|
||||||
if (Test-Path $c) { $FormPath = $c }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
# B2: Descriptor (Forms/Форма.xml → Forms/Форма/Ext/Form.xml)
|
|
||||||
if (-not (Test-Path $FormPath) -and $FormPath.EndsWith(".xml")) {
|
|
||||||
$stem = [System.IO.Path]::GetFileNameWithoutExtension($FormPath)
|
|
||||||
$dir = Split-Path $FormPath
|
|
||||||
$c = Join-Path (Join-Path (Join-Path $dir $stem) "Ext") "Form.xml"
|
|
||||||
if (Test-Path $c) { $FormPath = $c }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not (Test-Path $FormPath)) {
|
if (-not (Test-Path $FormPath)) {
|
||||||
Write-Error "File not found: $FormPath"
|
Write-Error "File not found: $FormPath"
|
||||||
@@ -368,69 +345,6 @@ if ($formsIdx -ge 0 -and ($formsIdx + 1) -lt $parts.Count) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Support status (Ext/ParentConfigurations.bin) ---
|
|
||||||
# See docs/1c-support-state-spec.md. Walks up from the target path, taking the
|
|
||||||
# uuid of the nearest element meta-xml (form/template/etc.) and the config root
|
|
||||||
# bin. Never throws — degrades to "не на поддержке".
|
|
||||||
function Get-SupportStatusForPath([string]$targetPath) {
|
|
||||||
try {
|
|
||||||
$rp = (Resolve-Path $targetPath).Path
|
|
||||||
$elemUuid = $null
|
|
||||||
$binPath = $null
|
|
||||||
# Reads the uuid of the first metadata element in an .xml file (or $null).
|
|
||||||
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
|
|
||||||
}
|
|
||||||
# The target file itself may be the element meta-xml (e.g. Subsystems/X.xml).
|
|
||||||
$elemUuid = Get-RootUuid $rp
|
|
||||||
$d = [System.IO.Path]::GetDirectoryName($rp)
|
|
||||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
|
||||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
|
||||||
if (-not $binPath) {
|
|
||||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
|
||||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $binPath = $cand }
|
|
||||||
}
|
|
||||||
if ($elemUuid -and $binPath) { break }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
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)
|
|
||||||
$h = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
|
||||||
if (-not $h.Success) { return "не на поддержке" }
|
|
||||||
$G = [int]$h.Groups[1].Value
|
|
||||||
$K = [int]$h.Groups[2].Value
|
|
||||||
if ($K -eq 0) { return "снято с поддержки (правки свободны)" }
|
|
||||||
if ($G -eq 1) { return "конфигурация read-only (возможность изменения выключена) — правки невозможны без включения" }
|
|
||||||
if (-not $elemUuid) { return "не на поддержке" }
|
|
||||||
$u = [regex]::Escape($elemUuid.ToLower())
|
|
||||||
$best = $null
|
|
||||||
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 }
|
|
||||||
}
|
|
||||||
if ($null -eq $best) { return "не на поддержке" }
|
|
||||||
switch ($best) {
|
|
||||||
0 { return "на замке — прямая правка сломает обновления; дорабатывай через cfe-* либо включи редактирование объекта" }
|
|
||||||
1 { return "редактируется с сохранением поддержки" }
|
|
||||||
2 { return "снято с поддержки (правки свободны)" }
|
|
||||||
}
|
|
||||||
return "не на поддержке"
|
|
||||||
} catch { return "не на поддержке" }
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Collect output ---
|
# --- Collect output ---
|
||||||
|
|
||||||
$lines = @()
|
$lines = @()
|
||||||
@@ -448,7 +362,6 @@ if ($formTitle) { $header += " — `"$formTitle`"" }
|
|||||||
if ($objectContext) { $header += " ($objectContext)" }
|
if ($objectContext) { $header += " ($objectContext)" }
|
||||||
$header += " ==="
|
$header += " ==="
|
||||||
$lines += $header
|
$lines += $header
|
||||||
$lines += "Поддержка: $(Get-SupportStatusForPath $FormPath)"
|
|
||||||
|
|
||||||
# --- Form properties (Title excluded — shown in header) ---
|
# --- Form properties (Title excluded — shown in header) ---
|
||||||
|
|
||||||
@@ -500,62 +413,6 @@ if ($formEvents -and $formEvents.HasChildNodes) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Main AutoCommandBar (form's id=-1 panel) ---
|
|
||||||
|
|
||||||
function Format-MainAcb($acbNode) {
|
|
||||||
if (-not $acbNode) { return @() }
|
|
||||||
$result = @()
|
|
||||||
$autofillNode = $acbNode.SelectSingleNode("d:Autofill", $ns)
|
|
||||||
$autofill = $true
|
|
||||||
if ($autofillNode -and $autofillNode.InnerText -eq "false") { $autofill = $false }
|
|
||||||
$halignNode = $acbNode.SelectSingleNode("d:HorizontalAlign", $ns)
|
|
||||||
$flags = @()
|
|
||||||
$flags += if ($autofill) { "autofill" } else { "no-autofill" }
|
|
||||||
if ($halignNode) { $flags += "align=$($halignNode.InnerText)" }
|
|
||||||
$header = "AutoCommandBar [$($flags -join ', ')]"
|
|
||||||
$childItemsNode = $acbNode.SelectSingleNode("d:ChildItems", $ns)
|
|
||||||
$buttons = @()
|
|
||||||
if ($childItemsNode) {
|
|
||||||
foreach ($btn in $childItemsNode.ChildNodes) {
|
|
||||||
if ($btn.NodeType -ne "Element") { continue }
|
|
||||||
if ($skipElements.ContainsKey($btn.LocalName)) { continue }
|
|
||||||
$bName = $btn.GetAttribute("name")
|
|
||||||
$cmdNode = $btn.SelectSingleNode("d:CommandName", $ns)
|
|
||||||
$cmdRef = if ($cmdNode) { $cmdNode.InnerText } else { "" }
|
|
||||||
$locNode = $btn.SelectSingleNode("d:LocationInCommandBar", $ns)
|
|
||||||
$locStr = if ($locNode) { " [$($locNode.InnerText)]" } else { "" }
|
|
||||||
$tag = Get-ElementTag $btn
|
|
||||||
if ($cmdRef) {
|
|
||||||
$buttons += " $tag $bName -> $cmdRef$locStr"
|
|
||||||
} else {
|
|
||||||
$buttons += " $tag $bName$locStr"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($buttons.Count -eq 0 -and $autofill -and -not $halignNode) {
|
|
||||||
# Default empty panel — terse one-liner
|
|
||||||
return @("AutoCommandBar [autofill]")
|
|
||||||
}
|
|
||||||
$result += $header
|
|
||||||
$result += $buttons
|
|
||||||
return $result
|
|
||||||
}
|
|
||||||
|
|
||||||
# Determine position from CommandBarLocation form property
|
|
||||||
$cbLocNode = $root.SelectSingleNode("d:CommandBarLocation", $ns)
|
|
||||||
$cbLoc = if ($cbLocNode) { $cbLocNode.InnerText } else { "Auto" }
|
|
||||||
$mainAcbNode = $root.SelectSingleNode("d:AutoCommandBar", $ns)
|
|
||||||
$acbLines = @()
|
|
||||||
if ($cbLoc -ne "None" -and $mainAcbNode) {
|
|
||||||
$acbLines = Format-MainAcb $mainAcbNode
|
|
||||||
}
|
|
||||||
|
|
||||||
# AutoCommandBar above Elements (Auto/Top)
|
|
||||||
if ($acbLines.Count -gt 0 -and ($cbLoc -eq "Auto" -or $cbLoc -eq "Top")) {
|
|
||||||
$lines += ""
|
|
||||||
$lines += $acbLines
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Element tree ---
|
# --- Element tree ---
|
||||||
|
|
||||||
$childItems = $root.SelectSingleNode("d:ChildItems", $ns)
|
$childItems = $root.SelectSingleNode("d:ChildItems", $ns)
|
||||||
@@ -566,12 +423,6 @@ if ($childItems) {
|
|||||||
$lines += $treeLines.ToArray()
|
$lines += $treeLines.ToArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
# AutoCommandBar below Elements (Bottom)
|
|
||||||
if ($acbLines.Count -gt 0 -and $cbLoc -eq "Bottom") {
|
|
||||||
$lines += ""
|
|
||||||
$lines += $acbLines
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Attributes ---
|
# --- Attributes ---
|
||||||
|
|
||||||
$attrsNode = $root.SelectSingleNode("d:Attributes", $ns)
|
$attrsNode = $root.SelectSingleNode("d:Attributes", $ns)
|
||||||
+3
-144
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-info v1.4 — Analyze 1C managed form structure
|
# form-info v1.1 — Analyze 1C managed form structure
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -336,85 +336,13 @@ def build_tree(child_items_node, prefix, tree_lines, expand="", state=None):
|
|||||||
build_tree(ci, prefix + continuation, tree_lines, expand, state)
|
build_tree(ci, prefix + continuation, tree_lines, expand, state)
|
||||||
|
|
||||||
|
|
||||||
# --- Support status (Ext/ParentConfigurations.bin) ---
|
|
||||||
# See docs/1c-support-state-spec.md. Walks up from the target path, taking the
|
|
||||||
# uuid of the nearest element meta-xml and the config root bin. Never throws —
|
|
||||||
# degrades to "не на поддержке".
|
|
||||||
def get_support_status_for_path(target_path):
|
|
||||||
try:
|
|
||||||
def 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:
|
|
||||||
pass
|
|
||||||
return None
|
|
||||||
rp = os.path.abspath(target_path)
|
|
||||||
# The target file itself may be the element meta-xml (e.g. Subsystems/X.xml).
|
|
||||||
elem_uuid = root_uuid(rp)
|
|
||||||
bin_path = None
|
|
||||||
d = os.path.dirname(rp)
|
|
||||||
for _ in range(12):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
if not elem_uuid:
|
|
||||||
elem_uuid = root_uuid(d + ".xml")
|
|
||||||
if not bin_path:
|
|
||||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
|
||||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
|
||||||
bin_path = cand
|
|
||||||
if elem_uuid and bin_path:
|
|
||||||
break
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
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 "снято с поддержки (правки свободны)"
|
|
||||||
if g == 1:
|
|
||||||
return "конфигурация read-only (возможность изменения выключена) — правки невозможны без включения"
|
|
||||||
if not elem_uuid:
|
|
||||||
return "не на поддержке"
|
|
||||||
best = None
|
|
||||||
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
|
|
||||||
if best is None:
|
|
||||||
return "не на поддержке"
|
|
||||||
return {
|
|
||||||
0: "на замке — прямая правка сломает обновления; дорабатывай через cfe-* либо включи редактирование объекта",
|
|
||||||
1: "редактируется с сохранением поддержки",
|
|
||||||
2: "снято с поддержки (правки свободны)",
|
|
||||||
}.get(best, "не на поддержке")
|
|
||||||
except Exception:
|
|
||||||
return "не на поддержке"
|
|
||||||
|
|
||||||
|
|
||||||
# --- Main ---
|
# --- Main ---
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
sys.stdout.reconfigure(encoding="utf-8")
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
sys.stderr.reconfigure(encoding="utf-8")
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
parser = argparse.ArgumentParser(description="Analyze 1C managed form structure", allow_abbrev=False)
|
parser = argparse.ArgumentParser(description="Analyze 1C managed form structure", allow_abbrev=False)
|
||||||
parser.add_argument("-FormPath", "-Path", required=True, help="Path to Form.xml")
|
parser.add_argument("-FormPath", required=True, help="Path to Form.xml")
|
||||||
parser.add_argument("-Limit", type=int, default=150, help="Max lines to show")
|
parser.add_argument("-Limit", type=int, default=150, help="Max lines to show")
|
||||||
parser.add_argument("-Offset", type=int, default=0, help="Line offset for pagination")
|
parser.add_argument("-Offset", type=int, default=0, help="Line offset for pagination")
|
||||||
parser.add_argument("-Expand", default="", help="Expand collapsed section by name, or * for all")
|
parser.add_argument("-Expand", default="", help="Expand collapsed section by name, or * for all")
|
||||||
@@ -425,27 +353,7 @@ def main():
|
|||||||
offset = args.Offset
|
offset = args.Offset
|
||||||
expand = args.Expand
|
expand = args.Expand
|
||||||
|
|
||||||
# --- Resolve FormPath ---
|
# --- Validate path ---
|
||||||
if not os.path.isabs(form_path):
|
|
||||||
form_path = os.path.join(os.getcwd(), form_path)
|
|
||||||
# A: Directory → Ext/Form.xml
|
|
||||||
if os.path.isdir(form_path):
|
|
||||||
form_path = os.path.join(form_path, "Ext", "Form.xml")
|
|
||||||
# B1: Missing Ext/ (Forms/Форма/Form.xml → Forms/Форма/Ext/Form.xml)
|
|
||||||
if not os.path.isfile(form_path):
|
|
||||||
fn = os.path.basename(form_path)
|
|
||||||
if fn == "Form.xml":
|
|
||||||
c = os.path.join(os.path.dirname(form_path), "Ext", fn)
|
|
||||||
if os.path.isfile(c):
|
|
||||||
form_path = c
|
|
||||||
# B2: Descriptor (Forms/Форма.xml → Forms/Форма/Ext/Form.xml)
|
|
||||||
if not os.path.isfile(form_path) and form_path.endswith(".xml"):
|
|
||||||
stem = os.path.splitext(os.path.basename(form_path))[0]
|
|
||||||
parent = os.path.dirname(form_path)
|
|
||||||
c = os.path.join(parent, stem, "Ext", "Form.xml")
|
|
||||||
if os.path.isfile(c):
|
|
||||||
form_path = c
|
|
||||||
|
|
||||||
if not os.path.isfile(form_path):
|
if not os.path.isfile(form_path):
|
||||||
print(f"File not found: {form_path}", file=sys.stderr)
|
print(f"File not found: {form_path}", file=sys.stderr)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -513,7 +421,6 @@ def main():
|
|||||||
header += f" ({object_context})"
|
header += f" ({object_context})"
|
||||||
header += " ==="
|
header += " ==="
|
||||||
lines.append(header)
|
lines.append(header)
|
||||||
lines.append(f"Поддержка: {get_support_status_for_path(form_path)}")
|
|
||||||
|
|
||||||
# --- Form properties (Title excluded -- shown in header) ---
|
# --- Form properties (Title excluded -- shown in header) ---
|
||||||
prop_names = [
|
prop_names = [
|
||||||
@@ -557,50 +464,6 @@ def main():
|
|||||||
ct_str = f"[{ct}]" if ct else ""
|
ct_str = f"[{ct}]" if ct else ""
|
||||||
lines.append(f" {e_name}{ct_str} -> {e_handler}")
|
lines.append(f" {e_name}{ct_str} -> {e_handler}")
|
||||||
|
|
||||||
# --- Main AutoCommandBar (form's id=-1 panel) ---
|
|
||||||
def format_main_acb(acb_node):
|
|
||||||
if acb_node is None:
|
|
||||||
return []
|
|
||||||
autofill_node = acb_node.find("d:Autofill", NSMAP)
|
|
||||||
autofill = not (autofill_node is not None and autofill_node.text == "false")
|
|
||||||
halign_node = acb_node.find("d:HorizontalAlign", NSMAP)
|
|
||||||
flags = ["autofill" if autofill else "no-autofill"]
|
|
||||||
if halign_node is not None and halign_node.text:
|
|
||||||
flags.append(f"align={halign_node.text}")
|
|
||||||
ci_node = acb_node.find("d:ChildItems", NSMAP)
|
|
||||||
buttons = []
|
|
||||||
if ci_node is not None:
|
|
||||||
for btn in ci_node:
|
|
||||||
if not isinstance(btn.tag, str):
|
|
||||||
continue
|
|
||||||
ln = etree.QName(btn).localname
|
|
||||||
if ln in SKIP_ELEMENTS:
|
|
||||||
continue
|
|
||||||
b_name = btn.get("name", "")
|
|
||||||
cmd_node = btn.find("d:CommandName", NSMAP)
|
|
||||||
cmd_ref = cmd_node.text if cmd_node is not None and cmd_node.text else ""
|
|
||||||
loc_node = btn.find("d:LocationInCommandBar", NSMAP)
|
|
||||||
loc_str = f" [{loc_node.text}]" if loc_node is not None and loc_node.text else ""
|
|
||||||
tag = get_element_tag(btn)
|
|
||||||
if cmd_ref:
|
|
||||||
buttons.append(f" {tag} {b_name} -> {cmd_ref}{loc_str}")
|
|
||||||
else:
|
|
||||||
buttons.append(f" {tag} {b_name}{loc_str}")
|
|
||||||
if not buttons and autofill and halign_node is None:
|
|
||||||
return ["AutoCommandBar [autofill]"]
|
|
||||||
return [f"AutoCommandBar [{', '.join(flags)}]"] + buttons
|
|
||||||
|
|
||||||
cb_loc_node = root.find("d:CommandBarLocation", NSMAP)
|
|
||||||
cb_loc = cb_loc_node.text if cb_loc_node is not None and cb_loc_node.text else "Auto"
|
|
||||||
main_acb_node = root.find("d:AutoCommandBar", NSMAP)
|
|
||||||
acb_lines = []
|
|
||||||
if cb_loc != "None" and main_acb_node is not None:
|
|
||||||
acb_lines = format_main_acb(main_acb_node)
|
|
||||||
|
|
||||||
if acb_lines and cb_loc in ("Auto", "Top"):
|
|
||||||
lines.append("")
|
|
||||||
lines.extend(acb_lines)
|
|
||||||
|
|
||||||
# --- Element tree ---
|
# --- Element tree ---
|
||||||
tree_state = {"has_collapsed": False}
|
tree_state = {"has_collapsed": False}
|
||||||
child_items = root.find("d:ChildItems", NSMAP)
|
child_items = root.find("d:ChildItems", NSMAP)
|
||||||
@@ -611,10 +474,6 @@ def main():
|
|||||||
build_tree(child_items, " ", tree_lines, expand, tree_state)
|
build_tree(child_items, " ", tree_lines, expand, tree_state)
|
||||||
lines.extend(tree_lines)
|
lines.extend(tree_lines)
|
||||||
|
|
||||||
if acb_lines and cb_loc == "Bottom":
|
|
||||||
lines.append("")
|
|
||||||
lines.extend(acb_lines)
|
|
||||||
|
|
||||||
# --- Attributes ---
|
# --- Attributes ---
|
||||||
attrs_node = root.find("d:Attributes", NSMAP)
|
attrs_node = root.find("d:Attributes", NSMAP)
|
||||||
if attrs_node is not None:
|
if attrs_node is not None:
|
||||||
@@ -41,9 +41,9 @@ allowed-tools: []
|
|||||||
├─ Информационные надписи (label, hyperlink)
|
├─ Информационные надписи (label, hyperlink)
|
||||||
Рабочая область
|
Рабочая область
|
||||||
├─ Таблица данных или Pages с вкладками
|
├─ Таблица данных или Pages с вкладками
|
||||||
Главная АКП формы (autoCmdBar)
|
Кнопки действий
|
||||||
├─ Выполнить / Применить (defaultButton: true)
|
├─ Выполнить / Применить (defaultButton)
|
||||||
└─ Закрыть (stdCommand: Close)
|
├─ Закрыть (stdCommand: Close)
|
||||||
```
|
```
|
||||||
|
|
||||||
**События:** OnCreateAtServer, OnOpen, NotificationProcessing
|
**События:** OnCreateAtServer, OnOpen, NotificationProcessing
|
||||||
@@ -90,12 +90,12 @@ allowed-tools: []
|
|||||||
├─ Шаг1: описание + параметры
|
├─ Шаг1: описание + параметры
|
||||||
├─ Шаг2: основная работа
|
├─ Шаг2: основная работа
|
||||||
└─ Шаг3: результат
|
└─ Шаг3: результат
|
||||||
Главная АКП формы (autoCmdBar)
|
Кнопки (horizontal)
|
||||||
├─ Назад, Далее (defaultButton: true), Выполнить
|
├─ Назад (command), Далее (command, defaultButton), Выполнить (command)
|
||||||
└─ Закрыть (stdCommand: Close)
|
└─ Закрыть (stdCommand: Close)
|
||||||
```
|
```
|
||||||
|
|
||||||
**Свойства:** windowOpeningMode=LockOwnerWindow
|
**Свойства:** windowOpeningMode=LockOwnerWindow, commandBarLocation=None
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -111,7 +111,7 @@ allowed-tools: []
|
|||||||
| Номер+Дата | `ГруппаНомерДата` | horizontal |
|
| Номер+Дата | `ГруппаНомерДата` | horizontal |
|
||||||
| Подвал | `ГруппаПодвал` | vertical |
|
| Подвал | `ГруппаПодвал` | vertical |
|
||||||
| Итоги | `ГруппаИтоги` | horizontal |
|
| Итоги | `ГруппаИтоги` | horizontal |
|
||||||
| Главная АКП формы | `ФормаКоманднаяПанель` | autoCmdBar |
|
| Кнопки | `ГруппаКнопок` | horizontal |
|
||||||
| Страницы | `ГруппаСтраницы` / `Страницы` | pages |
|
| Страницы | `ГруппаСтраницы` / `Страницы` | pages |
|
||||||
| Предупреждение | `ГруппаПредупреждение` | horizontal, visible:false |
|
| Предупреждение | `ГруппаПредупреждение` | horizontal, visible:false |
|
||||||
| Доп. секция | `ГруппаДополнительно` / `ГруппаПрочее` | vertical, collapse |
|
| Доп. секция | `ГруппаДополнительно` / `ГруппаПрочее` | vertical, collapse |
|
||||||
@@ -150,7 +150,7 @@ allowed-tools: []
|
|||||||
|
|
||||||
1. **Порядок чтения.** Сверху вниз, слева направо. Самое важное — вверху.
|
1. **Порядок чтения.** Сверху вниз, слева направо. Самое важное — вверху.
|
||||||
2. **Двухколоночная шапка.** Основные реквизиты слева (контрагент, склад), организационные справа (организация, подразделение).
|
2. **Двухколоночная шапка.** Основные реквизиты слева (контрагент, склад), организационные справа (организация, подразделение).
|
||||||
3. **Кнопки действий — на главной АКП формы** (`autoCmdBar`), не в отдельной группе на форме. Главная кнопка — `defaultButton: true`. Закрыть — всегда последняя.
|
3. **Кнопки действий внизу.** Главная кнопка — `defaultButton: true`. Закрыть — всегда последняя.
|
||||||
4. **Таблицы — основная область.** Табличные части занимают большую часть формы, обычно на Pages.
|
4. **Таблицы — основная область.** Табличные части занимают большую часть формы, обычно на Pages.
|
||||||
5. **Итоги рядом с таблицей.** В подвале, горизонтальная группа, все поля readOnly.
|
5. **Итоги рядом с таблицей.** В подвале, горизонтальная группа, все поля readOnly.
|
||||||
6. **Фильтры — отдельная зона.** Над списком, alwaysHorizontal, пара «флажок + поле» на каждый фильтр.
|
6. **Фильтры — отдельная зона.** Над списком, alwaysHorizontal, пара «флажок + поле» на каждый фильтр.
|
||||||
@@ -166,8 +166,8 @@ allowed-tools: []
|
|||||||
Для необязательных секций (подписи, дополнительно, прочее):
|
Для необязательных секций (подписи, дополнительно, прочее):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{ "group": "collapsible", "name": "ГруппаПодписи", "title": "Подписи",
|
{ "group": "vertical", "name": "ГруппаПодписи", "title": "Подписи",
|
||||||
"collapsed": true, "children": [...] }
|
"behavior": "Collapsible", "collapsed": true, "children": [...] }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Баннер-предупреждение
|
### Баннер-предупреждение
|
||||||
@@ -233,7 +233,7 @@ allowed-tools: []
|
|||||||
{ "input": "ДанныеКоличество", "path": "Объект.Данные.Количество", "on": ["OnChange"] },
|
{ "input": "ДанныеКоличество", "path": "Объект.Данные.Количество", "on": ["OnChange"] },
|
||||||
{ "input": "ДанныеСумма", "path": "Объект.Данные.Сумма", "readOnly": true }
|
{ "input": "ДанныеСумма", "path": "Объект.Данные.Сумма", "readOnly": true }
|
||||||
]},
|
]},
|
||||||
{ "autoCmdBar": "ФормаКоманднаяПанель", "children": [
|
{ "group": "horizontal", "name": "ГруппаКнопок", "children": [
|
||||||
{ "button": "Загрузить", "command": "Загрузить", "title": "Загрузить из файла", "defaultButton": true },
|
{ "button": "Загрузить", "command": "Загрузить", "title": "Загрузить из файла", "defaultButton": true },
|
||||||
{ "button": "Очистить", "command": "Очистить", "title": "Очистить таблицу" },
|
{ "button": "Очистить", "command": "Очистить", "title": "Очистить таблицу" },
|
||||||
{ "button": "Закрыть", "stdCommand": "Close" }
|
{ "button": "Закрыть", "stdCommand": "Close" }
|
||||||
@@ -31,7 +31,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/form-remove/scripts/remove-form.py" -ObjectName "<ObjectName>" -FormName "<FormName>" [-SrcDir "<SrcDir>"]
|
powershell.exe -NoProfile -File .claude/skills/form-remove/scripts/remove-form.ps1 -ObjectName "<ObjectName>" -FormName "<FormName>" [-SrcDir "<SrcDir>"]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Что удаляется
|
## Что удаляется
|
||||||
+5
-11
@@ -1,4 +1,4 @@
|
|||||||
# form-remove v1.3 — Remove form from 1C object
|
# form-remove v1.1 — Remove form from 1C object
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
@@ -12,8 +12,6 @@ param(
|
|||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = "Stop"
|
$ErrorActionPreference = "Stop"
|
||||||
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
[Console]::InputEncoding = [System.Text.Encoding]::UTF8
|
|
||||||
|
|
||||||
# --- Проверки ---
|
# --- Проверки ---
|
||||||
|
|
||||||
@@ -68,14 +66,10 @@ foreach ($node in $formNodes) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Очистить любые Default*/Auxiliary* form-слоты, указывавшие на удалённую форму
|
# Очистить DefaultForm если указывала на эту форму
|
||||||
# (form-add пишет свойство по назначению: DefaultObjectForm/DefaultListForm/
|
$defaultForm = $xmlDoc.SelectSingleNode("//md:DefaultForm", $nsMgr)
|
||||||
# DefaultChoiceForm/DefaultRecordForm/DefaultForm — не только generic DefaultForm).
|
if ($defaultForm -and $defaultForm.InnerText -match "Form\.$FormName$") {
|
||||||
$formRefRe = "Form\.$([regex]::Escape($FormName))$"
|
$defaultForm.InnerText = ""
|
||||||
foreach ($node in $xmlDoc.SelectNodes("//md:*", $nsMgr)) {
|
|
||||||
if ($node.LocalName -like "*Form" -and $node.InnerText -and $node.InnerText -match $formRefRe) {
|
|
||||||
$node.InnerText = ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Сохранить с BOM
|
# Сохранить с BOM
|
||||||
+7
-13
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# remove-form v1.3 — Remove form from 1C object
|
# remove-form v1.0 — Remove form from 1C object
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -16,9 +16,7 @@ NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
|||||||
def save_xml_with_bom(tree, path):
|
def save_xml_with_bom(tree, path):
|
||||||
"""Save XML tree to file with UTF-8 BOM."""
|
"""Save XML tree to file with UTF-8 BOM."""
|
||||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
xml_bytes = xml_bytes.replace(b"encoding='UTF-8'", b'encoding="UTF-8"')
|
||||||
if not xml_bytes.endswith(b"\n"):
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
with open(path, "wb") as f:
|
with open(path, "wb") as f:
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
@@ -85,15 +83,11 @@ def main():
|
|||||||
parent.remove(node)
|
parent.remove(node)
|
||||||
break
|
break
|
||||||
|
|
||||||
# Clear any Default*/Auxiliary* form slot that pointed to the removed form
|
# Clear DefaultForm if it pointed to removed form
|
||||||
# (form-add writes the purpose-specific property: DefaultObjectForm / DefaultListForm /
|
default_form = root.find(".//md:DefaultForm", NSMAP)
|
||||||
# DefaultChoiceForm / DefaultRecordForm / DefaultForm — not just generic DefaultForm).
|
if default_form is not None and default_form.text:
|
||||||
ref_re = re.compile(rf"Form\.{re.escape(form_name)}$")
|
if re.search(rf"Form\.{re.escape(form_name)}$", default_form.text):
|
||||||
for el in root.iter():
|
default_form.text = ""
|
||||||
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 with BOM
|
||||||
save_xml_with_bom(tree, root_xml_full)
|
save_xml_with_bom(tree, root_xml_full)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
name: form-validate
|
||||||
|
description: Валидация управляемой формы 1С. Используй после создания или модификации формы для проверки корректности. При наличии BaseForm автоматически проверяет callType и ID расширений
|
||||||
|
argument-hint: <FormPath> [-Detailed] [-MaxErrors 30]
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Glob
|
||||||
|
---
|
||||||
|
|
||||||
|
# /form-validate — валидация управляемой формы 1С
|
||||||
|
|
||||||
|
Проверяет Form.xml на структурные ошибки: уникальность ID, наличие companion-элементов, корректность ссылок DataPath и команд.
|
||||||
|
|
||||||
|
## Параметры
|
||||||
|
|
||||||
|
| Параметр | Обяз. | Умолч. | Описание |
|
||||||
|
|-----------|:-----:|---------|-----------------------------------------|
|
||||||
|
| FormPath | да | — | Путь к файлу Form.xml |
|
||||||
|
| Detailed | нет | — | Показывать [OK] для каждой проверки |
|
||||||
|
| MaxErrors | нет | 30 | Остановиться после N ошибок |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/form-validate/scripts/form-validate.ps1 -FormPath "Catalogs/Номенклатура/Forms/ФормаЭлемента"
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/form-validate/scripts/form-validate.ps1 -FormPath "src/МояОбработка/Forms/Форма/Ext/Form.xml"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Проверки
|
||||||
|
|
||||||
|
| # | Проверка | Серьёзность |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | Корневой элемент `<Form>`, version="2.17" | ERROR / WARN |
|
||||||
|
| 2 | `<AutoCommandBar>` присутствует, id="-1" | ERROR |
|
||||||
|
| 3 | Уникальность ID элементов (отдельный пул) | ERROR |
|
||||||
|
| 4 | Уникальность ID реквизитов (отдельный пул) | ERROR |
|
||||||
|
| 5 | Уникальность ID команд (отдельный пул) | ERROR |
|
||||||
|
| 6 | Companion-элементы (ContextMenu, ExtendedTooltip, и др.) | ERROR |
|
||||||
|
| 7 | DataPath → ссылается на существующий реквизит | ERROR |
|
||||||
|
| 8 | CommandName кнопок → ссылается на существующую команду | ERROR |
|
||||||
|
| 9 | События имеют непустые имена обработчиков | ERROR |
|
||||||
|
| 10 | Команды имеют Action (обработчик) | ERROR |
|
||||||
|
| 11 | Не более одного MainAttribute | ERROR |
|
||||||
|
| 12 | BaseForm: наличие и version (при расширении) | OK / WARN |
|
||||||
|
| 13 | callType значения: Before, After, Override | ERROR |
|
||||||
|
| 14 | ID расширения >= 1000000 для добавленных attrs/commands | WARN |
|
||||||
|
| 15 | callType без BaseForm — некорректная структура | WARN |
|
||||||
|
|
||||||
|
Exit code: 0 = OK, 1 = есть ошибки. По умолчанию краткий вывод. `-Detailed` для поштучной детализации.
|
||||||
+18
-194
@@ -1,8 +1,7 @@
|
|||||||
# form-validate v1.8 — Validate 1C managed form
|
# form-validate v1.1 — Validate 1C managed form
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)]
|
[Parameter(Mandatory)]
|
||||||
[Alias('Path')]
|
|
||||||
[string]$FormPath,
|
[string]$FormPath,
|
||||||
|
|
||||||
[switch]$Detailed,
|
[switch]$Detailed,
|
||||||
@@ -59,20 +58,6 @@ $nsMgr.AddNamespace("v8", "http://v8.1c.ru/8.1/data/core")
|
|||||||
|
|
||||||
$root = $xmlDoc.DocumentElement
|
$root = $xmlDoc.DocumentElement
|
||||||
|
|
||||||
# --- Detect context: config vs EPF/ERF ---
|
|
||||||
# Walk up from FormPath looking for Configuration.xml → config context
|
|
||||||
# No Configuration.xml → external data processor / report (EPF/ERF)
|
|
||||||
$script:isConfigContext = $false
|
|
||||||
$walkDir = Split-Path (Resolve-Path $FormPath) -Parent
|
|
||||||
for ($i = 0; $i -lt 15; $i++) {
|
|
||||||
if (-not $walkDir -or $walkDir -eq (Split-Path $walkDir)) { break }
|
|
||||||
if (Test-Path (Join-Path $walkDir "Configuration.xml")) {
|
|
||||||
$script:isConfigContext = $true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
$walkDir = Split-Path $walkDir
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Counters ---
|
# --- Counters ---
|
||||||
|
|
||||||
$errors = 0
|
$errors = 0
|
||||||
@@ -127,10 +112,10 @@ if ($root.LocalName -ne "Form") {
|
|||||||
Report-Error "Root element is '$($root.LocalName)', expected 'Form'"
|
Report-Error "Root element is '$($root.LocalName)', expected 'Form'"
|
||||||
} else {
|
} else {
|
||||||
$version = $root.GetAttribute("version")
|
$version = $root.GetAttribute("version")
|
||||||
if ($version -eq "2.17" -or $version -eq "2.20") {
|
if ($version -eq "2.17") {
|
||||||
Report-OK "Root element: Form version=$version"
|
Report-OK "Root element: Form version=$version"
|
||||||
} elseif ($version) {
|
} elseif ($version) {
|
||||||
Report-Warn "Form version='$version' (expected 2.17 or 2.20)"
|
Report-Warn "Form version='$version' (expected 2.17)"
|
||||||
} else {
|
} else {
|
||||||
Report-Warn "Form version attribute missing"
|
Report-Warn "Form version attribute missing"
|
||||||
}
|
}
|
||||||
@@ -155,8 +140,7 @@ if (-not $stopped) {
|
|||||||
|
|
||||||
# --- Collect all elements with IDs ---
|
# --- Collect all elements with IDs ---
|
||||||
|
|
||||||
$elementIds = @{} # id -> name (element ID pool)
|
$elementIds = @{} # id -> name (element ID pool)
|
||||||
$elementNames = @{} # name -> id (имена элементов уникальны в пределах формы)
|
|
||||||
$allElements = @() # @{Name; Tag; Id; ParentName; Node}
|
$allElements = @() # @{Name; Tag; Id; ParentName; Node}
|
||||||
|
|
||||||
function Collect-Elements {
|
function Collect-Elements {
|
||||||
@@ -186,13 +170,6 @@ function Collect-Elements {
|
|||||||
} else {
|
} else {
|
||||||
$elementIds[$id] = $name
|
$elementIds[$id] = $name
|
||||||
}
|
}
|
||||||
|
|
||||||
# Имена элементов уникальны (требование 1С)
|
|
||||||
if ($elementNames.ContainsKey($name)) {
|
|
||||||
Report-Error "Duplicate element name '$name': id=${id} and id=$($elementNames[$name])"
|
|
||||||
} else {
|
|
||||||
$elementNames[$name] = $id
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# Recurse into ChildItems
|
# Recurse into ChildItems
|
||||||
@@ -237,10 +214,6 @@ foreach ($attr in $attrNodes) {
|
|||||||
$attrName = $attr.GetAttribute("name")
|
$attrName = $attr.GetAttribute("name")
|
||||||
$attrId = $attr.GetAttribute("id")
|
$attrId = $attr.GetAttribute("id")
|
||||||
if ($attrName) {
|
if ($attrName) {
|
||||||
# Имена реквизитов уникальны среди реквизитов (отдельный неймспейс от элементов)
|
|
||||||
if ($attrMap.ContainsKey($attrName)) {
|
|
||||||
Report-Error "Duplicate attribute name '$attrName': id=${attrId} and id=$($attrMap[$attrName].GetAttribute('id'))"
|
|
||||||
}
|
|
||||||
$attrMap[$attrName] = $attr
|
$attrMap[$attrName] = $attr
|
||||||
}
|
}
|
||||||
if ($attrId -and $attrId -ne "") {
|
if ($attrId -and $attrId -ne "") {
|
||||||
@@ -253,7 +226,6 @@ foreach ($attr in $attrNodes) {
|
|||||||
|
|
||||||
# Column IDs are a separate sub-pool per attribute — check uniqueness within parent
|
# Column IDs are a separate sub-pool per attribute — check uniqueness within parent
|
||||||
$colIds = @{}
|
$colIds = @{}
|
||||||
$colNames = @{} # имена колонок уникальны в пределах своего реквизита
|
|
||||||
foreach ($col in $attr.SelectNodes("f:Columns/f:Column", $nsMgr)) {
|
foreach ($col in $attr.SelectNodes("f:Columns/f:Column", $nsMgr)) {
|
||||||
$colId = $col.GetAttribute("id")
|
$colId = $col.GetAttribute("id")
|
||||||
$colName = $col.GetAttribute("name")
|
$colName = $col.GetAttribute("name")
|
||||||
@@ -264,13 +236,6 @@ foreach ($attr in $attrNodes) {
|
|||||||
$colIds[$colId] = $colName
|
$colIds[$colId] = $colName
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ($colName) {
|
|
||||||
if ($colNames.ContainsKey($colName)) {
|
|
||||||
Report-Error "Duplicate column name '$colName' in '$attrName': id=${colId} and id=$($colNames[$colName])"
|
|
||||||
} else {
|
|
||||||
$colNames[$colName] = $colId
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -290,10 +255,6 @@ foreach ($cmd in $cmdNodes) {
|
|||||||
$cmdName = $cmd.GetAttribute("name")
|
$cmdName = $cmd.GetAttribute("name")
|
||||||
$cmdId = $cmd.GetAttribute("id")
|
$cmdId = $cmd.GetAttribute("id")
|
||||||
if ($cmdName) {
|
if ($cmdName) {
|
||||||
# Имена команд уникальны среди команд (отдельный неймспейс)
|
|
||||||
if ($cmdMap.ContainsKey($cmdName)) {
|
|
||||||
Report-Error "Duplicate command name '$cmdName': id=${cmdId} and id=$($cmdMap[$cmdName].GetAttribute('id'))"
|
|
||||||
}
|
|
||||||
$cmdMap[$cmdName] = $cmd
|
$cmdMap[$cmdName] = $cmd
|
||||||
}
|
}
|
||||||
if ($cmdId -and $cmdId -ne "") {
|
if ($cmdId -and $cmdId -ne "") {
|
||||||
@@ -314,20 +275,6 @@ if (-not $stopped) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Collect parameters (separate name pool, без id) ---
|
|
||||||
|
|
||||||
$paramNames = @{} # name -> $true (имена параметров уникальны среди параметров)
|
|
||||||
foreach ($param in $root.SelectNodes("f:Parameters/f:Parameter", $nsMgr)) {
|
|
||||||
$paramName = $param.GetAttribute("name")
|
|
||||||
if ($paramName) {
|
|
||||||
if ($paramNames.ContainsKey($paramName)) {
|
|
||||||
Report-Error "Duplicate parameter name '$paramName'"
|
|
||||||
} else {
|
|
||||||
$paramNames[$paramName] = $true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Check 4: Companion elements ---
|
# --- Check 4: Companion elements ---
|
||||||
|
|
||||||
# Define required companions per element type
|
# Define required companions per element type
|
||||||
@@ -382,10 +329,6 @@ if (-not $stopped) {
|
|||||||
$pathChecked = 0
|
$pathChecked = 0
|
||||||
$pathBaseSkipped = 0
|
$pathBaseSkipped = 0
|
||||||
|
|
||||||
# All data-binding tags whose value is an attribute path (root must exist in <Attributes>).
|
|
||||||
$bindingTags = @('DataPath','TitleDataPath','FooterDataPath','HeaderDataPath',
|
|
||||||
'MultipleValueDataPath','MultipleValuePresentDataPath','RowPictureDataPath','MultipleValuePictureDataPath')
|
|
||||||
|
|
||||||
foreach ($el in $allElements) {
|
foreach ($el in $allElements) {
|
||||||
if ($stopped) { break }
|
if ($stopped) { break }
|
||||||
$tag = $el.Tag
|
$tag = $el.Tag
|
||||||
@@ -402,63 +345,22 @@ if (-not $stopped) {
|
|||||||
try { if ([int]$el.Id -lt 1000000) { $pathBaseSkipped++; continue } } catch {}
|
try { if ([int]$el.Id -lt 1000000) { $pathBaseSkipped++; continue } } catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ($bTag in $bindingTags) {
|
$dpNode = $node.SelectSingleNode("f:DataPath", $nsMgr)
|
||||||
if ($stopped) { break }
|
if (-not $dpNode) { continue }
|
||||||
$dpNode = $node.SelectSingleNode("f:$bTag", $nsMgr)
|
|
||||||
if (-not $dpNode) { continue }
|
|
||||||
|
|
||||||
$dataPath = $dpNode.InnerText.Trim()
|
$dataPath = $dpNode.InnerText.Trim()
|
||||||
if (-not $dataPath) { continue }
|
if (-not $dataPath) { continue }
|
||||||
|
|
||||||
# Opaque platform-internal shapes — not validatable from Form.xml alone:
|
$pathChecked++
|
||||||
# - bare numeric (e.g. "10", "1000003") — internal index
|
|
||||||
# - "N/M:<uuid>" — metadata reference by UUID
|
|
||||||
if ($dataPath -match '^\d+$' -or $dataPath -match '^\d+/\d+:[0-9a-fA-F-]+$') {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
$pathChecked++
|
# Extract root segment of path, strip array indices like [0]
|
||||||
|
$cleanPath = $dataPath -replace '\[\d+\]', ''
|
||||||
|
$segments = $cleanPath -split '\.'
|
||||||
|
$rootAttr = $segments[0]
|
||||||
|
|
||||||
# Extract root segment of path, strip array indices like [0]
|
if (-not $attrMap.ContainsKey($rootAttr)) {
|
||||||
$cleanPath = $dataPath -replace '\[\d+\]', ''
|
Report-Error "[$tag] '$elName': DataPath='$dataPath' — attribute '$rootAttr' not found"
|
||||||
# Strip leading '~' (current row of DynamicList: ~Список.Поле)
|
$pathErrors++
|
||||||
if ($cleanPath.StartsWith('~')) { $cleanPath = $cleanPath.Substring(1) }
|
|
||||||
$segments = $cleanPath -split '\.'
|
|
||||||
$rootAttr = $segments[0]
|
|
||||||
|
|
||||||
# Resolve Items.<TableName>.CurrentData.<Field>... — table element, not attribute
|
|
||||||
if ($rootAttr -eq 'Items') {
|
|
||||||
if ($segments.Count -lt 3 -or $segments[2] -ne 'CurrentData') {
|
|
||||||
Report-Warn "[$tag] '$elName': $bTag='$dataPath' — unknown Items.* shape, expected Items.<Table>.CurrentData.*"
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$tableName = $segments[1]
|
|
||||||
$tableEl = $null
|
|
||||||
foreach ($candidate in $allElements) {
|
|
||||||
if ($candidate.Tag -eq 'Table' -and $candidate.Name -eq $tableName) {
|
|
||||||
$tableEl = $candidate
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (-not $tableEl) {
|
|
||||||
Report-Error "[$tag] '$elName': $bTag='$dataPath' — table element '$tableName' not found"
|
|
||||||
$pathErrors++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$tableDpNode = $tableEl.Node.SelectSingleNode("f:DataPath", $nsMgr)
|
|
||||||
if (-not $tableDpNode -or -not $tableDpNode.InnerText.Trim()) {
|
|
||||||
# Table without DataPath — can't resolve further, accept silently
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
$tableDp = $tableDpNode.InnerText.Trim() -replace '\[\d+\]', ''
|
|
||||||
if ($tableDp.StartsWith('~')) { $tableDp = $tableDp.Substring(1) }
|
|
||||||
$rootAttr = ($tableDp -split '\.')[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $attrMap.ContainsKey($rootAttr)) {
|
|
||||||
Report-Error "[$tag] '$elName': $bTag='$dataPath' — attribute '$rootAttr' not found"
|
|
||||||
$pathErrors++
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,9 +371,9 @@ if (-not $stopped) {
|
|||||||
$pathMsg = if ($pathMsg) { "$pathMsg, $skipNote" } else { $skipNote }
|
$pathMsg = if ($pathMsg) { "$pathMsg, $skipNote" } else { $skipNote }
|
||||||
}
|
}
|
||||||
if ($pathErrors -eq 0 -and $pathMsg) {
|
if ($pathErrors -eq 0 -and $pathMsg) {
|
||||||
Report-OK "Data bindings: $pathMsg"
|
Report-OK "DataPath references: $pathMsg"
|
||||||
} elseif ($pathErrors -eq 0) {
|
} elseif ($pathErrors -eq 0) {
|
||||||
Report-OK "Data bindings: none"
|
Report-OK "DataPath references: none"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -765,84 +667,6 @@ if (-not $stopped -and -not $isExtension) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Check 12: Type values validation ---
|
|
||||||
|
|
||||||
$knownInvalidTypes = @(
|
|
||||||
"FormDataStructure","FormDataCollection","FormDataTree","FormDataTreeItem","FormDataCollectionItem"
|
|
||||||
"FormGroup","FormField","FormButton","FormDecoration","FormTable"
|
|
||||||
)
|
|
||||||
$validClosedTypes = @(
|
|
||||||
"xs:boolean","xs:string","xs:decimal","xs:dateTime","xs:binary"
|
|
||||||
"v8:FillChecking","v8:Null","v8:StandardPeriod","v8:StandardBeginningDate","v8:Type"
|
|
||||||
"v8:TypeDescription","v8:UUID","v8:ValueListType","v8:ValueTable","v8:ValueTree"
|
|
||||||
"v8:Universal","v8:FixedArray","v8:FixedStructure"
|
|
||||||
"v8ui:Color","v8ui:Font","v8ui:FormattedString","v8ui:HorizontalAlign"
|
|
||||||
"v8ui:Picture","v8ui:SizeChangeMode","v8ui:VerticalAlign"
|
|
||||||
"dcsset:DataCompositionComparisonType","dcsset:DataCompositionFieldPlacement"
|
|
||||||
"dcsset:Filter","dcsset:SettingsComposer","dcsset:DataCompositionSettings"
|
|
||||||
"dcssch:DataCompositionSchema"
|
|
||||||
"dcscor:DataCompositionComparisonType","dcscor:DataCompositionGroupType"
|
|
||||||
"dcscor:DataCompositionPeriodAdditionType","dcscor:DataCompositionSortDirection","dcscor:Field"
|
|
||||||
"ent:AccountType","ent:AccumulationRecordType","ent:AccountingRecordType"
|
|
||||||
)
|
|
||||||
$validCfgPrefixes = @(
|
|
||||||
"AccountingRegisterRecordSet","AccumulationRegisterRecordSet"
|
|
||||||
"BusinessProcessObject","BusinessProcessRef"
|
|
||||||
"CatalogObject","CatalogRef"
|
|
||||||
"ChartOfAccountsObject","ChartOfAccountsRef"
|
|
||||||
"ChartOfCalculationTypesObject","ChartOfCalculationTypesRef"
|
|
||||||
"ChartOfCharacteristicTypesObject","ChartOfCharacteristicTypesRef"
|
|
||||||
"ConstantsSet","DataProcessorObject","DocumentObject","DocumentRef"
|
|
||||||
"DynamicList","EnumRef","ExchangePlanObject","ExchangePlanRef"
|
|
||||||
"ExternalDataProcessorObject","ExternalReportObject"
|
|
||||||
"InformationRegisterRecordManager","InformationRegisterRecordSet"
|
|
||||||
"ReportObject","TaskObject","TaskRef"
|
|
||||||
)
|
|
||||||
|
|
||||||
if (-not $stopped) {
|
|
||||||
$typeNodes = $root.SelectNodes("//v8:Type", $nsMgr)
|
|
||||||
$typeOk = $true
|
|
||||||
$typeChecked = 0
|
|
||||||
$typeInvalid = 0
|
|
||||||
foreach ($tn in $typeNodes) {
|
|
||||||
$tv = $tn.InnerText.Trim()
|
|
||||||
if (-not $tv) { continue }
|
|
||||||
$typeChecked++
|
|
||||||
if ($tv -in $knownInvalidTypes) {
|
|
||||||
Report-Error "12. Type '$tv': invalid runtime/UI type (not valid in XDTO schema)"
|
|
||||||
$typeOk = $false; $typeInvalid++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ($tv -in $validClosedTypes) { continue }
|
|
||||||
if ($tv -match '^cfg:(.+)$') {
|
|
||||||
$cfgVal = $Matches[1]
|
|
||||||
if ($cfgVal -eq "DynamicList") { continue }
|
|
||||||
if ($cfgVal -match '^([^.]+)\.') {
|
|
||||||
$pfx = $Matches[1]
|
|
||||||
if ($pfx -in $validCfgPrefixes) {
|
|
||||||
# ExternalDataProcessorObject/ExternalReportObject valid only for EPF/ERF, not config
|
|
||||||
if ($script:isConfigContext -and ($pfx -eq "ExternalDataProcessorObject" -or $pfx -eq "ExternalReportObject")) {
|
|
||||||
Report-Error "12. Type '$tv': External* type in configuration context (use DataProcessorObject/ReportObject instead)"
|
|
||||||
$typeOk = $false; $typeInvalid++
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Report-Warn "12. Type '$tv': unrecognized cfg prefix"
|
|
||||||
$typeOk = $false
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ($tv -match ':') { continue }
|
|
||||||
Report-Warn "12. Type '$tv': bare type without namespace prefix"
|
|
||||||
$typeOk = $false
|
|
||||||
}
|
|
||||||
if ($typeChecked -eq 0) {
|
|
||||||
Report-OK "12. Types: no type values to check"
|
|
||||||
} elseif ($typeOk) {
|
|
||||||
Report-OK "12. Types: $typeChecked values, all valid"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Summary ---
|
# --- Summary ---
|
||||||
|
|
||||||
$checks = $script:okCount + $errors + $warnings
|
$checks = $script:okCount + $errors + $warnings
|
||||||
+19
-178
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-validate v1.8 — Validate 1C managed form
|
# form-validate v1.1 — Validate 1C managed form
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
@@ -13,41 +13,6 @@ V8_NS = "http://v8.1c.ru/8.1/data/core"
|
|||||||
|
|
||||||
NSMAP = {"f": F_NS, "v8": V8_NS}
|
NSMAP = {"f": F_NS, "v8": V8_NS}
|
||||||
|
|
||||||
KNOWN_INVALID_TYPES = {
|
|
||||||
'FormDataStructure', 'FormDataCollection', 'FormDataTree',
|
|
||||||
'FormDataTreeItem', 'FormDataCollectionItem',
|
|
||||||
'FormGroup', 'FormField', 'FormButton', 'FormDecoration', 'FormTable',
|
|
||||||
}
|
|
||||||
|
|
||||||
VALID_CLOSED_TYPES = {
|
|
||||||
'xs:boolean', 'xs:string', 'xs:decimal', 'xs:dateTime', 'xs:binary',
|
|
||||||
'v8:FillChecking', 'v8:Null', 'v8:StandardPeriod', 'v8:StandardBeginningDate', 'v8:Type',
|
|
||||||
'v8:TypeDescription', 'v8:UUID', 'v8:ValueListType', 'v8:ValueTable', 'v8:ValueTree',
|
|
||||||
'v8:Universal', 'v8:FixedArray', 'v8:FixedStructure',
|
|
||||||
'v8ui:Color', 'v8ui:Font', 'v8ui:FormattedString', 'v8ui:HorizontalAlign',
|
|
||||||
'v8ui:Picture', 'v8ui:SizeChangeMode', 'v8ui:VerticalAlign',
|
|
||||||
'dcsset:DataCompositionComparisonType', 'dcsset:DataCompositionFieldPlacement',
|
|
||||||
'dcsset:Filter', 'dcsset:SettingsComposer', 'dcsset:DataCompositionSettings',
|
|
||||||
'dcssch:DataCompositionSchema',
|
|
||||||
'dcscor:DataCompositionComparisonType', 'dcscor:DataCompositionGroupType',
|
|
||||||
'dcscor:DataCompositionPeriodAdditionType', 'dcscor:DataCompositionSortDirection', 'dcscor:Field',
|
|
||||||
'ent:AccountType', 'ent:AccumulationRecordType', 'ent:AccountingRecordType',
|
|
||||||
}
|
|
||||||
|
|
||||||
VALID_CFG_PREFIXES = {
|
|
||||||
'AccountingRegisterRecordSet', 'AccumulationRegisterRecordSet',
|
|
||||||
'BusinessProcessObject', 'BusinessProcessRef',
|
|
||||||
'CatalogObject', 'CatalogRef',
|
|
||||||
'ChartOfAccountsObject', 'ChartOfAccountsRef',
|
|
||||||
'ChartOfCalculationTypesObject', 'ChartOfCalculationTypesRef',
|
|
||||||
'ChartOfCharacteristicTypesObject', 'ChartOfCharacteristicTypesRef',
|
|
||||||
'ConstantsSet', 'DataProcessorObject', 'DocumentObject', 'DocumentRef',
|
|
||||||
'DynamicList', 'EnumRef', 'ExchangePlanObject', 'ExchangePlanRef',
|
|
||||||
'ExternalDataProcessorObject', 'ExternalReportObject',
|
|
||||||
'InformationRegisterRecordManager', 'InformationRegisterRecordSet',
|
|
||||||
'ReportObject', 'TaskObject', 'TaskRef',
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def localname(el):
|
def localname(el):
|
||||||
return etree.QName(el.tag).localname
|
return etree.QName(el.tag).localname
|
||||||
@@ -57,7 +22,7 @@ def main():
|
|||||||
sys.stdout.reconfigure(encoding="utf-8")
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
sys.stderr.reconfigure(encoding="utf-8")
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
parser = argparse.ArgumentParser(description="Validate 1C managed form", allow_abbrev=False)
|
parser = argparse.ArgumentParser(description="Validate 1C managed form", allow_abbrev=False)
|
||||||
parser.add_argument("-FormPath", "-Path", required=True)
|
parser.add_argument("-FormPath", required=True)
|
||||||
parser.add_argument("-Detailed", action="store_true")
|
parser.add_argument("-Detailed", action="store_true")
|
||||||
parser.add_argument("-MaxErrors", type=int, default=30)
|
parser.add_argument("-MaxErrors", type=int, default=30)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
@@ -104,18 +69,6 @@ def main():
|
|||||||
|
|
||||||
root = tree.getroot()
|
root = tree.getroot()
|
||||||
|
|
||||||
# Detect context: config vs EPF/ERF
|
|
||||||
is_config_context = False
|
|
||||||
walk_dir = os.path.dirname(os.path.abspath(form_path))
|
|
||||||
for _ in range(15):
|
|
||||||
parent = os.path.dirname(walk_dir)
|
|
||||||
if parent == walk_dir:
|
|
||||||
break
|
|
||||||
if os.path.isfile(os.path.join(walk_dir, 'Configuration.xml')):
|
|
||||||
is_config_context = True
|
|
||||||
break
|
|
||||||
walk_dir = parent
|
|
||||||
|
|
||||||
errors = 0
|
errors = 0
|
||||||
warnings = 0
|
warnings = 0
|
||||||
ok_count = 0
|
ok_count = 0
|
||||||
@@ -161,10 +114,10 @@ def main():
|
|||||||
report_error(f"Root element is '{localname(root)}', expected 'Form'")
|
report_error(f"Root element is '{localname(root)}', expected 'Form'")
|
||||||
else:
|
else:
|
||||||
version = root.get("version", "")
|
version = root.get("version", "")
|
||||||
if version in ("2.17", "2.20"):
|
if version == "2.17":
|
||||||
report_ok(f"Root element: Form version={version}")
|
report_ok(f"Root element: Form version={version}")
|
||||||
elif version:
|
elif version:
|
||||||
report_warn(f"Form version='{version}' (expected 2.17 or 2.20)")
|
report_warn(f"Form version='{version}' (expected 2.17)")
|
||||||
else:
|
else:
|
||||||
report_warn("Form version attribute missing")
|
report_warn("Form version attribute missing")
|
||||||
|
|
||||||
@@ -182,8 +135,7 @@ def main():
|
|||||||
report_error("AutoCommandBar element missing")
|
report_error("AutoCommandBar element missing")
|
||||||
|
|
||||||
# --- Collect all elements with IDs ---
|
# --- Collect all elements with IDs ---
|
||||||
element_ids = {} # id -> name
|
element_ids = {} # id -> name
|
||||||
element_names = {} # name -> id (имена элементов уникальны в пределах формы)
|
|
||||||
all_elements = [] # list of dicts {Name, Tag, Id, ParentName, Node}
|
all_elements = [] # list of dicts {Name, Tag, Id, ParentName, Node}
|
||||||
|
|
||||||
def collect_elements(node, parent_name):
|
def collect_elements(node, parent_name):
|
||||||
@@ -212,12 +164,6 @@ def main():
|
|||||||
else:
|
else:
|
||||||
element_ids[eid] = name
|
element_ids[eid] = name
|
||||||
|
|
||||||
# Имена элементов уникальны (требование 1С)
|
|
||||||
if name in element_names:
|
|
||||||
report_error(f"Duplicate element name '{name}': id={eid} and id={element_names[name]}")
|
|
||||||
else:
|
|
||||||
element_names[name] = eid
|
|
||||||
|
|
||||||
child_items = child.find(f"{{{F_NS}}}ChildItems")
|
child_items = child.find(f"{{{F_NS}}}ChildItems")
|
||||||
if child_items is not None:
|
if child_items is not None:
|
||||||
collect_elements(child_items, name)
|
collect_elements(child_items, name)
|
||||||
@@ -259,9 +205,6 @@ def main():
|
|||||||
attr_name = attr.get("name", "")
|
attr_name = attr.get("name", "")
|
||||||
attr_id = attr.get("id", "")
|
attr_id = attr.get("id", "")
|
||||||
if attr_name:
|
if attr_name:
|
||||||
# Имена реквизитов уникальны среди реквизитов (отдельный неймспейс от элементов)
|
|
||||||
if attr_name in attr_map:
|
|
||||||
report_error(f"Duplicate attribute name '{attr_name}': id={attr_id} and id={attr_map[attr_name].get('id', '')}")
|
|
||||||
attr_map[attr_name] = attr
|
attr_map[attr_name] = attr
|
||||||
if attr_id:
|
if attr_id:
|
||||||
if attr_id in attr_ids:
|
if attr_id in attr_ids:
|
||||||
@@ -271,7 +214,6 @@ def main():
|
|||||||
|
|
||||||
# Column IDs uniqueness within parent
|
# Column IDs uniqueness within parent
|
||||||
col_ids = {}
|
col_ids = {}
|
||||||
col_names = {} # имена колонок уникальны в пределах своего реквизита
|
|
||||||
columns = attr.find(f"{{{F_NS}}}Columns")
|
columns = attr.find(f"{{{F_NS}}}Columns")
|
||||||
if columns is not None:
|
if columns is not None:
|
||||||
for col in columns.findall(f"{{{F_NS}}}Column"):
|
for col in columns.findall(f"{{{F_NS}}}Column"):
|
||||||
@@ -282,11 +224,6 @@ def main():
|
|||||||
report_error(f"Duplicate column id={col_id} in '{attr_name}': '{col_name}' and '{col_ids[col_id]}'")
|
report_error(f"Duplicate column id={col_id} in '{attr_name}': '{col_name}' and '{col_ids[col_id]}'")
|
||||||
else:
|
else:
|
||||||
col_ids[col_id] = col_name
|
col_ids[col_id] = col_name
|
||||||
if col_name:
|
|
||||||
if col_name in col_names:
|
|
||||||
report_error(f"Duplicate column name '{col_name}' in '{attr_name}': id={col_id} and id={col_names[col_name]}")
|
|
||||||
else:
|
|
||||||
col_names[col_name] = col_id
|
|
||||||
|
|
||||||
if not stopped:
|
if not stopped:
|
||||||
if attr_ids:
|
if attr_ids:
|
||||||
@@ -305,9 +242,6 @@ def main():
|
|||||||
cmd_name = cmd.get("name", "")
|
cmd_name = cmd.get("name", "")
|
||||||
cmd_id = cmd.get("id", "")
|
cmd_id = cmd.get("id", "")
|
||||||
if cmd_name:
|
if cmd_name:
|
||||||
# Имена команд уникальны среди команд (отдельный неймспейс)
|
|
||||||
if cmd_name in cmd_map:
|
|
||||||
report_error(f"Duplicate command name '{cmd_name}': id={cmd_id} and id={cmd_map[cmd_name].get('id', '')}")
|
|
||||||
cmd_map[cmd_name] = cmd
|
cmd_map[cmd_name] = cmd
|
||||||
if cmd_id:
|
if cmd_id:
|
||||||
if cmd_id in cmd_ids:
|
if cmd_id in cmd_ids:
|
||||||
@@ -319,18 +253,6 @@ def main():
|
|||||||
if cmd_ids:
|
if cmd_ids:
|
||||||
report_ok(f"Unique command IDs: {len(cmd_ids)} entries")
|
report_ok(f"Unique command IDs: {len(cmd_ids)} entries")
|
||||||
|
|
||||||
# --- Collect parameters (separate name pool, без id) ---
|
|
||||||
param_names = {} # name -> True (имена параметров уникальны среди параметров)
|
|
||||||
params_parent = root.find(f"{{{F_NS}}}Parameters")
|
|
||||||
if params_parent is not None:
|
|
||||||
for param in params_parent.findall(f"{{{F_NS}}}Parameter"):
|
|
||||||
param_name = param.get("name", "")
|
|
||||||
if param_name:
|
|
||||||
if param_name in param_names:
|
|
||||||
report_error(f"Duplicate parameter name '{param_name}'")
|
|
||||||
else:
|
|
||||||
param_names[param_name] = True
|
|
||||||
|
|
||||||
# --- Check 4: Companion elements ---
|
# --- Check 4: Companion elements ---
|
||||||
companion_rules = {
|
companion_rules = {
|
||||||
"InputField": ["ContextMenu", "ExtendedTooltip"],
|
"InputField": ["ContextMenu", "ExtendedTooltip"],
|
||||||
@@ -379,10 +301,6 @@ def main():
|
|||||||
path_checked = 0
|
path_checked = 0
|
||||||
path_base_skipped = 0
|
path_base_skipped = 0
|
||||||
|
|
||||||
# All data-binding tags whose value is an attribute path (root must exist in <Attributes>).
|
|
||||||
binding_tags = ["DataPath", "TitleDataPath", "FooterDataPath", "HeaderDataPath",
|
|
||||||
"MultipleValueDataPath", "MultipleValuePresentDataPath", "RowPictureDataPath", "MultipleValuePictureDataPath"]
|
|
||||||
|
|
||||||
skip_tags = {"ContextMenu", "ExtendedTooltip", "AutoCommandBar", "SearchStringAddition", "ViewStatusAddition", "SearchControlAddition"}
|
skip_tags = {"ContextMenu", "ExtendedTooltip", "AutoCommandBar", "SearchStringAddition", "ViewStatusAddition", "SearchControlAddition"}
|
||||||
|
|
||||||
for el in all_elements:
|
for el in all_elements:
|
||||||
@@ -403,58 +321,23 @@ def main():
|
|||||||
except (ValueError, TypeError):
|
except (ValueError, TypeError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
for b_tag in binding_tags:
|
dp_node = node.find(f"{{{F_NS}}}DataPath")
|
||||||
if stopped:
|
if dp_node is None:
|
||||||
break
|
continue
|
||||||
dp_node = node.find(f"{{{F_NS}}}{b_tag}")
|
|
||||||
if dp_node is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
data_path = (dp_node.text or "").strip()
|
data_path = (dp_node.text or "").strip()
|
||||||
if not data_path:
|
if not data_path:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Opaque platform-internal shapes — not validatable from Form.xml alone:
|
path_checked += 1
|
||||||
# - bare numeric (e.g. "10", "1000003") — internal index
|
|
||||||
# - "N/M:<uuid>" — metadata reference by UUID
|
|
||||||
if re.match(r'^\d+$', data_path) or re.match(r'^\d+/\d+:[0-9a-fA-F-]+$', data_path):
|
|
||||||
continue
|
|
||||||
|
|
||||||
path_checked += 1
|
clean_path = re.sub(r'\[\d+\]', '', data_path)
|
||||||
|
segments = clean_path.split(".")
|
||||||
|
root_attr = segments[0]
|
||||||
|
|
||||||
clean_path = re.sub(r'\[\d+\]', '', data_path)
|
if root_attr not in attr_map:
|
||||||
# Strip leading '~' (current row of DynamicList: ~Список.Поле)
|
report_error(f"[{tag}] '{el_name}': DataPath='{data_path}' \u2014 attribute '{root_attr}' not found")
|
||||||
if clean_path.startswith('~'):
|
path_errors += 1
|
||||||
clean_path = clean_path[1:]
|
|
||||||
segments = clean_path.split(".")
|
|
||||||
root_attr = segments[0]
|
|
||||||
|
|
||||||
# Resolve Items.<TableName>.CurrentData.<Field>... — table element, not attribute
|
|
||||||
if root_attr == 'Items':
|
|
||||||
if len(segments) < 3 or segments[2] != 'CurrentData':
|
|
||||||
report_warn(f"[{tag}] '{el_name}': {b_tag}='{data_path}' — unknown Items.* shape, expected Items.<Table>.CurrentData.*")
|
|
||||||
continue
|
|
||||||
table_name = segments[1]
|
|
||||||
table_el = None
|
|
||||||
for candidate in all_elements:
|
|
||||||
if candidate["Tag"] == 'Table' and candidate["Name"] == table_name:
|
|
||||||
table_el = candidate
|
|
||||||
break
|
|
||||||
if table_el is None:
|
|
||||||
report_error(f"[{tag}] '{el_name}': {b_tag}='{data_path}' — table element '{table_name}' not found")
|
|
||||||
path_errors += 1
|
|
||||||
continue
|
|
||||||
table_dp_node = table_el["Node"].find(f"{{{F_NS}}}DataPath")
|
|
||||||
if table_dp_node is None or not (table_dp_node.text or "").strip():
|
|
||||||
continue
|
|
||||||
table_dp = re.sub(r'\[\d+\]', '', (table_dp_node.text or "").strip())
|
|
||||||
if table_dp.startswith('~'):
|
|
||||||
table_dp = table_dp[1:]
|
|
||||||
root_attr = table_dp.split(".")[0]
|
|
||||||
|
|
||||||
if root_attr not in attr_map:
|
|
||||||
report_error(f"[{tag}] '{el_name}': {b_tag}='{data_path}' — attribute '{root_attr}' not found")
|
|
||||||
path_errors += 1
|
|
||||||
|
|
||||||
path_msg = ""
|
path_msg = ""
|
||||||
if path_checked > 0:
|
if path_checked > 0:
|
||||||
@@ -463,7 +346,7 @@ def main():
|
|||||||
skip_note = f"{path_base_skipped} base skipped"
|
skip_note = f"{path_base_skipped} base skipped"
|
||||||
path_msg = f"{path_msg}, {skip_note}" if path_msg else skip_note
|
path_msg = f"{path_msg}, {skip_note}" if path_msg else skip_note
|
||||||
if path_errors == 0 and path_msg:
|
if path_errors == 0 and path_msg:
|
||||||
report_ok(f"Data bindings: {path_msg}")
|
report_ok(f"DataPath references: {path_msg}")
|
||||||
|
|
||||||
# --- Check 6: Button command references ---
|
# --- Check 6: Button command references ---
|
||||||
if not stopped:
|
if not stopped:
|
||||||
@@ -705,48 +588,6 @@ def main():
|
|||||||
if call_type_without_base:
|
if call_type_without_base:
|
||||||
report_warn("callType attributes found but no BaseForm \u2014 possible incorrect structure")
|
report_warn("callType attributes found but no BaseForm \u2014 possible incorrect structure")
|
||||||
|
|
||||||
# --- Check 12: Type validation ---
|
|
||||||
if not stopped:
|
|
||||||
type_nodes = root.xpath('//v8:Type', namespaces={'v8': V8_NS})
|
|
||||||
type_error_count = 0
|
|
||||||
type_warn_count = 0
|
|
||||||
type_count = len(type_nodes)
|
|
||||||
|
|
||||||
for tn in type_nodes:
|
|
||||||
if stopped:
|
|
||||||
break
|
|
||||||
tv = (tn.text or "").strip()
|
|
||||||
if not tv:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if tv in KNOWN_INVALID_TYPES:
|
|
||||||
report_error(f'12. Type "{tv}": invalid runtime/UI type (not valid in XDTO schema)')
|
|
||||||
type_error_count += 1
|
|
||||||
elif tv in VALID_CLOSED_TYPES:
|
|
||||||
pass # OK
|
|
||||||
elif tv.startswith("cfg:"):
|
|
||||||
suffix = tv[4:] # after "cfg:"
|
|
||||||
prefix = suffix.split(".")[0]
|
|
||||||
if prefix in VALID_CFG_PREFIXES or suffix == "DynamicList":
|
|
||||||
# ExternalDataProcessorObject/ExternalReportObject valid only in EPF/ERF context
|
|
||||||
if is_config_context and prefix in ('ExternalDataProcessorObject', 'ExternalReportObject'):
|
|
||||||
report_error(f'12. Type "{tv}": External* type in configuration context (use DataProcessorObject/ReportObject instead)')
|
|
||||||
type_error_count += 1
|
|
||||||
else:
|
|
||||||
report_warn(f'12. Type "{tv}": unrecognized cfg prefix')
|
|
||||||
type_warn_count += 1
|
|
||||||
elif ":" in tv:
|
|
||||||
pass # unknown namespace, pass through
|
|
||||||
else:
|
|
||||||
report_warn(f'12. Type "{tv}": bare type without namespace prefix')
|
|
||||||
type_warn_count += 1
|
|
||||||
|
|
||||||
if type_error_count == 0 and type_warn_count == 0:
|
|
||||||
if type_count > 0:
|
|
||||||
report_ok(f'12. Types: {type_count} values, all valid')
|
|
||||||
else:
|
|
||||||
report_ok('12. Types: no type values to check')
|
|
||||||
|
|
||||||
# --- Finalize ---
|
# --- Finalize ---
|
||||||
checks = ok_count + errors + warnings
|
checks = ok_count + errors + warnings
|
||||||
if errors == 0 and warnings == 0 and not detailed:
|
if errors == 0 and warnings == 0 and not detailed:
|
||||||
@@ -30,7 +30,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".opencode/skills/help-add/scripts/add-help.py" -ObjectName "<ObjectName>" [-Lang "<Lang>"] [-SrcDir "<SrcDir>"]
|
powershell.exe -NoProfile -File .claude/skills/help-add/scripts/add-help.ps1 -ObjectName "<ObjectName>" [-Lang "<Lang>"] [-SrcDir "<SrcDir>"]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Что делает скрипт
|
## Что делает скрипт
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
# help-add v1.2 — Add built-in help to 1C object
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$ObjectName,
|
||||||
|
|
||||||
|
[string]$Lang = "ru",
|
||||||
|
|
||||||
|
[string]$SrcDir = "src"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
# --- Проверки ---
|
||||||
|
|
||||||
|
$objectDir = Join-Path $SrcDir $ObjectName
|
||||||
|
$extDir = Join-Path $objectDir "Ext"
|
||||||
|
|
||||||
|
if (-not (Test-Path $extDir)) {
|
||||||
|
Write-Error "Каталог объекта не найден: $extDir. Проверьте путь ObjectName (например Catalogs/МойСправочник)."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$helpXmlPath = Join-Path $extDir "Help.xml"
|
||||||
|
if (Test-Path $helpXmlPath) {
|
||||||
|
Write-Error "Справка уже существует: $helpXmlPath"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Кодировка ---
|
||||||
|
|
||||||
|
$encBom = New-Object System.Text.UTF8Encoding($true)
|
||||||
|
|
||||||
|
# --- 1. Help.xml ---
|
||||||
|
|
||||||
|
$helpXml = @"
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<Help xmlns="http://v8.1c.ru/8.3/xcf/extrnprops" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.17">
|
||||||
|
<Page>$Lang</Page>
|
||||||
|
</Help>
|
||||||
|
"@
|
||||||
|
|
||||||
|
[System.IO.File]::WriteAllText($helpXmlPath, $helpXml, $encBom)
|
||||||
|
|
||||||
|
# --- 2. Help/<lang>.html ---
|
||||||
|
|
||||||
|
$helpDir = Join-Path $extDir "Help"
|
||||||
|
New-Item -ItemType Directory -Path $helpDir -Force | Out-Null
|
||||||
|
|
||||||
|
$helpHtmlPath = Join-Path $helpDir "$Lang.html"
|
||||||
|
|
||||||
|
$helpHtml = @"
|
||||||
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
||||||
|
<link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"/>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>$ObjectName</h1>
|
||||||
|
<p>Описание.</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"@
|
||||||
|
|
||||||
|
[System.IO.File]::WriteAllText($helpHtmlPath, $helpHtml, $encBom)
|
||||||
|
|
||||||
|
# --- 3. Проверка IncludeHelpInContents в метаданных форм ---
|
||||||
|
|
||||||
|
$formsDir = Join-Path $objectDir "Forms"
|
||||||
|
if (Test-Path $formsDir) {
|
||||||
|
$formMetaFiles = Get-ChildItem -Path $formsDir -Filter "*.xml" -File
|
||||||
|
foreach ($formMeta in $formMetaFiles) {
|
||||||
|
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||||
|
$xmlDoc.PreserveWhitespace = $true
|
||||||
|
$xmlDoc.Load($formMeta.FullName)
|
||||||
|
|
||||||
|
$nsMgr = New-Object System.Xml.XmlNamespaceManager($xmlDoc.NameTable)
|
||||||
|
$nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||||
|
|
||||||
|
$includeHelp = $xmlDoc.SelectSingleNode("//md:IncludeHelpInContents", $nsMgr)
|
||||||
|
if (-not $includeHelp) {
|
||||||
|
# Добавить после <FormType>
|
||||||
|
$formType = $xmlDoc.SelectSingleNode("//md:FormType", $nsMgr)
|
||||||
|
if ($formType) {
|
||||||
|
$newElem = $xmlDoc.CreateElement("IncludeHelpInContents", "http://v8.1c.ru/8.3/MDClasses")
|
||||||
|
$newElem.InnerText = "false"
|
||||||
|
$parent = $formType.ParentNode
|
||||||
|
$nextSibling = $formType.NextSibling
|
||||||
|
# Вставить перенос + табуляцию + элемент
|
||||||
|
$ws = $xmlDoc.CreateWhitespace("`n`t`t`t")
|
||||||
|
if ($nextSibling) {
|
||||||
|
$parent.InsertBefore($ws, $nextSibling) | Out-Null
|
||||||
|
$parent.InsertBefore($newElem, $ws) | Out-Null
|
||||||
|
} else {
|
||||||
|
$parent.AppendChild($ws) | Out-Null
|
||||||
|
$parent.AppendChild($newElem) | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$settings = New-Object System.Xml.XmlWriterSettings
|
||||||
|
$settings.Encoding = $encBom
|
||||||
|
$settings.Indent = $false
|
||||||
|
$stream = New-Object System.IO.FileStream($formMeta.FullName, [System.IO.FileMode]::Create)
|
||||||
|
$writer = [System.Xml.XmlWriter]::Create($stream, $settings)
|
||||||
|
$xmlDoc.Save($writer)
|
||||||
|
$writer.Close()
|
||||||
|
$stream.Close()
|
||||||
|
|
||||||
|
Write-Host " IncludeHelpInContents добавлен: $($formMeta.Name)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "[OK] Создана справка: $ObjectName"
|
||||||
|
Write-Host " Метаданные: $helpXmlPath"
|
||||||
|
Write-Host " Страница: $helpHtmlPath"
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user