mirror of
https://github.com/Nikolay-Shirokov/cc-1c-skills.git
synced 2026-07-19 17:19:42 +03:00
Compare commits
635 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4f9d9aee97 | |||
| f3466e19fd | |||
| ebf92a8780 | |||
| 3d80191ca7 | |||
| 6c60398406 | |||
| 60de083a05 | |||
| 5690c82ab8 | |||
| dc0382cc06 | |||
| b1e29253d5 | |||
| 07b2ec36af | |||
| b4514dc350 | |||
| 8ad5d80f7f | |||
| fc19df604b | |||
| 76800fc92b | |||
| 36cd63d8bb | |||
| e216db5734 | |||
| a59be4b914 | |||
| 4b8d3b67dc | |||
| 6650d2b516 | |||
| 6b63177687 | |||
| 13174b63b1 | |||
| 433a2955b5 | |||
| 42b96bbd21 | |||
| bd3b40852a | |||
| 336dade274 | |||
| 99e9c1e0b8 | |||
| 3c3ed2ff46 | |||
| d75b4d96ca | |||
| 704fbc9f28 | |||
| cd74afa5e0 | |||
| 370873511d | |||
| 9ced410d8f | |||
| 50ba38a9f6 | |||
| d4b105bbe4 | |||
| 204a262746 | |||
| 210bde7b2e | |||
| a932841418 | |||
| 576f6dda8a | |||
| 1a5b788305 | |||
| b39da27d20 | |||
| 1f23afe6f9 | |||
| eda7279de0 | |||
| b3c2602439 | |||
| 853313faed | |||
| b7fbede819 | |||
| bdc38caffa | |||
| 2a86df1c98 | |||
| 2e1487fd17 | |||
| 3729b63b89 | |||
| c3ec51e174 | |||
| fb58a04700 | |||
| a30b720c89 | |||
| 54d47aadad | |||
| 3f23be8219 | |||
| f5dd677ac8 | |||
| 02e9053d00 | |||
| bd462f4cc3 | |||
| be74d224be | |||
| 1b46eb4d85 | |||
| 1cea9e794e | |||
| 00fafd4af5 | |||
| e30b518935 | |||
| afdfc97fb1 | |||
| 82e70d2c30 | |||
| aedf6df674 | |||
| 0d31d17204 | |||
| 2206c4cf3e | |||
| 8a9f285da9 | |||
| e5e3f199f2 | |||
| 3ee715939b | |||
| b8ab791456 | |||
| 97a2ef91d5 | |||
| a41897a966 | |||
| 076bbcb9d5 | |||
| 3c48451704 | |||
| 801ceea2c0 | |||
| 63de8bd27c | |||
| d1e770c843 | |||
| e3069ceb36 | |||
| 0b2c09f8d9 | |||
| 0d5d3451ff | |||
| 7a8f437e77 | |||
| dc4ffa1fc8 | |||
| 6805b9da02 | |||
| aa93031a3f | |||
| 037062c728 | |||
| 9cbda1989a | |||
| d34ddd41ff | |||
| 96d1dea552 | |||
| 83b289de32 | |||
| 384e68cab4 | |||
| 46e065adb9 | |||
| fdfe4ac2f4 | |||
| afacaa5ade | |||
| 73242ee60e | |||
| e2924c4ae0 | |||
| 123fc41b06 | |||
| 338faa253d | |||
| d3520a8945 | |||
| e731bde7f0 | |||
| 321e426f98 | |||
| 54c04cfe76 | |||
| 9727635e5d | |||
| 6404016afb | |||
| 17afd807d2 | |||
| 9bfc431a6a | |||
| d755c41233 | |||
| 87e636f644 | |||
| ae1dcaac07 | |||
| d155086444 | |||
| 940eafb8e4 | |||
| e4dcef8c90 | |||
| 08688f5cab | |||
| 1bc5e8f07a | |||
| 358830c65b | |||
| 3ba6072660 | |||
| 20adf4f463 | |||
| d5aacc9e60 | |||
| 3bd69baae6 | |||
| b0fdc32053 | |||
| 731a652cae | |||
| dd88f78969 | |||
| ff068202e3 | |||
| 91798e3838 | |||
| 9620c3846a | |||
| ffc34904c5 | |||
| b008c820f9 | |||
| e5697d6f5c | |||
| 29ee294de6 | |||
| d72cbacfd6 | |||
| c8a7ba4683 | |||
| ea8b28280d | |||
| eebc2a0679 | |||
| 974e8ff5e4 | |||
| 47c2e5d48f | |||
| e56a932ee2 | |||
| 69f5e0b7ae | |||
| 84462e3dd9 | |||
| d574320849 | |||
| 90ff1d53b6 | |||
| 09bc0d00b8 | |||
| 66c6dc7aa1 | |||
| 1d89b3ec69 | |||
| 43d1d09ee8 | |||
| 404e6c6851 | |||
| 009022d04b | |||
| 70e684d189 | |||
| 72bad1aaaa | |||
| 29a5cbae4c | |||
| be1bbb2d26 | |||
| 5281fd54f2 | |||
| f697ba3ff3 | |||
| 0778cc89ee | |||
| 28b2765f68 | |||
| 0d116863ec | |||
| bc6bc01047 | |||
| 972cd5061d | |||
| 4565808b77 | |||
| 250978c2fd | |||
| 4551525718 | |||
| 9422c66df4 | |||
| a1b3fdd4e2 | |||
| d6d44b8b35 | |||
| b480fa0b49 | |||
| 44a84f8ce7 | |||
| dcacecff7f | |||
| 8b38f8f78d | |||
| 74b3f76a32 | |||
| 671be7c6b5 | |||
| 4a697db47a | |||
| 34f582ddef | |||
| eec626eb6f | |||
| 312d058412 | |||
| 95776a4248 | |||
| 347722ef0d | |||
| 9f6793abae | |||
| 0ddb675502 | |||
| d2dfcfd160 | |||
| 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 |
@@ -24,7 +24,7 @@ allowed-tools:
|
|||||||
| `NoValidate` | Пропустить авто-валидацию |
|
| `NoValidate` | Пропустить авто-валидацию |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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'
|
||||||
```
|
```
|
||||||
|
|
||||||
## Операции
|
## Операции
|
||||||
+3
-137
@@ -1,4 +1,4 @@
|
|||||||
# cf-edit v1.10 — Edit 1C configuration root (Configuration.xml)
|
# cf-edit v1.4 — Edit 1C configuration root (Configuration.xml)
|
||||||
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
param(
|
param(
|
||||||
[Parameter(Mandatory)][Alias('Path')][string]$ConfigPath,
|
[Parameter(Mandatory)][Alias('Path')][string]$ConfigPath,
|
||||||
@@ -29,139 +29,6 @@ if (-not (Test-Path $ConfigPath)) { Write-Error "File not found: $ConfigPath"; e
|
|||||||
$resolvedPath = (Resolve-Path $ConfigPath).Path
|
$resolvedPath = (Resolve-Path $ConfigPath).Path
|
||||||
$script:configDir = [System.IO.Path]::GetDirectoryName($resolvedPath)
|
$script:configDir = [System.IO.Path]::GetDirectoryName($resolvedPath)
|
||||||
|
|
||||||
# --- Support guard (Ext/ParentConfigurations.bin) ---
|
|
||||||
# See docs/1c-support-state-spec.md. Blocks edits of vendor objects "на замке" /
|
|
||||||
# read-only configs unless allowed. Trigger = bin present; reaction from
|
|
||||||
# .v8-project.json editingAllowedCheck (deny|warn|off, default deny). Never
|
|
||||||
# throws — guard errors degrade to allow.
|
|
||||||
function Get-RootUuid([string]$xmlPath) {
|
|
||||||
if (-not (Test-Path $xmlPath)) { return $null }
|
|
||||||
try {
|
|
||||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
|
||||||
$el = $mx.DocumentElement.FirstChild
|
|
||||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
|
||||||
if ($el) { $u = $el.GetAttribute("uuid"); if ($u) { return $u } }
|
|
||||||
} catch {}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
function Test-ExternalObjectRoot([string]$xmlPath) {
|
|
||||||
if (-not (Test-Path $xmlPath)) { return $false }
|
|
||||||
try {
|
|
||||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
|
||||||
$el = $mx.DocumentElement.FirstChild
|
|
||||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
|
||||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
|
||||||
} catch {}
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
function Find-V8Project([string]$startDir) {
|
|
||||||
$d = $startDir
|
|
||||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
|
||||||
$pj = Join-Path $d ".v8-project.json"
|
|
||||||
if (Test-Path $pj) { return $pj }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
function Get-EditMode([string]$cfgDir) {
|
|
||||||
try {
|
|
||||||
$pj = Find-V8Project (Get-Location).Path
|
|
||||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
|
||||||
if (-not $pj) { return 'deny' }
|
|
||||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
|
||||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
|
||||||
if ($proj.databases) {
|
|
||||||
foreach ($db in $proj.databases) {
|
|
||||||
if ($db.configSrc) {
|
|
||||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
|
||||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
|
||||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
|
||||||
return 'deny'
|
|
||||||
} catch { return 'deny' }
|
|
||||||
}
|
|
||||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
|
||||||
try {
|
|
||||||
$rp = $targetPath
|
|
||||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if (Test-ExternalObjectRoot $rp) { return }
|
|
||||||
$elemUuid = Get-RootUuid $rp
|
|
||||||
$cfgDir = $null; $binPath = $null
|
|
||||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
|
||||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
|
||||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
|
||||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
|
||||||
if (-not $cfgDir) {
|
|
||||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
|
||||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
|
||||||
}
|
|
||||||
if ($elemUuid -and $cfgDir) { break }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
# New object (no element file): fall back to config root uuid.
|
|
||||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
|
||||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
|
||||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
|
||||||
if ($bytes.Length -le 32) { return }
|
|
||||||
$start = 0
|
|
||||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
|
||||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
|
||||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
|
||||||
if (-not $hm.Success) { return }
|
|
||||||
$G = [int]$hm.Groups[1].Value
|
|
||||||
$K = [int]$hm.Groups[2].Value
|
|
||||||
if ($K -eq 0) { return }
|
|
||||||
$best = $null
|
|
||||||
if ($elemUuid) {
|
|
||||||
$u = [regex]::Escape($elemUuid.ToLower())
|
|
||||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
|
||||||
$f1 = [int]$m.Groups[1].Value
|
|
||||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$blocked = $false; $code = ""; $reason = ""
|
|
||||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
|
||||||
elseif ($require -eq 'removed') {
|
|
||||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
|
||||||
}
|
|
||||||
if (-not $blocked) { return }
|
|
||||||
$mode = Get-EditMode $cfgDir
|
|
||||||
if ($mode -eq 'off') { return }
|
|
||||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
|
||||||
# latter throws and would be swallowed by this function's own catch.
|
|
||||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
|
||||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if ($code -eq "capability-off") {
|
|
||||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
|
||||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
} elseif ($code -eq "not-removed") {
|
|
||||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
|
||||||
} else {
|
|
||||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
|
||||||
}
|
|
||||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
|
||||||
exit 1
|
|
||||||
} catch { return }
|
|
||||||
}
|
|
||||||
|
|
||||||
Assert-EditAllowed $resolvedPath 'editable'
|
|
||||||
|
|
||||||
# --- Load XML with PreserveWhitespace ---
|
# --- Load XML with PreserveWhitespace ---
|
||||||
$script:xmlDoc = New-Object System.Xml.XmlDocument
|
$script:xmlDoc = New-Object System.Xml.XmlDocument
|
||||||
$script:xmlDoc.PreserveWhitespace = $true
|
$script:xmlDoc.PreserveWhitespace = $true
|
||||||
@@ -209,7 +76,7 @@ Info "Configuration: $($script:objName)"
|
|||||||
$script:typeOrder = @(
|
$script:typeOrder = @(
|
||||||
"Language","Subsystem","StyleItem","Style",
|
"Language","Subsystem","StyleItem","Style",
|
||||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||||
@@ -225,7 +92,7 @@ $script:typeOrder = @(
|
|||||||
$script:typeToDir = @{
|
$script:typeToDir = @{
|
||||||
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
||||||
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"; "CommonTemplate"="CommonTemplates"
|
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"; "CommonTemplate"="CommonTemplates"
|
||||||
"FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"; "Bot"="Bots"; "CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"
|
"FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"; "CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"
|
||||||
"XDTOPackage"="XDTOPackages"; "WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
"XDTOPackage"="XDTOPackages"; "WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
||||||
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"; "SettingsStorage"="SettingsStorages"; "FunctionalOption"="FunctionalOptions"
|
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"; "SettingsStorage"="SettingsStorages"; "FunctionalOption"="FunctionalOptions"
|
||||||
"FunctionalOptionsParameter"="FunctionalOptionsParameters"; "DefinedType"="DefinedTypes"; "CommonCommand"="CommonCommands"; "CommandGroup"="CommandGroups"
|
"FunctionalOptionsParameter"="FunctionalOptionsParameters"; "DefinedType"="DefinedTypes"; "CommonCommand"="CommonCommands"; "CommandGroup"="CommandGroups"
|
||||||
@@ -713,7 +580,6 @@ $script:ruTypeMap = @{
|
|||||||
"регистррасчёта" = "CalculationRegister"
|
"регистррасчёта" = "CalculationRegister"
|
||||||
"бизнеспроцесс" = "BusinessProcess"
|
"бизнеспроцесс" = "BusinessProcess"
|
||||||
"задача" = "Task"
|
"задача" = "Task"
|
||||||
"бот" = "Bot"
|
|
||||||
"планобмена" = "ExchangePlan"
|
"планобмена" = "ExchangePlan"
|
||||||
"хранилищенастроек" = "SettingsStorage"
|
"хранилищенастроек" = "SettingsStorage"
|
||||||
}
|
}
|
||||||
+7
-224
@@ -1,194 +1,16 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-edit v1.10 — Edit 1C configuration root (Configuration.xml)
|
# cf-edit v1.4 — Edit 1C configuration root (Configuration.xml)
|
||||||
# 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
|
||||||
import os
|
import os
|
||||||
import re
|
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import uuid as _uuid
|
import uuid as _uuid
|
||||||
from html import escape as html_escape
|
from html import escape as html_escape
|
||||||
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_is_external_root(xml_path):
|
|
||||||
if not os.path.isfile(xml_path):
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
mx = etree.parse(xml_path).getroot()
|
|
||||||
for child in mx:
|
|
||||||
if isinstance(child.tag, str):
|
|
||||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _sg_find_v8project(start_dir):
|
|
||||||
d = start_dir
|
|
||||||
for _ in range(20):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
pj = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pj):
|
|
||||||
return pj
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _sg_get_edit_mode(cfg_dir):
|
|
||||||
try:
|
|
||||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
|
||||||
if not pj:
|
|
||||||
return "deny"
|
|
||||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
|
||||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
|
||||||
for db in proj.get("databases", []):
|
|
||||||
src = db.get("configSrc")
|
|
||||||
if src:
|
|
||||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
|
||||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
|
||||||
if db.get("editingAllowedCheck"):
|
|
||||||
return db["editingAllowedCheck"]
|
|
||||||
if proj.get("editingAllowedCheck"):
|
|
||||||
return proj["editingAllowedCheck"]
|
|
||||||
return "deny"
|
|
||||||
except Exception:
|
|
||||||
return "deny"
|
|
||||||
|
|
||||||
|
|
||||||
def assert_edit_allowed(target_path, require):
|
|
||||||
try:
|
|
||||||
rp = os.path.abspath(target_path)
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if _sg_is_external_root(rp):
|
|
||||||
return
|
|
||||||
elem_uuid = _sg_root_uuid(rp)
|
|
||||||
cfg_dir = None
|
|
||||||
bin_path = None
|
|
||||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
|
||||||
for _ in range(12):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
if _sg_is_external_root(d + ".xml"):
|
|
||||||
return
|
|
||||||
if not elem_uuid:
|
|
||||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
|
||||||
if not cfg_dir:
|
|
||||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
|
||||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
|
||||||
cfg_dir = d
|
|
||||||
bin_path = cand
|
|
||||||
if elem_uuid and cfg_dir:
|
|
||||||
break
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
if not elem_uuid and cfg_dir:
|
|
||||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
|
||||||
if not bin_path or not os.path.exists(bin_path):
|
|
||||||
return
|
|
||||||
data = open(bin_path, "rb").read()
|
|
||||||
if len(data) <= 32:
|
|
||||||
return
|
|
||||||
if data[:3] == b"\xef\xbb\xbf":
|
|
||||||
data = data[3:]
|
|
||||||
text = data.decode("utf-8", "replace")
|
|
||||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
|
||||||
if not h:
|
|
||||||
return
|
|
||||||
g = int(h.group(1))
|
|
||||||
k = int(h.group(2))
|
|
||||||
if k == 0:
|
|
||||||
return
|
|
||||||
best = None
|
|
||||||
if elem_uuid:
|
|
||||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
|
||||||
f1 = int(m.group(1))
|
|
||||||
if best is None or f1 < best:
|
|
||||||
best = f1
|
|
||||||
blocked = False
|
|
||||||
code = ""
|
|
||||||
reason = ""
|
|
||||||
if g == 1:
|
|
||||||
blocked = True
|
|
||||||
code = "capability-off"
|
|
||||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
|
||||||
elif require == "removed":
|
|
||||||
if best is not None and best != 2:
|
|
||||||
blocked = True
|
|
||||||
code = "not-removed"
|
|
||||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
|
||||||
else:
|
|
||||||
if best is not None and best == 0:
|
|
||||||
blocked = True
|
|
||||||
code = "locked"
|
|
||||||
reason = "объект на замке — редактирование сломает обновления"
|
|
||||||
if not blocked:
|
|
||||||
return
|
|
||||||
mode = _sg_get_edit_mode(cfg_dir)
|
|
||||||
if mode == "off":
|
|
||||||
return
|
|
||||||
if mode == "warn":
|
|
||||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
|
||||||
return
|
|
||||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if code == "capability-off":
|
|
||||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
|
||||||
fix = (
|
|
||||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
|
||||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
|
||||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
|
||||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
)
|
|
||||||
elif code == "not-removed":
|
|
||||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
fix = (
|
|
||||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
fix = (
|
|
||||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
|
||||||
)
|
|
||||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
|
||||||
sys.exit(1)
|
|
||||||
except SystemExit:
|
|
||||||
raise
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
MD_NS = "http://v8.1c.ru/8.3/MDClasses"
|
MD_NS = "http://v8.1c.ru/8.3/MDClasses"
|
||||||
XR_NS = "http://v8.1c.ru/8.3/xcf/readable"
|
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"
|
||||||
@@ -199,7 +21,7 @@ XS_NS = "http://www.w3.org/2001/XMLSchema"
|
|||||||
TYPE_ORDER = [
|
TYPE_ORDER = [
|
||||||
"Language", "Subsystem", "StyleItem", "Style",
|
"Language", "Subsystem", "StyleItem", "Style",
|
||||||
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
||||||
"FilterCriterion", "CommonModule", "Bot", "CommonAttribute", "ExchangePlan",
|
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
|
||||||
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
||||||
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
||||||
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
||||||
@@ -215,7 +37,7 @@ TYPE_ORDER = [
|
|||||||
TYPE_TO_DIR = {
|
TYPE_TO_DIR = {
|
||||||
"Language": "Languages", "Subsystem": "Subsystems", "StyleItem": "StyleItems", "Style": "Styles",
|
"Language": "Languages", "Subsystem": "Subsystems", "StyleItem": "StyleItems", "Style": "Styles",
|
||||||
"CommonPicture": "CommonPictures", "SessionParameter": "SessionParameters", "Role": "Roles", "CommonTemplate": "CommonTemplates",
|
"CommonPicture": "CommonPictures", "SessionParameter": "SessionParameters", "Role": "Roles", "CommonTemplate": "CommonTemplates",
|
||||||
"FilterCriterion": "FilterCriteria", "CommonModule": "CommonModules", "Bot": "Bots", "CommonAttribute": "CommonAttributes", "ExchangePlan": "ExchangePlans",
|
"FilterCriterion": "FilterCriteria", "CommonModule": "CommonModules", "CommonAttribute": "CommonAttributes", "ExchangePlan": "ExchangePlans",
|
||||||
"XDTOPackage": "XDTOPackages", "WebService": "WebServices", "HTTPService": "HTTPServices", "WSReference": "WSReferences",
|
"XDTOPackage": "XDTOPackages", "WebService": "WebServices", "HTTPService": "HTTPServices", "WSReference": "WSReferences",
|
||||||
"EventSubscription": "EventSubscriptions", "ScheduledJob": "ScheduledJobs", "SettingsStorage": "SettingsStorages", "FunctionalOption": "FunctionalOptions",
|
"EventSubscription": "EventSubscriptions", "ScheduledJob": "ScheduledJobs", "SettingsStorage": "SettingsStorages", "FunctionalOption": "FunctionalOptions",
|
||||||
"FunctionalOptionsParameter": "FunctionalOptionsParameters", "DefinedType": "DefinedTypes", "CommonCommand": "CommonCommands", "CommandGroup": "CommandGroups",
|
"FunctionalOptionsParameter": "FunctionalOptionsParameters", "DefinedType": "DefinedTypes", "CommonCommand": "CommonCommands", "CommandGroup": "CommandGroups",
|
||||||
@@ -324,48 +146,12 @@ def parse_batch_value(val):
|
|||||||
return items
|
return items
|
||||||
|
|
||||||
|
|
||||||
def _detect_xml_style(path):
|
|
||||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
|
||||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
|
||||||
try:
|
|
||||||
raw = open(path, "rb").read()
|
|
||||||
except OSError:
|
|
||||||
return None
|
|
||||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
|
||||||
body = raw[3:] if bom else raw
|
|
||||||
crlf = b"\r\n" in body
|
|
||||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
|
||||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
|
||||||
final_nl = body.endswith(b"\n")
|
|
||||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
|
||||||
|
|
||||||
|
|
||||||
def _finalize_xml_bytes(xml_bytes, style):
|
|
||||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
|
||||||
enc_decl = style["enc"] if style else "utf-8"
|
|
||||||
xml_bytes = xml_bytes.replace(
|
|
||||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
|
||||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
|
||||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
|
||||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
|
||||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
|
||||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
|
||||||
want_final_nl = style["final_nl"] if style else True
|
|
||||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
|
||||||
if want_final_nl:
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
|
||||||
if style and style["crlf"]:
|
|
||||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
|
||||||
return xml_bytes
|
|
||||||
|
|
||||||
|
|
||||||
def save_xml_bom(tree, path):
|
def save_xml_bom(tree, path):
|
||||||
style = _detect_xml_style(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 = _finalize_xml_bytes(xml_bytes, style)
|
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" 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:
|
||||||
if style is None or style["bom"]:
|
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
|
|
||||||
@@ -404,8 +190,6 @@ def main():
|
|||||||
resolved_path = os.path.abspath(config_path)
|
resolved_path = os.path.abspath(config_path)
|
||||||
config_dir = os.path.dirname(resolved_path)
|
config_dir = os.path.dirname(resolved_path)
|
||||||
|
|
||||||
assert_edit_allowed(resolved_path, "editable")
|
|
||||||
|
|
||||||
xml_parser = etree.XMLParser(remove_blank_text=False)
|
xml_parser = etree.XMLParser(remove_blank_text=False)
|
||||||
tree = etree.parse(resolved_path, xml_parser)
|
tree = etree.parse(resolved_path, xml_parser)
|
||||||
xml_root = tree.getroot()
|
xml_root = tree.getroot()
|
||||||
@@ -824,7 +608,6 @@ def main():
|
|||||||
"регистррасчета": "CalculationRegister",
|
"регистррасчета": "CalculationRegister",
|
||||||
"регистррасчёта": "CalculationRegister",
|
"регистррасчёта": "CalculationRegister",
|
||||||
"бизнеспроцесс": "BusinessProcess",
|
"бизнеспроцесс": "BusinessProcess",
|
||||||
"бот": "Bot",
|
|
||||||
"задача": "Task", "планобмена": "ExchangePlan",
|
"задача": "Task", "планобмена": "ExchangePlan",
|
||||||
"хранилищенастроек": "SettingsStorage",
|
"хранилищенастроек": "SettingsStorage",
|
||||||
}
|
}
|
||||||
@@ -1023,7 +806,7 @@ def main():
|
|||||||
if os.path.isfile(validate_script):
|
if os.path.isfile(validate_script):
|
||||||
print()
|
print()
|
||||||
print("--- Running cf-validate ---")
|
print("--- Running cf-validate ---")
|
||||||
subprocess.run([sys.executable, validate_script, "-ConfigPath", resolved_path])
|
subprocess.run([sys.executable, validate_script, "-ConfigPath", "-Path", resolved_path])
|
||||||
|
|
||||||
# --- Summary ---
|
# --- Summary ---
|
||||||
print()
|
print()
|
||||||
@@ -23,7 +23,7 @@ allowed-tools:
|
|||||||
| `OutFile` | Записать результат в файл (UTF-8 BOM) |
|
| `OutFile` | Записать результат в файл (UTF-8 BOM) |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/cf-info/scripts/cf-info.py" -ConfigPath "<путь>"
|
powershell.exe -NoProfile -File .claude/skills/cf-info/scripts/cf-info.ps1 -ConfigPath "<путь>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Три режима
|
## Три режима
|
||||||
+2
-78
@@ -1,4 +1,4 @@
|
|||||||
# cf-info v1.4 — Compact summary of 1C configuration root
|
# cf-info v1.2 — 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)][Alias('Path')][string]$ConfigPath,
|
||||||
@@ -89,7 +89,7 @@ function Get-PropML([string]$propName) {
|
|||||||
$typeOrder = @(
|
$typeOrder = @(
|
||||||
"Language","Subsystem","StyleItem","Style",
|
"Language","Subsystem","StyleItem","Style",
|
||||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||||
@@ -105,7 +105,6 @@ $typeRuNames = @{
|
|||||||
"Language"="Языки"; "Subsystem"="Подсистемы"; "StyleItem"="Элементы стиля"; "Style"="Стили"
|
"Language"="Языки"; "Subsystem"="Подсистемы"; "StyleItem"="Элементы стиля"; "Style"="Стили"
|
||||||
"CommonPicture"="Общие картинки"; "SessionParameter"="Параметры сеанса"; "Role"="Роли"
|
"CommonPicture"="Общие картинки"; "SessionParameter"="Параметры сеанса"; "Role"="Роли"
|
||||||
"CommonTemplate"="Общие макеты"; "FilterCriterion"="Критерии отбора"; "CommonModule"="Общие модули"
|
"CommonTemplate"="Общие макеты"; "FilterCriterion"="Критерии отбора"; "CommonModule"="Общие модули"
|
||||||
"Bot"="Боты"
|
|
||||||
"CommonAttribute"="Общие реквизиты"; "ExchangePlan"="Планы обмена"; "XDTOPackage"="XDTO-пакеты"
|
"CommonAttribute"="Общие реквизиты"; "ExchangePlan"="Планы обмена"; "XDTOPackage"="XDTO-пакеты"
|
||||||
"WebService"="Веб-сервисы"; "HTTPService"="HTTP-сервисы"; "WSReference"="WS-ссылки"
|
"WebService"="Веб-сервисы"; "HTTPService"="HTTP-сервисы"; "WSReference"="WS-ссылки"
|
||||||
"EventSubscription"="Подписки на события"; "ScheduledJob"="Регламентные задания"
|
"EventSubscription"="Подписки на события"; "ScheduledJob"="Регламентные задания"
|
||||||
@@ -219,78 +218,6 @@ function Get-HomePageLayout {
|
|||||||
|
|
||||||
$script:homePage = Get-HomePageLayout
|
$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) {
|
function Format-HomePageItem($it, [bool]$detailed) {
|
||||||
$badges = @()
|
$badges = @()
|
||||||
$badges += "h=$($it.height)"
|
$badges += "h=$($it.height)"
|
||||||
@@ -326,7 +253,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"
|
||||||
@@ -358,7 +284,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"
|
||||||
@@ -461,7 +386,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 ""
|
||||||
+2
-74
@@ -1,10 +1,9 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-info v1.4 — Compact summary of 1C configuration root
|
# cf-info v1.2 — 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
|
||||||
@@ -95,7 +94,7 @@ def get_prop_ml(prop_name):
|
|||||||
type_order = [
|
type_order = [
|
||||||
"Language", "Subsystem", "StyleItem", "Style",
|
"Language", "Subsystem", "StyleItem", "Style",
|
||||||
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
"CommonPicture", "SessionParameter", "Role", "CommonTemplate",
|
||||||
"FilterCriterion", "CommonModule", "Bot", "CommonAttribute", "ExchangePlan",
|
"FilterCriterion", "CommonModule", "CommonAttribute", "ExchangePlan",
|
||||||
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
"XDTOPackage", "WebService", "HTTPService", "WSReference",
|
||||||
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
"EventSubscription", "ScheduledJob", "SettingsStorage", "FunctionalOption",
|
||||||
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
"FunctionalOptionsParameter", "DefinedType", "CommonCommand", "CommandGroup",
|
||||||
@@ -111,7 +110,6 @@ type_ru_names = {
|
|||||||
"Language": "Языки", "Subsystem": "Подсистемы", "StyleItem": "Элементы стиля", "Style": "Стили",
|
"Language": "Языки", "Subsystem": "Подсистемы", "StyleItem": "Элементы стиля", "Style": "Стили",
|
||||||
"CommonPicture": "Общие картинки", "SessionParameter": "Параметры сеанса", "Role": "Роли",
|
"CommonPicture": "Общие картинки", "SessionParameter": "Параметры сеанса", "Role": "Роли",
|
||||||
"CommonTemplate": "Общие макеты", "FilterCriterion": "Критерии отбора", "CommonModule": "Общие модули",
|
"CommonTemplate": "Общие макеты", "FilterCriterion": "Критерии отбора", "CommonModule": "Общие модули",
|
||||||
"Bot": "Боты",
|
|
||||||
"CommonAttribute": "Общие реквизиты", "ExchangePlan": "Планы обмена", "XDTOPackage": "XDTO-пакеты",
|
"CommonAttribute": "Общие реквизиты", "ExchangePlan": "Планы обмена", "XDTOPackage": "XDTO-пакеты",
|
||||||
"WebService": "Веб-сервисы", "HTTPService": "HTTP-сервисы", "WSReference": "WS-ссылки",
|
"WebService": "Веб-сервисы", "HTTPService": "HTTP-сервисы", "WSReference": "WS-ссылки",
|
||||||
"EventSubscription": "Подписки на события", "ScheduledJob": "Регламентные задания",
|
"EventSubscription": "Подписки на события", "ScheduledJob": "Регламентные задания",
|
||||||
@@ -221,71 +219,6 @@ def get_home_page_layout():
|
|||||||
|
|
||||||
home_page = get_home_page_layout()
|
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):
|
def format_home_page_item(it, detailed):
|
||||||
badges = [f"h={it['height']}"]
|
badges = [f"h={it['height']}"]
|
||||||
if not it["common"]:
|
if not it["common"]:
|
||||||
@@ -316,7 +249,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")
|
||||||
@@ -349,8 +281,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}")
|
||||||
@@ -439,8 +369,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}")
|
||||||
@@ -24,7 +24,7 @@ allowed-tools:
|
|||||||
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
| `CompatibilityMode` | Режим совместимости (default: `Version8_3_24`) |
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/cf-init/scripts/cf-init.py" -Name "МояКонфигурация"
|
powershell.exe -NoProfile -File .claude/skills/cf-init/scripts/cf-init.ps1 -Name "МояКонфигурация"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
@@ -24,6 +24,6 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/cf-validate/scripts/cf-validate.py" -ConfigPath "upload/cfempty"
|
powershell.exe -NoProfile -File .claude/skills/cf-validate/scripts/cf-validate.ps1 -ConfigPath "upload/cfempty"
|
||||||
python ".codeassistant/skills/cf-validate/scripts/cf-validate.py" -ConfigPath "upload/cfempty/Configuration.xml"
|
powershell.exe -NoProfile -File .claude/skills/cf-validate/scripts/cf-validate.ps1 -ConfigPath "upload/cfempty/Configuration.xml"
|
||||||
```
|
```
|
||||||
+3
-4
@@ -1,4 +1,4 @@
|
|||||||
# cf-validate v1.4 — Validate 1C configuration root structure
|
# cf-validate v1.3 — 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)]
|
||||||
@@ -104,11 +104,11 @@ $validClassIds = @(
|
|||||||
"fb282519-d103-4dd3-bc12-cb271d631dfc" # home page / client app interface
|
"fb282519-d103-4dd3-bc12-cb271d631dfc" # home page / client app interface
|
||||||
)
|
)
|
||||||
|
|
||||||
# 45 types in canonical order
|
# 44 types in canonical order
|
||||||
$childObjectTypes = @(
|
$childObjectTypes = @(
|
||||||
"Language","Subsystem","StyleItem","Style",
|
"Language","Subsystem","StyleItem","Style",
|
||||||
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
"CommonPicture","SessionParameter","Role","CommonTemplate",
|
||||||
"FilterCriterion","CommonModule","Bot","CommonAttribute","ExchangePlan",
|
"FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
|
||||||
"XDTOPackage","WebService","HTTPService","WSReference",
|
"XDTOPackage","WebService","HTTPService","WSReference",
|
||||||
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
"EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
|
||||||
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
"FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
|
||||||
@@ -125,7 +125,6 @@ $childTypeDirMap = @{
|
|||||||
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
"Language"="Languages"; "Subsystem"="Subsystems"; "StyleItem"="StyleItems"; "Style"="Styles"
|
||||||
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"
|
"CommonPicture"="CommonPictures"; "SessionParameter"="SessionParameters"; "Role"="Roles"
|
||||||
"CommonTemplate"="CommonTemplates"; "FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"
|
"CommonTemplate"="CommonTemplates"; "FilterCriterion"="FilterCriteria"; "CommonModule"="CommonModules"
|
||||||
"Bot"="Bots"
|
|
||||||
"CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"; "XDTOPackage"="XDTOPackages"
|
"CommonAttribute"="CommonAttributes"; "ExchangePlan"="ExchangePlans"; "XDTOPackage"="XDTOPackages"
|
||||||
"WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
"WebService"="WebServices"; "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
|
||||||
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
|
"EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
|
||||||
+3
-4
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cf-validate v1.4 — Validate 1C configuration XML structure
|
# cf-validate v1.3 — 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
|
||||||
@@ -33,11 +33,11 @@ VALID_CLASS_IDS = [
|
|||||||
'fb282519-d103-4dd3-bc12-cb271d631dfc', # home page / client app interface
|
'fb282519-d103-4dd3-bc12-cb271d631dfc', # home page / client app interface
|
||||||
]
|
]
|
||||||
|
|
||||||
# 45 types in canonical order
|
# 44 types in canonical order
|
||||||
CHILD_OBJECT_TYPES = [
|
CHILD_OBJECT_TYPES = [
|
||||||
'Language', 'Subsystem', 'StyleItem', 'Style',
|
'Language', 'Subsystem', 'StyleItem', 'Style',
|
||||||
'CommonPicture', 'SessionParameter', 'Role', 'CommonTemplate',
|
'CommonPicture', 'SessionParameter', 'Role', 'CommonTemplate',
|
||||||
'FilterCriterion', 'CommonModule', 'Bot', 'CommonAttribute', 'ExchangePlan',
|
'FilterCriterion', 'CommonModule', 'CommonAttribute', 'ExchangePlan',
|
||||||
'XDTOPackage', 'WebService', 'HTTPService', 'WSReference',
|
'XDTOPackage', 'WebService', 'HTTPService', 'WSReference',
|
||||||
'EventSubscription', 'ScheduledJob', 'SettingsStorage', 'FunctionalOption',
|
'EventSubscription', 'ScheduledJob', 'SettingsStorage', 'FunctionalOption',
|
||||||
'FunctionalOptionsParameter', 'DefinedType', 'CommonCommand', 'CommandGroup',
|
'FunctionalOptionsParameter', 'DefinedType', 'CommonCommand', 'CommandGroup',
|
||||||
@@ -54,7 +54,6 @@ CHILD_TYPE_DIR_MAP = {
|
|||||||
'Language': 'Languages', 'Subsystem': 'Subsystems', 'StyleItem': 'StyleItems', 'Style': 'Styles',
|
'Language': 'Languages', 'Subsystem': 'Subsystems', 'StyleItem': 'StyleItems', 'Style': 'Styles',
|
||||||
'CommonPicture': 'CommonPictures', 'SessionParameter': 'SessionParameters', 'Role': 'Roles',
|
'CommonPicture': 'CommonPictures', 'SessionParameter': 'SessionParameters', 'Role': 'Roles',
|
||||||
'CommonTemplate': 'CommonTemplates', 'FilterCriterion': 'FilterCriteria', 'CommonModule': 'CommonModules',
|
'CommonTemplate': 'CommonTemplates', 'FilterCriterion': 'FilterCriteria', 'CommonModule': 'CommonModules',
|
||||||
'Bot': 'Bots',
|
|
||||||
'CommonAttribute': 'CommonAttributes', 'ExchangePlan': 'ExchangePlans', 'XDTOPackage': 'XDTOPackages',
|
'CommonAttribute': 'CommonAttributes', 'ExchangePlan': 'ExchangePlans', 'XDTOPackage': 'XDTOPackages',
|
||||||
'WebService': 'WebServices', 'HTTPService': 'HTTPServices', 'WSReference': 'WSReferences',
|
'WebService': 'WebServices', 'HTTPService': 'HTTPServices', 'WSReference': 'WSReferences',
|
||||||
'EventSubscription': 'EventSubscriptions', 'ScheduledJob': 'ScheduledJobs',
|
'EventSubscription': 'EventSubscriptions', 'ScheduledJob': 'ScheduledJobs',
|
||||||
@@ -71,7 +71,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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.Контрагенты"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+82
-176
@@ -1,4 +1,4 @@
|
|||||||
# cfe-borrow v1.9 — Borrow objects from configuration into extension (CFE)
|
# cfe-borrow v1.3 — 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
|
||||||
@@ -444,14 +419,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,23 +481,8 @@ 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=`"$($script:formatVersion)`">") | Out-Null
|
||||||
@@ -564,10 +516,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 = $script:formatVersion }
|
||||||
# (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 +552,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 +568,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 +855,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) {
|
|
||||||
Info " Preserved existing Module.bsl"
|
|
||||||
} else {
|
|
||||||
[System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
|
[System.IO.File]::WriteAllText($moduleBslFile, "", $enc)
|
||||||
Info " Created: $moduleBslFile"
|
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 +1010,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 +1024,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 +1142,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 +1375,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,83 +1454,58 @@ 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)..."
|
if ($realDeep.Count -gt 0) {
|
||||||
|
Info " Processing $($realDeep.Count) deep path(s)..."
|
||||||
|
|
||||||
|
# Group by ObjectAttr → target catalog
|
||||||
|
$deepByAttr = @{}
|
||||||
|
foreach ($dp in $realDeep) {
|
||||||
|
if (-not $deepByAttr.ContainsKey($dp.ObjectAttr)) { $deepByAttr[$dp.ObjectAttr] = @() }
|
||||||
|
$deepByAttr[$dp.ObjectAttr] += $dp.SubAttr
|
||||||
|
}
|
||||||
|
|
||||||
foreach ($attrName in $deepByAttr.Keys) {
|
foreach ($attrName in $deepByAttr.Keys) {
|
||||||
|
# Find the attribute's type to determine target catalog
|
||||||
$attrInfo = $srcAttrs | Where-Object { $_.Name -eq $attrName } | Select-Object -First 1
|
$attrInfo = $srcAttrs | Where-Object { $_.Name -eq $attrName } | Select-Object -First 1
|
||||||
if (-not $attrInfo) { continue }
|
if (-not $attrInfo) { continue }
|
||||||
|
|
||||||
|
# Extract catalog name from type: cfg:CatalogRef.XXX
|
||||||
$catMatch = [regex]::Match($attrInfo.TypeXml, 'cfg:(\w+)Ref\.(\w+)')
|
$catMatch = [regex]::Match($attrInfo.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 $deepByAttr[$attrName]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Tabular-section deep paths: Объект.<ТЧ>.<Колонка>.<Sub> — borrow the column's catalog with the sub-attribute
|
$targetTypeName = $catMatch.Groups[1].Value
|
||||||
$tsDeepByCol = @{}
|
$targetObjName = $catMatch.Groups[2].Value
|
||||||
foreach ($dp in $deepPaths) {
|
|
||||||
if (-not $tsNames.ContainsKey($dp.ObjectAttr)) { continue }
|
|
||||||
if (-not $dp.SubSubAttr) { continue }
|
|
||||||
if ($script:standardFields -contains $dp.SubSubAttr) { continue }
|
|
||||||
$k = "$($dp.ObjectAttr)|$($dp.SubAttr)"
|
|
||||||
if (-not $tsDeepByCol.ContainsKey($k)) { $tsDeepByCol[$k] = @() }
|
|
||||||
if ($tsDeepByCol[$k] -notcontains $dp.SubSubAttr) { $tsDeepByCol[$k] += $dp.SubSubAttr }
|
|
||||||
}
|
|
||||||
if ($tsDeepByCol.Count -gt 0) {
|
|
||||||
Info " Processing $($tsDeepByCol.Count) tabular-section deep path(s)..."
|
|
||||||
foreach ($k in $tsDeepByCol.Keys) {
|
|
||||||
$parts = $k.Split("|")
|
|
||||||
$tsName = $parts[0]; $colName = $parts[1]
|
|
||||||
$tsInfo = $srcTS | Where-Object { $_.Name -eq $tsName } | Select-Object -First 1
|
|
||||||
if (-not $tsInfo) { continue }
|
|
||||||
$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 }
|
|
||||||
Borrow-DeepTargetAttrs $catMatch.Groups[1].Value $catMatch.Groups[2].Value $tsDeepByCol[$k]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Info " Main attribute borrowing complete"
|
# Ensure target is borrowed
|
||||||
}
|
|
||||||
|
|
||||||
# --- 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)) {
|
if (-not (Test-ObjectBorrowed $targetTypeName $targetObjName)) {
|
||||||
$tSrc = Read-SourceObject $targetTypeName $targetObjName
|
$tSrc = Read-SourceObject $targetTypeName $targetObjName
|
||||||
$tBorrowedXml = Build-BorrowedObjectXml $targetTypeName $targetObjName $tSrc.Uuid $tSrc.Properties
|
$tBorrowedXml = Build-BorrowedObjectXml $targetTypeName $targetObjName $tSrc.Uuid $tSrc.Properties
|
||||||
$tTargetDir = Join-Path $extDir $childTypeDirMap[$targetTypeName]
|
$tTargetDir = Join-Path $extDir $childTypeDirMap[$targetTypeName]
|
||||||
if (-not (Test-Path $tTargetDir)) { New-Item -ItemType Directory -Path $tTargetDir -Force | Out-Null }
|
if (-not (Test-Path $tTargetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $tTargetDir -Force | Out-Null
|
||||||
|
}
|
||||||
$tTargetFile = Join-Path $tTargetDir "${targetObjName}.xml"
|
$tTargetFile = Join-Path $tTargetDir "${targetObjName}.xml"
|
||||||
[System.IO.File]::WriteAllText($tTargetFile, $tBorrowedXml, $encBomLocal)
|
[System.IO.File]::WriteAllText($tTargetFile, $tBorrowedXml, $encBom)
|
||||||
Add-ToChildObjects $targetTypeName $targetObjName
|
Add-ToChildObjects $targetTypeName $targetObjName
|
||||||
$script:borrowedFiles += $tTargetFile
|
$script:borrowedFiles += $tTargetFile
|
||||||
Info " Auto-borrowed for deep path: ${targetTypeName}.${targetObjName}"
|
Info " Auto-borrowed for deep path: ${targetTypeName}.${targetObjName}"
|
||||||
}
|
}
|
||||||
|
|
||||||
# Resolve sub-attributes in target catalog and merge them in
|
# Resolve sub-attributes in target catalog
|
||||||
$subNames = @{}
|
$subNames = @{}
|
||||||
foreach ($sn in $subAttrNames) { $subNames[$sn] = $true }
|
foreach ($sn in $deepByAttr[$attrName]) { $subNames[$sn] = $true }
|
||||||
$subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
|
$subResolved = Resolve-SourceAttributes $targetTypeName $targetObjName $subNames
|
||||||
|
|
||||||
if ($subResolved.Attributes.Count -gt 0) {
|
if ($subResolved.Attributes.Count -gt 0) {
|
||||||
Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
|
Merge-AttributesIntoObject $targetTypeName $targetObjName $subResolved.Attributes
|
||||||
|
|
||||||
# Borrow ref types referenced by the sub-attributes
|
# Collect and borrow ref types from deep attributes
|
||||||
$subTypeXmls = @()
|
$subTypeXmls = @()
|
||||||
foreach ($sa in $subResolved.Attributes) { $subTypeXmls += $sa.TypeXml }
|
foreach ($sa in $subResolved.Attributes) { $subTypeXmls += $sa.TypeXml }
|
||||||
$subRefTypes = Collect-ReferenceTypes $subTypeXmls
|
$subRefTypes = Collect-ReferenceTypes $subTypeXmls
|
||||||
@@ -1613,14 +1517,21 @@ function Borrow-DeepTargetAttrs {
|
|||||||
$sSrc = Read-SourceObject $srt.TypeName $srt.ObjName
|
$sSrc = Read-SourceObject $srt.TypeName $srt.ObjName
|
||||||
$sBorrowedXml = Build-BorrowedObjectXml $srt.TypeName $srt.ObjName $sSrc.Uuid $sSrc.Properties
|
$sBorrowedXml = Build-BorrowedObjectXml $srt.TypeName $srt.ObjName $sSrc.Uuid $sSrc.Properties
|
||||||
$sTargetDir = Join-Path $extDir $childTypeDirMap[$srt.TypeName]
|
$sTargetDir = Join-Path $extDir $childTypeDirMap[$srt.TypeName]
|
||||||
if (-not (Test-Path $sTargetDir)) { New-Item -ItemType Directory -Path $sTargetDir -Force | Out-Null }
|
if (-not (Test-Path $sTargetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $sTargetDir -Force | Out-Null
|
||||||
|
}
|
||||||
$sTargetFile = Join-Path $sTargetDir "$($srt.ObjName).xml"
|
$sTargetFile = Join-Path $sTargetDir "$($srt.ObjName).xml"
|
||||||
[System.IO.File]::WriteAllText($sTargetFile, $sBorrowedXml, $encBomLocal)
|
[System.IO.File]::WriteAllText($sTargetFile, $sBorrowedXml, $encBom)
|
||||||
Add-ToChildObjects $srt.TypeName $srt.ObjName
|
Add-ToChildObjects $srt.TypeName $srt.ObjName
|
||||||
$script:borrowedFiles += $sTargetFile
|
$script:borrowedFiles += $sTargetFile
|
||||||
Info " Auto-borrowed (deep): $($srt.TypeName).$($srt.ObjName)"
|
Info " Auto-borrowed (deep): $($srt.TypeName).$($srt.ObjName)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Info " Main attribute borrowing complete"
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- 12. Helper: build borrowed object XML ---
|
# --- 12. Helper: build borrowed object XML ---
|
||||||
@@ -1661,11 +1572,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)
|
||||||
+72
-197
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# cfe-borrow v1.9 — Borrow objects from configuration into extension (CFE)
|
# cfe-borrow v1.3 — 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
|
||||||
@@ -349,48 +319,12 @@ def expand_self_closing(container, parent_indent):
|
|||||||
container.text = "\r\n" + parent_indent
|
container.text = "\r\n" + parent_indent
|
||||||
|
|
||||||
|
|
||||||
def _detect_xml_style(path):
|
|
||||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
|
||||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
|
||||||
try:
|
|
||||||
raw = open(path, "rb").read()
|
|
||||||
except OSError:
|
|
||||||
return None
|
|
||||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
|
||||||
body = raw[3:] if bom else raw
|
|
||||||
crlf = b"\r\n" in body
|
|
||||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
|
||||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
|
||||||
final_nl = body.endswith(b"\n")
|
|
||||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
|
||||||
|
|
||||||
|
|
||||||
def _finalize_xml_bytes(xml_bytes, style):
|
|
||||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
|
||||||
enc_decl = style["enc"] if style else "utf-8"
|
|
||||||
xml_bytes = xml_bytes.replace(
|
|
||||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
|
||||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
|
||||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
|
||||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
|
||||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
|
||||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
|
||||||
want_final_nl = style["final_nl"] if style else True
|
|
||||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
|
||||||
if want_final_nl:
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
|
||||||
if style and style["crlf"]:
|
|
||||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
|
||||||
return xml_bytes
|
|
||||||
|
|
||||||
|
|
||||||
def save_xml_bom(tree, path):
|
def save_xml_bom(tree, path):
|
||||||
style = _detect_xml_style(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 = _finalize_xml_bytes(xml_bytes, style)
|
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" 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:
|
||||||
if style is None or style["bom"]:
|
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
|
|
||||||
@@ -528,13 +462,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}
|
||||||
|
|
||||||
@@ -606,10 +533,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:
|
||||||
@@ -721,10 +644,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)
|
path = m.group(1)
|
||||||
segments = path.split(".")
|
segments = path.split(".")
|
||||||
seg0 = segments[0]
|
seg0 = segments[0]
|
||||||
@@ -735,30 +655,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 scan <Field>Объект.X</Field> — object attributes referenced by filter/conditional-appearance
|
# Also collect from TitleDataPath
|
||||||
# fields (and dynamic lists), not via a *DataPath binding (e.g. УдалитьЮрФизЛицо). Designer borrows these too.
|
for m in re.finditer(r'<TitleDataPath>[^<]*\b\u041e\u0431\u044a\u0435\u043a\u0442\.(\w+(?:\.\w+)*)</TitleDataPath>', content):
|
||||||
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]
|
||||||
if seg0 in STANDARD_FIELDS:
|
if seg0 in STANDARD_FIELDS:
|
||||||
continue
|
continue
|
||||||
first_level[seg0] = True
|
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})
|
|
||||||
|
|
||||||
# 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)
|
||||||
@@ -1029,40 +941,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:
|
||||||
@@ -1114,58 +1012,38 @@ 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
|
||||||
|
real_deep = [dp for dp in deep_paths if dp["ObjectAttr"] not in ts_names]
|
||||||
|
|
||||||
|
if real_deep:
|
||||||
|
info(f" Processing {len(real_deep)} deep path(s)...")
|
||||||
|
|
||||||
|
# Group by ObjectAttr -> target catalog
|
||||||
deep_by_attr = {}
|
deep_by_attr = {}
|
||||||
for dp in deep_paths:
|
for dp in real_deep:
|
||||||
if dp["ObjectAttr"] in ts_names:
|
if dp["ObjectAttr"] not in deep_by_attr:
|
||||||
continue
|
deep_by_attr[dp["ObjectAttr"]] = []
|
||||||
deep_by_attr.setdefault(dp["ObjectAttr"], [])
|
|
||||||
if dp["SubAttr"] not in 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:
|
|
||||||
continue
|
|
||||||
if not dp.get("SubSubAttr"):
|
|
||||||
continue
|
|
||||||
if dp["SubSubAttr"] in STANDARD_FIELDS:
|
|
||||||
continue
|
|
||||||
k = (dp["ObjectAttr"], dp["SubAttr"])
|
|
||||||
ts_deep_by_col.setdefault(k, [])
|
|
||||||
if dp["SubSubAttr"] not in ts_deep_by_col[k]:
|
|
||||||
ts_deep_by_col[k].append(dp["SubSubAttr"])
|
|
||||||
if ts_deep_by_col:
|
|
||||||
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():
|
|
||||||
ts_info = next((t for t in src_ts if t["Name"] == ts_name), None)
|
|
||||||
if not ts_info:
|
|
||||||
continue
|
|
||||||
col_info = next((c for c in ts_info["Attributes"] if c["Name"] == col_name), None)
|
|
||||||
if not col_info:
|
|
||||||
continue
|
|
||||||
cat_match = re.search(r'cfg:(\w+)Ref\.(\w+)', col_info["TypeXml"])
|
|
||||||
if not cat_match:
|
|
||||||
continue
|
|
||||||
borrow_deep_target_attrs(cat_match.group(1), cat_match.group(2), sub_attr_names)
|
|
||||||
|
|
||||||
info(" Main attribute borrowing complete")
|
# Ensure target is borrowed
|
||||||
|
|
||||||
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):
|
if not test_object_borrowed(target_type_name, target_obj_name):
|
||||||
t_src = read_source_object(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_borrowed_xml = build_borrowed_object_xml(target_type_name, target_obj_name, t_src["Uuid"], t_src["Properties"])
|
||||||
@@ -1177,10 +1055,14 @@ def main():
|
|||||||
borrowed_files.append(t_target_file)
|
borrowed_files.append(t_target_file)
|
||||||
info(f" Auto-borrowed for deep path: {target_type_name}.{target_obj_name}")
|
info(f" Auto-borrowed for deep path: {target_type_name}.{target_obj_name}")
|
||||||
|
|
||||||
|
# Resolve sub-attributes in target catalog
|
||||||
sub_names = {sn: True for sn in sub_attr_names}
|
sub_names = {sn: True for sn in sub_attr_names}
|
||||||
sub_resolved = resolve_source_attributes(target_type_name, target_obj_name, sub_names)
|
sub_resolved = resolve_source_attributes(target_type_name, target_obj_name, sub_names)
|
||||||
|
|
||||||
if sub_resolved["Attributes"]:
|
if sub_resolved["Attributes"]:
|
||||||
merge_attributes_into_object(target_type_name, target_obj_name, sub_resolved["Attributes"])
|
merge_attributes_into_object(target_type_name, target_obj_name, sub_resolved["Attributes"])
|
||||||
|
|
||||||
|
# Collect and borrow ref types from deep attributes
|
||||||
sub_type_xmls = [sa["TypeXml"] for sa in sub_resolved["Attributes"]]
|
sub_type_xmls = [sa["TypeXml"] for sa in sub_resolved["Attributes"]]
|
||||||
sub_ref_types = collect_reference_types(sub_type_xmls)
|
sub_ref_types = collect_reference_types(sub_type_xmls)
|
||||||
for srt in sub_ref_types:
|
for srt in sub_ref_types:
|
||||||
@@ -1201,6 +1083,8 @@ def main():
|
|||||||
borrowed_files.append(s_target_file)
|
borrowed_files.append(s_target_file)
|
||||||
info(f" Auto-borrowed (deep): {srt['TypeName']}.{srt['ObjName']}")
|
info(f" Auto-borrowed (deep): {srt['TypeName']}.{srt['ObjName']}")
|
||||||
|
|
||||||
|
info(" Main attribute borrowing complete")
|
||||||
|
|
||||||
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]
|
||||||
|
|
||||||
@@ -1216,21 +1100,7 @@ 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
|
|
||||||
# (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()
|
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"?>',
|
||||||
@@ -1261,10 +1131,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", format_version)
|
||||||
# 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 = []
|
||||||
@@ -1282,21 +1149,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 = ""
|
||||||
@@ -1307,12 +1178,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)
|
||||||
@@ -1549,14 +1428,10 @@ 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):
|
|
||||||
info(" Preserved existing Module.bsl")
|
|
||||||
else:
|
|
||||||
save_text_bom(module_bsl_file, "")
|
save_text_bom(module_bsl_file, "")
|
||||||
info(f" Created: {module_bsl_file}")
|
info(f" Created: {module_bsl_file}")
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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 — обзор расширения
|
||||||
@@ -44,7 +44,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/cfe-init/scripts/cfe-init.py" -Name "МоёРасширение"
|
powershell.exe -NoProfile -File .claude/skills/cfe-init/scripts/cfe-init.ps1 -Name "МоёРасширение"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
+4
-13
@@ -1,4 +1,4 @@
|
|||||||
# cfe-init v1.2 — Create 1C configuration extension scaffold (CFE)
|
# cfe-init v1.1 — 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) {
|
||||||
@@ -79,11 +75,6 @@ if ($ConfigPath) {
|
|||||||
$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()
|
||||||
@@ -147,7 +138,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>
|
||||||
@@ -212,7 +203,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 +220,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>
|
||||||
+4
-12
@@ -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.1 — 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:
|
||||||
@@ -92,10 +88,6 @@ def main():
|
|||||||
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:
|
||||||
@@ -163,7 +155,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>
|
||||||
@@ -198,7 +190,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 +205,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>
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
---
|
||||||
|
name: cfe-patch-method
|
||||||
|
description: Генерация перехватчика метода в расширении 1С (CFE). Используй когда нужно перехватить метод заимствованного объекта — вставить код до, после или вместо оригинального
|
||||||
|
argument-hint: -ExtensionPath <path> -ModulePath "Catalog.X.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||||
|
allowed-tools:
|
||||||
|
- Bash
|
||||||
|
- Read
|
||||||
|
- Glob
|
||||||
|
---
|
||||||
|
|
||||||
|
# /cfe-patch-method — Генерация перехватчика метода
|
||||||
|
|
||||||
|
Генерирует `.bsl` файл с декоратором перехвата для заимствованного объекта расширения. Создаёт файл или дописывает в существующий.
|
||||||
|
|
||||||
|
## Предусловие
|
||||||
|
|
||||||
|
Объект должен быть заимствован в расширение (`/cfe-borrow`). Скрипт читает `NamePrefix` из `Configuration.xml` расширения для формирования имени процедуры.
|
||||||
|
|
||||||
|
## Параметры
|
||||||
|
|
||||||
|
| Параметр | Описание | По умолчанию |
|
||||||
|
|----------|----------|--------------|
|
||||||
|
| `ExtensionPath` | Путь к расширению (обязат.) | — |
|
||||||
|
| `ModulePath` | Путь к модулю (обязат.) | — |
|
||||||
|
| `MethodName` | Имя перехватываемого метода (обязат.) | — |
|
||||||
|
| `InterceptorType` | `Before` / `After` / `ModificationAndControl` (обязат.) | — |
|
||||||
|
| `Context` | Директива контекста | `НаСервере` |
|
||||||
|
| `IsFunction` | Метод — функция (добавит `Возврат`) | false |
|
||||||
|
|
||||||
|
## Формат ModulePath
|
||||||
|
|
||||||
|
| ModulePath | Файл |
|
||||||
|
|------------|------|
|
||||||
|
| `Catalog.X.ObjectModule` | `Catalogs/X/Ext/ObjectModule.bsl` |
|
||||||
|
| `Catalog.X.ManagerModule` | `Catalogs/X/Ext/ManagerModule.bsl` |
|
||||||
|
| `Catalog.X.Form.Y` | `Catalogs/X/Forms/Y/Ext/Form/Module.bsl` |
|
||||||
|
| `CommonModule.X` | `CommonModules/X/Ext/Module.bsl` |
|
||||||
|
| `Document.X.ObjectModule` | `Documents/X/Ext/ObjectModule.bsl` |
|
||||||
|
| `Document.X.Form.Y` | `Documents/X/Forms/Y/Ext/Form/Module.bsl` |
|
||||||
|
|
||||||
|
Аналогично для Report, DataProcessor, InformationRegister и других типов.
|
||||||
|
|
||||||
|
## Типы перехвата
|
||||||
|
|
||||||
|
| InterceptorType | Декоратор | Назначение |
|
||||||
|
|-----------------|-----------|------------|
|
||||||
|
| `Before` | `&Перед` | Код до вызова оригинального метода |
|
||||||
|
| `After` | `&После` | Код после вызова оригинального метода |
|
||||||
|
| `ModificationAndControl` | `&ИзменениеИКонтроль` | Копия тела метода с маркерами `#Вставка`/`#Удаление` |
|
||||||
|
|
||||||
|
## Команда
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
powershell.exe -NoProfile -File .claude/skills/cfe-patch-method/scripts/cfe-patch-method.ps1 -ExtensionPath src -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||||
|
```
|
||||||
|
|
||||||
|
## Примеры
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# Перехват &Перед на сервере
|
||||||
|
... -ExtensionPath src -ModulePath "Catalog.Контрагенты.ObjectModule" -MethodName "ПриЗаписи" -InterceptorType Before
|
||||||
|
|
||||||
|
# Перехват &После на клиенте
|
||||||
|
... -ExtensionPath src -ModulePath "Document.Заказ.Form.ФормаДокумента" -MethodName "ПослеЗаписиНаСервере" -InterceptorType After -Context "НаКлиенте"
|
||||||
|
|
||||||
|
# ИзменениеИКонтроль для функции
|
||||||
|
... -ExtensionPath src -ModulePath "CommonModule.ОбщийМодуль" -MethodName "ПолучитьДанные" -InterceptorType ModificationAndControl -IsFunction
|
||||||
|
```
|
||||||
|
|
||||||
|
## Генерируемый код (Before)
|
||||||
|
|
||||||
|
```bsl
|
||||||
|
&НаСервере
|
||||||
|
&Перед("ПриЗаписи")
|
||||||
|
Процедура Расш1_ПриЗаписи()
|
||||||
|
// TODO: код перед вызовом оригинального метода
|
||||||
|
КонецПроцедуры
|
||||||
|
```
|
||||||
@@ -0,0 +1,209 @@
|
|||||||
|
# cfe-patch-method v1.1 — Generate method interceptor for 1C extension (CFE)
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$ExtensionPath,
|
||||||
|
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$ModulePath,
|
||||||
|
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[string]$MethodName,
|
||||||
|
|
||||||
|
[Parameter(Mandatory)]
|
||||||
|
[ValidateSet("Before","After","ModificationAndControl")]
|
||||||
|
[string]$InterceptorType,
|
||||||
|
|
||||||
|
[string]$Context = "НаСервере",
|
||||||
|
|
||||||
|
[switch]$IsFunction
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
|
||||||
|
|
||||||
|
# --- Resolve extension path ---
|
||||||
|
if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
|
||||||
|
$ExtensionPath = Join-Path (Get-Location).Path $ExtensionPath
|
||||||
|
}
|
||||||
|
if (Test-Path $ExtensionPath -PathType Leaf) {
|
||||||
|
$ExtensionPath = Split-Path $ExtensionPath -Parent
|
||||||
|
}
|
||||||
|
$cfgFile = Join-Path $ExtensionPath "Configuration.xml"
|
||||||
|
if (-not (Test-Path $cfgFile)) {
|
||||||
|
Write-Error "Configuration.xml not found in: $ExtensionPath"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Read NamePrefix from Configuration.xml ---
|
||||||
|
$cfgDoc = New-Object System.Xml.XmlDocument
|
||||||
|
$cfgDoc.PreserveWhitespace = $false
|
||||||
|
$cfgDoc.Load($cfgFile)
|
||||||
|
|
||||||
|
$cfgNs = New-Object System.Xml.XmlNamespaceManager($cfgDoc.NameTable)
|
||||||
|
$cfgNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
|
||||||
|
|
||||||
|
$propsNode = $cfgDoc.SelectSingleNode("//md:Configuration/md:Properties", $cfgNs)
|
||||||
|
$prefixNode = if ($propsNode) { $propsNode.SelectSingleNode("md:NamePrefix", $cfgNs) } else { $null }
|
||||||
|
$namePrefix = if ($prefixNode -and $prefixNode.InnerText) { $prefixNode.InnerText } else { "Расш_" }
|
||||||
|
|
||||||
|
# --- Map ModulePath to file path ---
|
||||||
|
# ModulePath formats:
|
||||||
|
# Catalog.X.ObjectModule -> Catalogs/X/Ext/ObjectModule.bsl
|
||||||
|
# Catalog.X.ManagerModule -> Catalogs/X/Ext/ManagerModule.bsl
|
||||||
|
# Catalog.X.Form.Y -> Catalogs/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
# CommonModule.X -> CommonModules/X/Ext/Module.bsl
|
||||||
|
# Document.X.ObjectModule -> Documents/X/Ext/ObjectModule.bsl
|
||||||
|
# Document.X.ManagerModule -> Documents/X/Ext/ManagerModule.bsl
|
||||||
|
# Document.X.Form.Y -> Documents/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
|
||||||
|
$typeDirMap = @{
|
||||||
|
"Catalog"="Catalogs"; "Document"="Documents"; "Enum"="Enums"
|
||||||
|
"CommonModule"="CommonModules"; "Report"="Reports"; "DataProcessor"="DataProcessors"
|
||||||
|
"ExchangePlan"="ExchangePlans"; "ChartOfAccounts"="ChartsOfAccounts"
|
||||||
|
"ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"
|
||||||
|
"ChartOfCalculationTypes"="ChartsOfCalculationTypes"
|
||||||
|
"BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
|
||||||
|
"InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
|
||||||
|
"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(".")
|
||||||
|
if ($parts.Count -lt 2) {
|
||||||
|
Write-Error "Invalid ModulePath format: $ModulePath. Expected: Type.Name.Module or CommonModule.Name"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$objType = $parts[0]
|
||||||
|
$objName = $parts[1]
|
||||||
|
|
||||||
|
if (-not $typeDirMap.ContainsKey($objType)) {
|
||||||
|
Write-Error "Unknown object type: $objType"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$dirName = $typeDirMap[$objType]
|
||||||
|
|
||||||
|
$bslFile = $null
|
||||||
|
if ($objType -eq "CommonModule") {
|
||||||
|
# CommonModule.X -> CommonModules/X/Ext/Module.bsl
|
||||||
|
$bslFile = Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Ext") "Module.bsl"
|
||||||
|
} elseif ($parts.Count -ge 4 -and $parts[2] -eq "Form") {
|
||||||
|
# Type.X.Form.Y -> Types/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
$formName = $parts[3]
|
||||||
|
$bslFile = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Forms") $formName) "Ext") "Form") "Module.bsl"
|
||||||
|
} elseif ($parts.Count -ge 3) {
|
||||||
|
# Type.X.ObjectModule -> Types/X/Ext/ObjectModule.bsl
|
||||||
|
$moduleName = $parts[2]
|
||||||
|
$moduleFileName = switch ($moduleName) {
|
||||||
|
"ObjectModule" { "ObjectModule.bsl" }
|
||||||
|
"ManagerModule" { "ManagerModule.bsl" }
|
||||||
|
"RecordSetModule" { "RecordSetModule.bsl" }
|
||||||
|
"CommandModule" { "CommandModule.bsl" }
|
||||||
|
default { "$moduleName.bsl" }
|
||||||
|
}
|
||||||
|
$bslFile = Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) (Join-Path "Ext" $moduleFileName)
|
||||||
|
} else {
|
||||||
|
Write-Error "Invalid ModulePath format: $ModulePath. Expected: Type.Name.Module, Type.Name.Form.FormName, or CommonModule.Name"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Map InterceptorType to decorator ---
|
||||||
|
$decorator = switch ($InterceptorType) {
|
||||||
|
"Before" { "&Перед" }
|
||||||
|
"After" { "&После" }
|
||||||
|
"ModificationAndControl" { "&ИзменениеИКонтроль" }
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Map Context to annotation ---
|
||||||
|
$contextAnnotation = switch ($Context) {
|
||||||
|
"НаСервере" { "&НаСервере" }
|
||||||
|
"НаКлиенте" { "&НаКлиенте" }
|
||||||
|
"НаСервереБезКонтекста" { "&НаСервереБезКонтекста" }
|
||||||
|
default { "&$Context" }
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Procedure name ---
|
||||||
|
$procName = "${namePrefix}${MethodName}"
|
||||||
|
|
||||||
|
# --- Generate BSL code ---
|
||||||
|
$keyword = if ($IsFunction) { "Функция" } else { "Процедура" }
|
||||||
|
$endKeyword = if ($IsFunction) { "КонецФункции" } else { "КонецПроцедуры" }
|
||||||
|
|
||||||
|
$bodyLines = @()
|
||||||
|
switch ($InterceptorType) {
|
||||||
|
"Before" {
|
||||||
|
$bodyLines += "`t// TODO: код перед вызовом оригинального метода"
|
||||||
|
}
|
||||||
|
"After" {
|
||||||
|
$bodyLines += "`t// TODO: код после вызова оригинального метода"
|
||||||
|
}
|
||||||
|
"ModificationAndControl" {
|
||||||
|
$bodyLines += "`t// Скопируйте тело оригинального метода и внесите изменения,"
|
||||||
|
$bodyLines += "`t// используя маркеры #Удаление / #КонецУдаления и #Вставка / #КонецВставки"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($IsFunction) {
|
||||||
|
$bodyLines += "`t"
|
||||||
|
$bodyLines += "`tВозврат Неопределено; // TODO: заменить на реальное возвращаемое значение"
|
||||||
|
}
|
||||||
|
|
||||||
|
$bslCode = @()
|
||||||
|
$bslCode += "$contextAnnotation"
|
||||||
|
$bslCode += "${decorator}(`"$MethodName`")"
|
||||||
|
$bslCode += "$keyword ${procName}()"
|
||||||
|
$bslCode += $bodyLines
|
||||||
|
$bslCode += "$endKeyword"
|
||||||
|
|
||||||
|
$bslText = ($bslCode -join "`r`n") + "`r`n"
|
||||||
|
|
||||||
|
# --- Check form borrowing for .Form. paths ---
|
||||||
|
if ($parts.Count -ge 4 -and $parts[2] -eq "Form") {
|
||||||
|
$formName = $parts[3]
|
||||||
|
$dirName = $typeDirMap[$objType]
|
||||||
|
$formMetaFile = Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Forms") "${formName}.xml"
|
||||||
|
$formXmlFile = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Forms") $formName) "Ext/Form.xml"
|
||||||
|
|
||||||
|
if (-not (Test-Path $formMetaFile) -or -not (Test-Path $formXmlFile)) {
|
||||||
|
Write-Host "[WARN] Form '$formName' metadata or Form.xml not found in extension."
|
||||||
|
Write-Host " Run /cfe-borrow first:"
|
||||||
|
Write-Host " /cfe-borrow -ExtensionPath $ExtensionPath -ConfigPath <ConfigPath> -Object `"$objType.$objName.Form.$formName`""
|
||||||
|
Write-Host ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Check if file exists and append ---
|
||||||
|
$bslDir = Split-Path $bslFile -Parent
|
||||||
|
if (-not (Test-Path $bslDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $bslDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$enc = New-Object System.Text.UTF8Encoding($true)
|
||||||
|
|
||||||
|
if (Test-Path $bslFile) {
|
||||||
|
# Append to existing file
|
||||||
|
$existing = [System.IO.File]::ReadAllText($bslFile, $enc)
|
||||||
|
$separator = "`r`n"
|
||||||
|
if ($existing -and -not $existing.EndsWith("`n")) {
|
||||||
|
$separator = "`r`n`r`n"
|
||||||
|
}
|
||||||
|
$newContent = $existing + $separator + $bslText
|
||||||
|
[System.IO.File]::WriteAllText($bslFile, $newContent, $enc)
|
||||||
|
Write-Host "[OK] Добавлен перехватчик в существующий файл"
|
||||||
|
} else {
|
||||||
|
[System.IO.File]::WriteAllText($bslFile, $bslText, $enc)
|
||||||
|
Write-Host "[OK] Создан файл модуля"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host " Файл: $bslFile"
|
||||||
|
Write-Host " Декоратор: $decorator(`"$MethodName`")"
|
||||||
|
Write-Host " Процедура: ${procName}()"
|
||||||
|
Write-Host " Контекст: $contextAnnotation"
|
||||||
@@ -0,0 +1,247 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# cfe-patch-method v1.1 — Generate method interceptor for 1C extension (CFE)
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8")
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Generate method interceptor for 1C extension (CFE)",
|
||||||
|
allow_abbrev=False,
|
||||||
|
)
|
||||||
|
parser.add_argument("-ExtensionPath", required=True)
|
||||||
|
parser.add_argument("-ModulePath", required=True)
|
||||||
|
parser.add_argument("-MethodName", required=True)
|
||||||
|
parser.add_argument(
|
||||||
|
"-InterceptorType",
|
||||||
|
required=True,
|
||||||
|
choices=["Before", "After", "ModificationAndControl"],
|
||||||
|
)
|
||||||
|
parser.add_argument("-Context", default="\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435") # НаСервере
|
||||||
|
parser.add_argument("-IsFunction", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
extension_path = args.ExtensionPath
|
||||||
|
module_path = args.ModulePath
|
||||||
|
method_name = args.MethodName
|
||||||
|
interceptor_type = args.InterceptorType
|
||||||
|
context = args.Context
|
||||||
|
is_function = args.IsFunction
|
||||||
|
|
||||||
|
# --- Resolve extension path ---
|
||||||
|
if not os.path.isabs(extension_path):
|
||||||
|
extension_path = os.path.join(os.getcwd(), extension_path)
|
||||||
|
if os.path.isfile(extension_path):
|
||||||
|
extension_path = os.path.dirname(extension_path)
|
||||||
|
|
||||||
|
cfg_file = os.path.join(extension_path, "Configuration.xml")
|
||||||
|
if not os.path.isfile(cfg_file):
|
||||||
|
print(f"Configuration.xml not found in: {extension_path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Read NamePrefix from Configuration.xml ---
|
||||||
|
tree = ET.parse(cfg_file)
|
||||||
|
root = tree.getroot()
|
||||||
|
|
||||||
|
ns = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
||||||
|
props_node = root.find(".//md:Configuration/md:Properties", ns)
|
||||||
|
name_prefix = "\u0420\u0430\u0441\u0448_" # Расш_
|
||||||
|
if props_node is not None:
|
||||||
|
prefix_node = props_node.find("md:NamePrefix", ns)
|
||||||
|
if prefix_node is not None and prefix_node.text:
|
||||||
|
name_prefix = prefix_node.text
|
||||||
|
|
||||||
|
# --- Map ModulePath to file path ---
|
||||||
|
# ModulePath formats:
|
||||||
|
# Catalog.X.ObjectModule -> Catalogs/X/Ext/ObjectModule.bsl
|
||||||
|
# Catalog.X.ManagerModule -> Catalogs/X/Ext/ManagerModule.bsl
|
||||||
|
# Catalog.X.Form.Y -> Catalogs/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
# CommonModule.X -> CommonModules/X/Ext/Module.bsl
|
||||||
|
# Document.X.ObjectModule -> Documents/X/Ext/ObjectModule.bsl
|
||||||
|
# Document.X.ManagerModule -> Documents/X/Ext/ManagerModule.bsl
|
||||||
|
# Document.X.Form.Y -> Documents/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
|
||||||
|
type_dir_map = {
|
||||||
|
"Catalog": "Catalogs",
|
||||||
|
"Document": "Documents",
|
||||||
|
"Enum": "Enums",
|
||||||
|
"CommonModule": "CommonModules",
|
||||||
|
"Report": "Reports",
|
||||||
|
"DataProcessor": "DataProcessors",
|
||||||
|
"ExchangePlan": "ExchangePlans",
|
||||||
|
"ChartOfAccounts": "ChartsOfAccounts",
|
||||||
|
"ChartOfCharacteristicTypes": "ChartsOfCharacteristicTypes",
|
||||||
|
"ChartOfCalculationTypes": "ChartsOfCalculationTypes",
|
||||||
|
"BusinessProcess": "BusinessProcesses",
|
||||||
|
"Task": "Tasks",
|
||||||
|
"InformationRegister": "InformationRegisters",
|
||||||
|
"AccumulationRegister": "AccumulationRegisters",
|
||||||
|
"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 = module_path.split(".")
|
||||||
|
if len(parts) < 2:
|
||||||
|
print(
|
||||||
|
f"Invalid ModulePath format: {module_path}. "
|
||||||
|
"Expected: Type.Name.Module or CommonModule.Name",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
obj_type = parts[0]
|
||||||
|
obj_name = parts[1]
|
||||||
|
|
||||||
|
if obj_type not in type_dir_map:
|
||||||
|
print(f"Unknown object type: {obj_type}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
dir_name = type_dir_map[obj_type]
|
||||||
|
|
||||||
|
bsl_file = None
|
||||||
|
if obj_type == "CommonModule":
|
||||||
|
# CommonModule.X -> CommonModules/X/Ext/Module.bsl
|
||||||
|
bsl_file = os.path.join(extension_path, dir_name, obj_name, "Ext", "Module.bsl")
|
||||||
|
elif len(parts) >= 4 and parts[2] == "Form":
|
||||||
|
# Type.X.Form.Y -> Types/X/Forms/Y/Ext/Form/Module.bsl
|
||||||
|
form_name = parts[3]
|
||||||
|
bsl_file = os.path.join(
|
||||||
|
extension_path, dir_name, obj_name, "Forms", form_name, "Ext", "Form", "Module.bsl"
|
||||||
|
)
|
||||||
|
elif len(parts) >= 3:
|
||||||
|
# Type.X.ObjectModule -> Types/X/Ext/ObjectModule.bsl
|
||||||
|
module_name = parts[2]
|
||||||
|
module_file_map = {
|
||||||
|
"ObjectModule": "ObjectModule.bsl",
|
||||||
|
"ManagerModule": "ManagerModule.bsl",
|
||||||
|
"RecordSetModule": "RecordSetModule.bsl",
|
||||||
|
"CommandModule": "CommandModule.bsl",
|
||||||
|
}
|
||||||
|
module_file_name = module_file_map.get(module_name, f"{module_name}.bsl")
|
||||||
|
bsl_file = os.path.join(extension_path, dir_name, obj_name, "Ext", module_file_name)
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
f"Invalid ModulePath format: {module_path}. "
|
||||||
|
"Expected: Type.Name.Module, Type.Name.Form.FormName, or CommonModule.Name",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Map InterceptorType to decorator ---
|
||||||
|
decorator_map = {
|
||||||
|
"Before": "&\u041f\u0435\u0440\u0435\u0434", # &Перед
|
||||||
|
"After": "&\u041f\u043e\u0441\u043b\u0435", # &После
|
||||||
|
"ModificationAndControl": "&\u0418\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u0435\u0418\u041a\u043e\u043d\u0442\u0440\u043e\u043b\u044c", # &ИзменениеИКонтроль
|
||||||
|
}
|
||||||
|
decorator = decorator_map[interceptor_type]
|
||||||
|
|
||||||
|
# --- Map Context to annotation ---
|
||||||
|
context_map = {
|
||||||
|
"\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435": "&\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435", # НаСервере -> &НаСервере
|
||||||
|
"\u041d\u0430\u041a\u043b\u0438\u0435\u043d\u0442\u0435": "&\u041d\u0430\u041a\u043b\u0438\u0435\u043d\u0442\u0435", # НаКлиенте -> &НаКлиенте
|
||||||
|
"\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435\u0411\u0435\u0437\u041a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0430": "&\u041d\u0430\u0421\u0435\u0440\u0432\u0435\u0440\u0435\u0411\u0435\u0437\u041a\u043e\u043d\u0442\u0435\u043a\u0441\u0442\u0430", # НаСервереБезКонтекста -> &НаСервереБезКонтекста
|
||||||
|
}
|
||||||
|
context_annotation = context_map.get(context, f"&{context}")
|
||||||
|
|
||||||
|
# --- Procedure name ---
|
||||||
|
proc_name = f"{name_prefix}{method_name}"
|
||||||
|
|
||||||
|
# --- Generate BSL code ---
|
||||||
|
keyword = "\u0424\u0443\u043d\u043a\u0446\u0438\u044f" if is_function else "\u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u0430" # Функция / Процедура
|
||||||
|
end_keyword = "\u041a\u043e\u043d\u0435\u0446\u0424\u0443\u043d\u043a\u0446\u0438\u0438" if is_function else "\u041a\u043e\u043d\u0435\u0446\u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u044b" # КонецФункции / КонецПроцедуры
|
||||||
|
|
||||||
|
body_lines = []
|
||||||
|
if interceptor_type == "Before":
|
||||||
|
body_lines.append("\t// TODO: \u043a\u043e\u0434 \u043f\u0435\u0440\u0435\u0434 \u0432\u044b\u0437\u043e\u0432\u043e\u043c \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043c\u0435\u0442\u043e\u0434\u0430") # код перед вызовом оригинального метода
|
||||||
|
elif interceptor_type == "After":
|
||||||
|
body_lines.append("\t// TODO: \u043a\u043e\u0434 \u043f\u043e\u0441\u043b\u0435 \u0432\u044b\u0437\u043e\u0432\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043c\u0435\u0442\u043e\u0434\u0430") # код после вызова оригинального метода
|
||||||
|
elif interceptor_type == "ModificationAndControl":
|
||||||
|
body_lines.append("\t// \u0421\u043a\u043e\u043f\u0438\u0440\u0443\u0439\u0442\u0435 \u0442\u0435\u043b\u043e \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0433\u043e \u043c\u0435\u0442\u043e\u0434\u0430 \u0438 \u0432\u043d\u0435\u0441\u0438\u0442\u0435 \u0438\u0437\u043c\u0435\u043d\u0435\u043d\u0438\u044f,") # Скопируйте тело оригинального метода и внесите изменения,
|
||||||
|
body_lines.append("\t// \u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044f \u043c\u0430\u0440\u043a\u0435\u0440\u044b #\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 / #\u041a\u043e\u043d\u0435\u0446\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u044f \u0438 #\u0412\u0441\u0442\u0430\u0432\u043a\u0430 / #\u041a\u043e\u043d\u0435\u0446\u0412\u0441\u0442\u0430\u0432\u043a\u0438") # используя маркеры #Удаление / #КонецУдаления и #Вставка / #КонецВставки
|
||||||
|
|
||||||
|
if is_function:
|
||||||
|
body_lines.append("\t")
|
||||||
|
body_lines.append("\t\u0412\u043e\u0437\u0432\u0440\u0430\u0442 \u041d\u0435\u043e\u043f\u0440\u0435\u0434\u0435\u043b\u0435\u043d\u043e; // TODO: \u0437\u0430\u043c\u0435\u043d\u0438\u0442\u044c \u043d\u0430 \u0440\u0435\u0430\u043b\u044c\u043d\u043e\u0435 \u0432\u043e\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u043c\u043e\u0435 \u0437\u043d\u0430\u0447\u0435\u043d\u0438\u0435") # Возврат Неопределено; // TODO: заменить на реальное возвращаемое значение
|
||||||
|
|
||||||
|
bsl_code = [
|
||||||
|
context_annotation,
|
||||||
|
f'{decorator}("{method_name}")',
|
||||||
|
f"{keyword} {proc_name}()",
|
||||||
|
]
|
||||||
|
bsl_code.extend(body_lines)
|
||||||
|
bsl_code.append(end_keyword)
|
||||||
|
|
||||||
|
bsl_text = "\r\n".join(bsl_code) + "\r\n"
|
||||||
|
|
||||||
|
# --- Check form borrowing for .Form. paths ---
|
||||||
|
if len(parts) >= 4 and parts[2] == "Form":
|
||||||
|
form_name = parts[3]
|
||||||
|
form_meta_file = os.path.join(
|
||||||
|
extension_path, dir_name, obj_name, "Forms", f"{form_name}.xml"
|
||||||
|
)
|
||||||
|
form_xml_file = os.path.join(
|
||||||
|
extension_path, dir_name, obj_name, "Forms", form_name, "Ext", "Form.xml"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not os.path.isfile(form_meta_file) or not os.path.isfile(form_xml_file):
|
||||||
|
print(f"[WARN] Form '{form_name}' metadata or Form.xml not found in extension.")
|
||||||
|
print(" Run /cfe-borrow first:")
|
||||||
|
print(
|
||||||
|
f" /cfe-borrow -ExtensionPath {extension_path} "
|
||||||
|
f'-ConfigPath <ConfigPath> -Object "{obj_type}.{obj_name}.Form.{form_name}"'
|
||||||
|
)
|
||||||
|
print()
|
||||||
|
|
||||||
|
# --- Check if file exists and append ---
|
||||||
|
bsl_dir = os.path.dirname(bsl_file)
|
||||||
|
if not os.path.isdir(bsl_dir):
|
||||||
|
os.makedirs(bsl_dir, exist_ok=True)
|
||||||
|
|
||||||
|
if os.path.isfile(bsl_file):
|
||||||
|
# Append to existing file
|
||||||
|
with open(bsl_file, "r", encoding="utf-8-sig", newline="") as f:
|
||||||
|
existing = f.read()
|
||||||
|
|
||||||
|
separator = "\r\n"
|
||||||
|
if existing and not existing.endswith("\n"):
|
||||||
|
separator = "\r\n\r\n"
|
||||||
|
new_content = existing + separator + bsl_text
|
||||||
|
|
||||||
|
with open(bsl_file, "w", encoding="utf-8-sig", newline="") as f:
|
||||||
|
f.write(new_content)
|
||||||
|
print("[OK] \u0414\u043e\u0431\u0430\u0432\u043b\u0435\u043d \u043f\u0435\u0440\u0435\u0445\u0432\u0430\u0442\u0447\u0438\u043a \u0432 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u044e\u0449\u0438\u0439 \u0444\u0430\u0439\u043b") # Добавлен перехватчик в существующий файл
|
||||||
|
else:
|
||||||
|
with open(bsl_file, "w", encoding="utf-8-sig", newline="") as f:
|
||||||
|
f.write(bsl_text)
|
||||||
|
print("[OK] \u0421\u043e\u0437\u0434\u0430\u043d \u0444\u0430\u0439\u043b \u043c\u043e\u0434\u0443\u043b\u044f") # Создан файл модуля
|
||||||
|
|
||||||
|
print(f" \u0424\u0430\u0439\u043b: {bsl_file}") # Файл:
|
||||||
|
print(f' \u0414\u0435\u043a\u043e\u0440\u0430\u0442\u043e\u0440: {decorator}("{method_name}")') # Декоратор:
|
||||||
|
print(f" \u041f\u0440\u043e\u0446\u0435\u0434\u0443\u0440\u0430: {proc_name}()") # Процедура:
|
||||||
|
print(f" \u041a\u043e\u043d\u0442\u0435\u043a\u0441\u0442: {context_annotation}") # Контекст:
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -24,6 +24,6 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/cfe-validate/scripts/cfe-validate.py" -ExtensionPath "src"
|
powershell.exe -NoProfile -File .claude/skills/cfe-validate/scripts/cfe-validate.ps1 -ExtensionPath "src"
|
||||||
python ".codeassistant/skills/cfe-validate/scripts/cfe-validate.py" -ExtensionPath "src/Configuration.xml"
|
powershell.exe -NoProfile -File .claude/skills/cfe-validate/scripts/cfe-validate.ps1 -ExtensionPath "src/Configuration.xml"
|
||||||
```
|
```
|
||||||
-11
@@ -930,17 +930,6 @@ if ($script:borrowedFormsWithTree.Count -eq 0) {
|
|||||||
Report-OK "13. TypeLink: clean"
|
Report-OK "13. TypeLink: clean"
|
||||||
}
|
}
|
||||||
|
|
||||||
# --- Breadcrumb: controlled methods (&ИзменениеИКонтроль) drift is not checked here ---
|
|
||||||
$extRootDir = Split-Path $resolvedPath -Parent
|
|
||||||
$ctrlCount = 0
|
|
||||||
foreach ($bslFile in (Get-ChildItem -Path $extRootDir -Recurse -Filter *.bsl -File -ErrorAction SilentlyContinue)) {
|
|
||||||
$txt = [System.IO.File]::ReadAllText($bslFile.FullName, [System.Text.Encoding]::UTF8)
|
|
||||||
$ctrlCount += ([regex]::Matches($txt, '(?m)^\s*&ИзменениеИКонтроль\(')).Count
|
|
||||||
}
|
|
||||||
if ($ctrlCount -gt 0) {
|
|
||||||
Out-Line "[INFO] Контролируемых методов (&ИзменениеИКонтроль): $ctrlCount — их актуальность здесь не проверяется. Сверьте: /cfe-patch-method -Check -ExtensionPath <ext> -ConfigPath <cf>"
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Final output ---
|
# --- Final output ---
|
||||||
& $finalize
|
& $finalize
|
||||||
|
|
||||||
-15
@@ -885,21 +885,6 @@ def main():
|
|||||||
elif check13_ok:
|
elif check13_ok:
|
||||||
r.ok('13. TypeLink: clean')
|
r.ok('13. TypeLink: clean')
|
||||||
|
|
||||||
# --- Breadcrumb: controlled methods (&ИзменениеИКонтроль) drift is not checked here ---
|
|
||||||
ctrl_count = 0
|
|
||||||
for dp, _dn, files in os.walk(config_dir):
|
|
||||||
for fn in files:
|
|
||||||
if fn.endswith('.bsl'):
|
|
||||||
try:
|
|
||||||
with open(os.path.join(dp, fn), 'r', encoding='utf-8-sig') as f:
|
|
||||||
for ln in f:
|
|
||||||
if re.match(r'^\s*&ИзменениеИКонтроль\(', ln):
|
|
||||||
ctrl_count += 1
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
if ctrl_count > 0:
|
|
||||||
r.out('[INFO] Контролируемых методов (&ИзменениеИКонтроль): %d — их актуальность здесь не проверяется. Сверьте: /cfe-patch-method -Check -ExtensionPath <ext> -ConfigPath <cf>' % ctrl_count)
|
|
||||||
|
|
||||||
# --- 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)
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/skills/db-dump-cf/scripts/db-dump-cf.py" <парамет
|
|||||||
|
|
||||||
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
> `*` — нужен либо `-InfoBasePath`, либо пара `-InfoBaseServer` + `-InfoBaseRef`
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
|
## После выполнения
|
||||||
|
|
||||||
|
Прочитай лог-файл и покажи результат. Если есть ошибки — покажи содержимое лога.
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Выгрузка конфигурации (файловая база)
|
# Выгрузка конфигурации (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/skills/db-load-git/scripts/db-load-git.py" <параме
|
|||||||
|
|
||||||
## После выполнения
|
## После выполнения
|
||||||
|
|
||||||
Если `-UpdateDB` не был указан — **предложить `/db-update`** для применения изменений к БД
|
1. Показать список загруженных файлов и результат из лога
|
||||||
|
2. Если `-UpdateDB` не был указан — **предложить `/db-update`** для применения изменений к БД
|
||||||
|
|
||||||
## Примеры
|
## Примеры
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Все незафиксированные изменения
|
# Все незафиксированные изменения
|
||||||
python ".codeassistant/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 ".codeassistant/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:
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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,279 @@
|
|||||||
|
# db-load-xml v1.3 — 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,
|
||||||
|
|
||||||
|
[Parameter(Mandatory=$false)]
|
||||||
|
[switch]$StrictLog
|
||||||
|
)
|
||||||
|
|
||||||
|
$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
|
||||||
|
|
||||||
|
# --- Read log ---
|
||||||
|
$logContent = $null
|
||||||
|
if (Test-Path $outFile) {
|
||||||
|
$logContent = Get-Content $outFile -Raw -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Scan log for silent rejections ---
|
||||||
|
# Platform often writes load-time rejections into /Out but exits with code 0.
|
||||||
|
# These patterns flag cases where metadata was dropped or rejected silently.
|
||||||
|
$fatalLogPatterns = @(
|
||||||
|
'Неверное свойство объекта метаданных',
|
||||||
|
'не входит в состав объекта метаданных',
|
||||||
|
'Неизвестное имя типа',
|
||||||
|
'Неизвестный объект метаданных',
|
||||||
|
'Ни один из документов не является регистратором для регистра',
|
||||||
|
'Неверное значение перечисления',
|
||||||
|
'не может быть приведен к типу'
|
||||||
|
)
|
||||||
|
$silentFailures = @()
|
||||||
|
if ($logContent) {
|
||||||
|
foreach ($line in ($logContent -split "`r?`n")) {
|
||||||
|
foreach ($pat in $fatalLogPatterns) {
|
||||||
|
if ($line -match [regex]::Escape($pat)) {
|
||||||
|
$silentFailures += $line.Trim()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
# Default: mirror platform's verdict via exit code. Log content (including any
|
||||||
|
# rejection warnings) is always printed to stdout for visibility. With -StrictLog,
|
||||||
|
# elevate exit code to 1 when rejection patterns are found even if platform said 0.
|
||||||
|
if ($exitCode -eq 0) {
|
||||||
|
Write-Host "Load completed successfully" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host "Error loading configuration (code: $exitCode)" -ForegroundColor Red
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($logContent) {
|
||||||
|
Write-Host "--- Log ---"
|
||||||
|
Write-Host $logContent
|
||||||
|
Write-Host "--- End ---"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($silentFailures.Count -gt 0) {
|
||||||
|
$msg = "[warning] log contains $($silentFailures.Count) rejection(s) — platform loaded config but dropped properties/refs"
|
||||||
|
if (-not $StrictLog) { $msg += " (pass -StrictLog to treat as error)" }
|
||||||
|
Write-Host $msg -ForegroundColor Yellow
|
||||||
|
foreach ($f in $silentFailures) { Write-Host " $f" -ForegroundColor Yellow }
|
||||||
|
if ($StrictLog -and $exitCode -eq 0) { $exitCode = 1 }
|
||||||
|
}
|
||||||
|
|
||||||
|
exit $exitCode
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
if (Test-Path $tempDir) {
|
||||||
|
Remove-Item -Path $tempDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# db-load-xml v1.3 — 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")
|
||||||
|
parser.add_argument(
|
||||||
|
"-StrictLog",
|
||||||
|
action="store_true",
|
||||||
|
help="Treat silent rejection warnings in the log as errors (elevate exit code to 1)",
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
# --- Read log ---
|
||||||
|
log_content = ""
|
||||||
|
if os.path.isfile(out_file):
|
||||||
|
try:
|
||||||
|
with open(out_file, "r", encoding="utf-8-sig") as f:
|
||||||
|
log_content = f.read()
|
||||||
|
except Exception:
|
||||||
|
log_content = ""
|
||||||
|
|
||||||
|
# --- Scan log for silent rejections ---
|
||||||
|
# Platform often writes load-time rejections into /Out but exits with code 0.
|
||||||
|
# These patterns flag cases where metadata was dropped or rejected silently.
|
||||||
|
fatal_log_patterns = [
|
||||||
|
"Неверное свойство объекта метаданных",
|
||||||
|
"не входит в состав объекта метаданных",
|
||||||
|
"Неизвестное имя типа",
|
||||||
|
"Неизвестный объект метаданных",
|
||||||
|
"Ни один из документов не является регистратором для регистра",
|
||||||
|
"Неверное значение перечисления",
|
||||||
|
"не может быть приведен к типу",
|
||||||
|
]
|
||||||
|
silent_failures = []
|
||||||
|
if log_content:
|
||||||
|
for line in log_content.splitlines():
|
||||||
|
for pat in fatal_log_patterns:
|
||||||
|
if pat in line:
|
||||||
|
silent_failures.append(line.strip())
|
||||||
|
break
|
||||||
|
|
||||||
|
# --- Result ---
|
||||||
|
# Default: mirror platform's verdict via exit code. Log content (including any
|
||||||
|
# rejection warnings) is always printed to stdout for visibility. With -StrictLog,
|
||||||
|
# elevate exit code to 1 when rejection patterns are found even if platform said 0.
|
||||||
|
if exit_code == 0:
|
||||||
|
print("Load completed successfully")
|
||||||
|
else:
|
||||||
|
print(f"Error loading configuration (code: {exit_code})", file=sys.stderr)
|
||||||
|
|
||||||
|
if log_content:
|
||||||
|
print("--- Log ---")
|
||||||
|
print(log_content)
|
||||||
|
print("--- End ---")
|
||||||
|
|
||||||
|
if silent_failures:
|
||||||
|
suffix = "" if args.StrictLog else " (pass -StrictLog to treat as error)"
|
||||||
|
print(
|
||||||
|
f"[warning] log contains {len(silent_failures)} rejection(s) — "
|
||||||
|
f"platform loaded config but dropped properties/refs{suffix}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
for f in silent_failures:
|
||||||
|
print(f" {f}", file=sys.stderr)
|
||||||
|
if args.StrictLog and exit_code == 0:
|
||||||
|
exit_code = 1
|
||||||
|
|
||||||
|
sys.exit(exit_code)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temp_dir):
|
||||||
|
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -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 ".codeassistant/skills/db-run/scripts/db-run.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/db-run/scripts/db-run.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -63,14 +63,14 @@ python ".codeassistant/skills/db-run/scripts/db-run.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Простой запуск
|
# Простой запуск
|
||||||
python ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/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
|
||||||
|
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/skills/db-update/scripts/db-update.py" <параметр
|
|||||||
| `-BackgroundSuspend` | Приостановить |
|
| `-BackgroundSuspend` | Приостановить |
|
||||||
| `-BackgroundResume` | Возобновить |
|
| `-BackgroundResume` | Возобновить |
|
||||||
|
|
||||||
|
## Коды возврата
|
||||||
|
|
||||||
|
| Код | Описание |
|
||||||
|
|-----|----------|
|
||||||
|
| 0 | Успешно |
|
||||||
|
| 1 | Ошибка (см. лог) |
|
||||||
|
|
||||||
## Предупреждения
|
## Предупреждения
|
||||||
|
|
||||||
- Если обновление **не динамическое** — потребуется **монопольный доступ** к базе (все пользователи должны выйти)
|
- Если обновление **не динамическое** — потребуется **монопольный доступ** к базе (все пользователи должны выйти)
|
||||||
@@ -76,11 +83,11 @@ python ".codeassistant/skills/db-update/scripts/db-update.py" <параметр
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Обычное обновление (файловая база)
|
# Обычное обновление (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -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 ".codeassistant/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 ".codeassistant/skills/epf-build/scripts/epf-build.py" <параметр
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Сборка обработки (файловая база)
|
# Сборка обработки (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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 ".codeassistant/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 ".codeassistant/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Разборка обработки (файловая база)
|
# Разборка обработки (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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()
|
||||||
@@ -30,7 +30,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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>"]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Дальнейшие шаги
|
## Дальнейшие шаги
|
||||||
+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
-1
@@ -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
|
||||||
@@ -24,7 +24,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/epf-validate/scripts/epf-validate.py" -ObjectPath "src/МояОбработка"
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МояОбработка"
|
||||||
python ".codeassistant/skills/epf-validate/scripts/epf-validate.py" -ObjectPath "src/МояОбработка/МояОбработка.xml"
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МояОбработка/МояОбработка.xml"
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -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 ".codeassistant/skills/epf-build/scripts/epf-build.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-build/scripts/epf-build.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -64,8 +64,8 @@ python ".codeassistant/skills/epf-build/scripts/epf-build.py" <параметр
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Сборка отчёта (файловая база)
|
# Сборка отчёта (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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 ".codeassistant/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
powershell.exe -NoProfile -File .claude/skills/epf-dump/scripts/epf-dump.ps1 <параметры>
|
||||||
```
|
```
|
||||||
|
|
||||||
### Параметры скрипта
|
### Параметры скрипта
|
||||||
@@ -64,8 +64,8 @@ python ".codeassistant/skills/epf-dump/scripts/epf-dump.py" <параметры>
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Разборка отчёта (файловая база)
|
# Разборка отчёта (файловая база)
|
||||||
python ".codeassistant/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 ".codeassistant/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"
|
||||||
```
|
```
|
||||||
@@ -31,7 +31,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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]
|
||||||
```
|
```
|
||||||
|
|
||||||
## Дальнейшие шаги
|
## Дальнейшие шаги
|
||||||
+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
-1
@@ -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
|
||||||
@@ -26,7 +26,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/epf-validate/scripts/epf-validate.py" -ObjectPath "src/МойОтчёт"
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МойОтчёт"
|
||||||
python ".codeassistant/skills/epf-validate/scripts/epf-validate.py" -ObjectPath "src/МойОтчёт/МойОтчёт.xml"
|
powershell.exe -NoProfile -File .claude/skills/epf-validate/scripts/epf-validate.ps1 -ObjectPath "src/МойОтчёт/МойОтчёт.xml"
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -32,7 +32,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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 — назначение формы
|
||||||
+2
-136
@@ -1,4 +1,4 @@
|
|||||||
# form-add v1.10 — Add managed form to 1C config object
|
# form-add v1.4 — 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,139 +15,6 @@ 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 Test-ExternalObjectRoot([string]$xmlPath) {
|
|
||||||
if (-not (Test-Path $xmlPath)) { return $false }
|
|
||||||
try {
|
|
||||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
|
||||||
$el = $mx.DocumentElement.FirstChild
|
|
||||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
|
||||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
|
||||||
} catch {}
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
function Find-V8Project([string]$startDir) {
|
|
||||||
$d = $startDir
|
|
||||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
|
||||||
$pj = Join-Path $d ".v8-project.json"
|
|
||||||
if (Test-Path $pj) { return $pj }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
function Get-EditMode([string]$cfgDir) {
|
|
||||||
try {
|
|
||||||
$pj = Find-V8Project (Get-Location).Path
|
|
||||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
|
||||||
if (-not $pj) { return 'deny' }
|
|
||||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
|
||||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
|
||||||
if ($proj.databases) {
|
|
||||||
foreach ($db in $proj.databases) {
|
|
||||||
if ($db.configSrc) {
|
|
||||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
|
||||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
|
||||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
|
||||||
return 'deny'
|
|
||||||
} catch { return 'deny' }
|
|
||||||
}
|
|
||||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
|
||||||
try {
|
|
||||||
$rp = $targetPath
|
|
||||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if (Test-ExternalObjectRoot $rp) { return }
|
|
||||||
$elemUuid = Get-RootUuid $rp
|
|
||||||
$cfgDir = $null; $binPath = $null
|
|
||||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
|
||||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
|
||||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
|
||||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
|
||||||
if (-not $cfgDir) {
|
|
||||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
|
||||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
|
||||||
}
|
|
||||||
if ($elemUuid -and $cfgDir) { break }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
# New object (no element file): fall back to config root uuid.
|
|
||||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
|
||||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
|
||||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
|
||||||
if ($bytes.Length -le 32) { return }
|
|
||||||
$start = 0
|
|
||||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
|
||||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
|
||||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
|
||||||
if (-not $hm.Success) { return }
|
|
||||||
$G = [int]$hm.Groups[1].Value
|
|
||||||
$K = [int]$hm.Groups[2].Value
|
|
||||||
if ($K -eq 0) { return }
|
|
||||||
$best = $null
|
|
||||||
if ($elemUuid) {
|
|
||||||
$u = [regex]::Escape($elemUuid.ToLower())
|
|
||||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
|
||||||
$f1 = [int]$m.Groups[1].Value
|
|
||||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$blocked = $false; $code = ""; $reason = ""
|
|
||||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
|
||||||
elseif ($require -eq 'removed') {
|
|
||||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
|
||||||
}
|
|
||||||
if (-not $blocked) { return }
|
|
||||||
$mode = Get-EditMode $cfgDir
|
|
||||||
if ($mode -eq 'off') { return }
|
|
||||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
|
||||||
# latter throws and would be swallowed by this function's own catch.
|
|
||||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
|
||||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if ($code -eq "capability-off") {
|
|
||||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
|
||||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
} elseif ($code -eq "not-removed") {
|
|
||||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
|
||||||
} else {
|
|
||||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
|
||||||
}
|
|
||||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
|
||||||
exit 1
|
|
||||||
} catch { return }
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- Detect XML format version ---
|
# --- Detect XML format version ---
|
||||||
|
|
||||||
@@ -186,7 +53,6 @@ if (-not (Test-Path $ObjectPath)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$objectXmlFull = Resolve-Path $ObjectPath
|
$objectXmlFull = Resolve-Path $ObjectPath
|
||||||
Assert-EditAllowed $objectXmlFull.Path 'editable'
|
|
||||||
$script:formatVersion = Detect-FormatVersion (Split-Path $objectXmlFull.Path -Parent)
|
$script:formatVersion = Detect-FormatVersion (Split-Path $objectXmlFull.Path -Parent)
|
||||||
|
|
||||||
$xmlDoc = New-Object System.Xml.XmlDocument
|
$xmlDoc = New-Object System.Xml.XmlDocument
|
||||||
@@ -208,7 +74,7 @@ $supportedTypes = @(
|
|||||||
"Document", "Catalog", "DataProcessor", "Report",
|
"Document", "Catalog", "DataProcessor", "Report",
|
||||||
"ExternalDataProcessor", "ExternalReport",
|
"ExternalDataProcessor", "ExternalReport",
|
||||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||||
"ExchangePlan", "BusinessProcess", "Task", "DocumentJournal"
|
"ExchangePlan", "BusinessProcess", "Task"
|
||||||
)
|
)
|
||||||
|
|
||||||
$objectType = $null
|
$objectType = $null
|
||||||
+6
-221
@@ -1,9 +1,8 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-add v1.10 — Add managed form to 1C config object
|
# form-add v1.4 — 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 re
|
||||||
import sys
|
import sys
|
||||||
@@ -11,183 +10,6 @@ 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_is_external_root(xml_path):
|
|
||||||
if not os.path.isfile(xml_path):
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
mx = etree.parse(xml_path).getroot()
|
|
||||||
for child in mx:
|
|
||||||
if isinstance(child.tag, str):
|
|
||||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _sg_find_v8project(start_dir):
|
|
||||||
d = start_dir
|
|
||||||
for _ in range(20):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
pj = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pj):
|
|
||||||
return pj
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _sg_get_edit_mode(cfg_dir):
|
|
||||||
try:
|
|
||||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
|
||||||
if not pj:
|
|
||||||
return "deny"
|
|
||||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
|
||||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
|
||||||
for db in proj.get("databases", []):
|
|
||||||
src = db.get("configSrc")
|
|
||||||
if src:
|
|
||||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
|
||||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
|
||||||
if db.get("editingAllowedCheck"):
|
|
||||||
return db["editingAllowedCheck"]
|
|
||||||
if proj.get("editingAllowedCheck"):
|
|
||||||
return proj["editingAllowedCheck"]
|
|
||||||
return "deny"
|
|
||||||
except Exception:
|
|
||||||
return "deny"
|
|
||||||
|
|
||||||
|
|
||||||
def assert_edit_allowed(target_path, require):
|
|
||||||
try:
|
|
||||||
rp = os.path.abspath(target_path)
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if _sg_is_external_root(rp):
|
|
||||||
return
|
|
||||||
elem_uuid = _sg_root_uuid(rp)
|
|
||||||
cfg_dir = None
|
|
||||||
bin_path = None
|
|
||||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
|
||||||
for _ in range(12):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
if _sg_is_external_root(d + ".xml"):
|
|
||||||
return
|
|
||||||
if not elem_uuid:
|
|
||||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
|
||||||
if not cfg_dir:
|
|
||||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
|
||||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
|
||||||
cfg_dir = d
|
|
||||||
bin_path = cand
|
|
||||||
if elem_uuid and cfg_dir:
|
|
||||||
break
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
if not elem_uuid and cfg_dir:
|
|
||||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
|
||||||
if not bin_path or not os.path.exists(bin_path):
|
|
||||||
return
|
|
||||||
data = open(bin_path, "rb").read()
|
|
||||||
if len(data) <= 32:
|
|
||||||
return
|
|
||||||
if data[:3] == b"\xef\xbb\xbf":
|
|
||||||
data = data[3:]
|
|
||||||
text = data.decode("utf-8", "replace")
|
|
||||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
|
||||||
if not h:
|
|
||||||
return
|
|
||||||
g = int(h.group(1))
|
|
||||||
k = int(h.group(2))
|
|
||||||
if k == 0:
|
|
||||||
return
|
|
||||||
best = None
|
|
||||||
if elem_uuid:
|
|
||||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
|
||||||
f1 = int(m.group(1))
|
|
||||||
if best is None or f1 < best:
|
|
||||||
best = f1
|
|
||||||
blocked = False
|
|
||||||
code = ""
|
|
||||||
reason = ""
|
|
||||||
if g == 1:
|
|
||||||
blocked = True
|
|
||||||
code = "capability-off"
|
|
||||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
|
||||||
elif require == "removed":
|
|
||||||
if best is not None and best != 2:
|
|
||||||
blocked = True
|
|
||||||
code = "not-removed"
|
|
||||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
|
||||||
else:
|
|
||||||
if best is not None and best == 0:
|
|
||||||
blocked = True
|
|
||||||
code = "locked"
|
|
||||||
reason = "объект на замке — редактирование сломает обновления"
|
|
||||||
if not blocked:
|
|
||||||
return
|
|
||||||
mode = _sg_get_edit_mode(cfg_dir)
|
|
||||||
if mode == "off":
|
|
||||||
return
|
|
||||||
if mode == "warn":
|
|
||||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
|
||||||
return
|
|
||||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if code == "capability-off":
|
|
||||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
|
||||||
fix = (
|
|
||||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
|
||||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
|
||||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
|
||||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
)
|
|
||||||
elif code == "not-removed":
|
|
||||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
fix = (
|
|
||||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
fix = (
|
|
||||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
|
||||||
)
|
|
||||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
|
||||||
sys.exit(1)
|
|
||||||
except SystemExit:
|
|
||||||
raise
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
NSMAP = {
|
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",
|
||||||
@@ -210,49 +32,13 @@ def detect_format_version(d):
|
|||||||
return "2.17"
|
return "2.17"
|
||||||
|
|
||||||
|
|
||||||
def _detect_xml_style(path):
|
|
||||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
|
||||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
|
||||||
try:
|
|
||||||
raw = open(path, "rb").read()
|
|
||||||
except OSError:
|
|
||||||
return None
|
|
||||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
|
||||||
body = raw[3:] if bom else raw
|
|
||||||
crlf = b"\r\n" in body
|
|
||||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
|
||||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
|
||||||
final_nl = body.endswith(b"\n")
|
|
||||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
|
||||||
|
|
||||||
|
|
||||||
def _finalize_xml_bytes(xml_bytes, style):
|
|
||||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
|
||||||
enc_decl = style["enc"] if style else "utf-8"
|
|
||||||
xml_bytes = xml_bytes.replace(
|
|
||||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
|
||||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
|
||||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
|
||||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
|
||||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
|
||||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
|
||||||
want_final_nl = style["final_nl"] if style else True
|
|
||||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
|
||||||
if want_final_nl:
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
|
||||||
if style and style["crlf"]:
|
|
||||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
|
||||||
return xml_bytes
|
|
||||||
|
|
||||||
|
|
||||||
def save_xml_with_bom(tree, path):
|
def save_xml_with_bom(tree, path):
|
||||||
"""Save XML tree preserving the existing file's BOM/EOL/encoding-case/final-newline."""
|
"""Save XML tree to file with UTF-8 BOM."""
|
||||||
style = _detect_xml_style(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 = _finalize_xml_bytes(xml_bytes, style)
|
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" 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:
|
||||||
if style is None or style["bom"]:
|
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
|
|
||||||
@@ -298,7 +84,6 @@ def main():
|
|||||||
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))
|
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)
|
||||||
@@ -309,7 +94,7 @@ def main():
|
|||||||
"Document", "Catalog", "DataProcessor", "Report",
|
"Document", "Catalog", "DataProcessor", "Report",
|
||||||
"ExternalDataProcessor", "ExternalReport",
|
"ExternalDataProcessor", "ExternalReport",
|
||||||
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
"InformationRegister", "AccumulationRegister", "ChartOfAccounts", "ChartOfCharacteristicTypes",
|
||||||
"ExchangePlan", "BusinessProcess", "Task", "DocumentJournal",
|
"ExchangePlan", "BusinessProcess", "Task",
|
||||||
]
|
]
|
||||||
|
|
||||||
object_type = None
|
object_type = None
|
||||||
+16
-43
@@ -29,10 +29,10 @@ allowed-tools:
|
|||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
# Режим JSON DSL
|
# Режим JSON DSL
|
||||||
python ".codeassistant/skills/form-compile/scripts/form-compile.py" -JsonPath "<json>" -OutputPath "<Form.xml>"
|
powershell.exe -NoProfile -File .claude/skills/form-compile/scripts/form-compile.ps1 -JsonPath "<json>" -OutputPath "<Form.xml>"
|
||||||
|
|
||||||
# Режим from-object (объект и purpose выводятся из OutputPath; Document и Catalog)
|
# Режим from-object (объект и purpose выводятся из OutputPath; Document и Catalog)
|
||||||
python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject -OutputPath "<.../TypePlural/ObjectName/Forms/FormName/Ext/Form.xml>"
|
powershell.exe -NoProfile -File .claude/skills/form-compile/scripts/form-compile.ps1 -FromObject -OutputPath "<.../TypePlural/ObjectName/Forms/FormName/Ext/Form.xml>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## JSON DSL — справка
|
## JSON DSL — справка
|
||||||
@@ -61,7 +61,7 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
|
|
||||||
| DSL ключ | XML элемент | Значение ключа |
|
| DSL ключ | XML элемент | Значение ключа |
|
||||||
|--------------|-------------------|---------------------------------------------------|
|
|--------------|-------------------|---------------------------------------------------|
|
||||||
| `"group"` | UsualGroup | ориентация: `"vertical"` / `"horizontalIfPossible"` / `"alwaysHorizontal"` (поведение — отдельный ключ `behavior`) |
|
| `"group"` | UsualGroup | `"horizontal"` / `"vertical"` / `"alwaysHorizontal"` / `"alwaysVertical"` / `"collapsible"` |
|
||||||
| `"columnGroup"` | ColumnGroup | `"horizontal"` / `"vertical"` / `"inCell"` — только внутри `columns` таблицы |
|
| `"columnGroup"` | ColumnGroup | `"horizontal"` / `"vertical"` / `"inCell"` — только внутри `columns` таблицы |
|
||||||
| `"input"` | InputField | имя элемента |
|
| `"input"` | InputField | имя элемента |
|
||||||
| `"check"` | CheckBoxField | имя |
|
| `"check"` | CheckBoxField | имя |
|
||||||
@@ -83,15 +83,15 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `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`)
|
||||||
|
|
||||||
Компилятор предупреждает о неизвестных событиях. Имена регистрозависимы — используйте точно как указано.
|
Компилятор предупреждает о неизвестных событиях. Имена регистрозависимы — используйте точно как указано.
|
||||||
|
|
||||||
@@ -116,7 +116,7 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
| Ключ | Описание | Пример |
|
| Ключ | Описание | Пример |
|
||||||
|------|----------|--------|
|
|------|----------|--------|
|
||||||
| `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` | Кнопка выбора ("...") | ссылочное поле |
|
||||||
@@ -179,15 +179,13 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
|
|
||||||
### Группа (group)
|
### Группа (group)
|
||||||
|
|
||||||
Значение ключа задаёт **ориентацию**: `"vertical"`, `"horizontalIfPossible"`, `"alwaysHorizontal"`.
|
Значение ключа задаёт ориентацию: `"horizontal"`, `"vertical"`, `"alwaysHorizontal"`, `"alwaysVertical"`, `"collapsible"`.
|
||||||
|
|
||||||
| Ключ | Описание |
|
| Ключ | Описание |
|
||||||
|------|----------|
|
|------|----------|
|
||||||
| `behavior` | Поведение группы: `"collapsible"` (сворачиваемая) / `"popup"` (всплывающая). Опустить = обычная |
|
|
||||||
| `showTitle: true` | Показывать заголовок группы |
|
| `showTitle: true` | Показывать заголовок группы |
|
||||||
| `united: false` | Левый край полей ввода выравнивается только в пределах этой группы (по умолчанию `true` — сквозное выравнивание по самому длинному заголовку, в т.ч. с соседними группами) |
|
| `united: false` | Левый край полей ввода выравнивается только в пределах этой группы (по умолчанию `true` — сквозное выравнивание по самому длинному заголовку, в т.ч. с соседними группами) |
|
||||||
| `collapsed: true` | Для `behavior: "collapsible"` / `"popup"` — группа создаётся свёрнутой |
|
| `collapsed: true` | Только для `"group": "collapsible"` — группа создаётся свёрнутой |
|
||||||
| `controlRepresentation` | Отображение управления свёрткой (`behavior: "collapsible"`): `"TitleHyperlink"` (гиперссылка заголовка, по умолчанию) / `"Picture"` (картинка) |
|
|
||||||
| `representation` | `"none"`, `"normal"`, `"weak"`, `"strong"` |
|
| `representation` | `"none"`, `"normal"`, `"weak"`, `"strong"` |
|
||||||
| `children: [...]` | Вложенные элементы |
|
| `children: [...]` | Вложенные элементы |
|
||||||
|
|
||||||
@@ -204,8 +202,8 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
| `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` | Режим выбора (для форм выбора) |
|
| `choiceMode: true` | Режим выбора (для форм выбора) |
|
||||||
| `initialTreeView` | `"ExpandTopLevel"` и др. (иерархические списки) |
|
| `initialTreeView` | `"ExpandTopLevel"` и др. (иерархические списки) |
|
||||||
| `enableDrag: true` | Разрешить перетаскивание |
|
| `enableDrag: true` | Разрешить перетаскивание |
|
||||||
@@ -242,15 +240,6 @@ python ".codeassistant/skills/form-compile/scripts/form-compile.py" -FromObject
|
|||||||
]}
|
]}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Картинка-поле (picField)
|
|
||||||
|
|
||||||
PictureField, привязанный к булеву/числу, рисует иконку только при заданном `valuesPicture`:
|
|
||||||
|
|
||||||
| Ключ | Описание |
|
|
||||||
|------|----------|
|
|
||||||
| `valuesPicture` | Ref картинки значения: `"StdPicture.Favorites"`, `"CommonPicture.X"` |
|
|
||||||
| `loadTransparent: true` | Скрыть кадр «нет значения» |
|
|
||||||
|
|
||||||
### Страницы (pages + page)
|
### Страницы (pages + page)
|
||||||
|
|
||||||
| Ключ (pages) | Описание |
|
| Ключ (pages) | Описание |
|
||||||
@@ -442,7 +431,7 @@ 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": "Лог" },
|
||||||
@@ -502,8 +491,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": "Данные.Дата" },
|
||||||
@@ -524,26 +513,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 ".codeassistant/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 формат
|
||||||
+4
-187
@@ -1,4 +1,4 @@
|
|||||||
# form-edit v1.5 — 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)]
|
||||||
@@ -12,137 +12,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 Test-ExternalObjectRoot([string]$xmlPath) {
|
|
||||||
if (-not (Test-Path $xmlPath)) { return $false }
|
|
||||||
try {
|
|
||||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
|
||||||
$el = $mx.DocumentElement.FirstChild
|
|
||||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
|
||||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
|
||||||
} catch {}
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
function Find-V8Project([string]$startDir) {
|
|
||||||
$d = $startDir
|
|
||||||
for ($i = 0; $i -lt 20 -and $d; $i++) {
|
|
||||||
$pj = Join-Path $d ".v8-project.json"
|
|
||||||
if (Test-Path $pj) { return $pj }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
return $null
|
|
||||||
}
|
|
||||||
function Get-EditMode([string]$cfgDir) {
|
|
||||||
try {
|
|
||||||
$pj = Find-V8Project (Get-Location).Path
|
|
||||||
if (-not $pj) { $pj = Find-V8Project $cfgDir }
|
|
||||||
if (-not $pj) { return 'deny' }
|
|
||||||
$proj = Get-Content -Raw $pj | ConvertFrom-Json
|
|
||||||
$cfgFull = [System.IO.Path]::GetFullPath($cfgDir).TrimEnd('\', '/')
|
|
||||||
if ($proj.databases) {
|
|
||||||
foreach ($db in $proj.databases) {
|
|
||||||
if ($db.configSrc) {
|
|
||||||
$src = [System.IO.Path]::GetFullPath($db.configSrc).TrimEnd('\', '/')
|
|
||||||
if ($cfgFull -eq $src -or $cfgFull.StartsWith($src + [System.IO.Path]::DirectorySeparatorChar)) {
|
|
||||||
if ($db.editingAllowedCheck) { return $db.editingAllowedCheck }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ($proj.editingAllowedCheck) { return $proj.editingAllowedCheck }
|
|
||||||
return 'deny'
|
|
||||||
} catch { return 'deny' }
|
|
||||||
}
|
|
||||||
function Assert-EditAllowed([string]$targetPath, [string]$require) {
|
|
||||||
try {
|
|
||||||
$rp = $targetPath
|
|
||||||
try { $rp = (Resolve-Path $targetPath -ErrorAction Stop).Path } catch {}
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if (Test-ExternalObjectRoot $rp) { return }
|
|
||||||
$elemUuid = Get-RootUuid $rp
|
|
||||||
$cfgDir = $null; $binPath = $null
|
|
||||||
$d = if (Test-Path $rp -PathType Container) { $rp } else { [System.IO.Path]::GetDirectoryName($rp) }
|
|
||||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
|
||||||
if (Test-ExternalObjectRoot "$d.xml") { return }
|
|
||||||
if (-not $elemUuid) { $elemUuid = Get-RootUuid "$d.xml" }
|
|
||||||
if (-not $cfgDir) {
|
|
||||||
$cand = Join-Path (Join-Path $d "Ext") "ParentConfigurations.bin"
|
|
||||||
if ((Test-Path $cand) -or (Test-Path (Join-Path $d "Configuration.xml"))) { $cfgDir = $d; $binPath = $cand }
|
|
||||||
}
|
|
||||||
if ($elemUuid -and $cfgDir) { break }
|
|
||||||
$parent = [System.IO.Path]::GetDirectoryName($d)
|
|
||||||
if ($parent -eq $d) { break }
|
|
||||||
$d = $parent
|
|
||||||
}
|
|
||||||
# New object (no element file): fall back to config root uuid.
|
|
||||||
if (-not $elemUuid -and $cfgDir) { $elemUuid = Get-RootUuid (Join-Path $cfgDir "Configuration.xml") }
|
|
||||||
if (-not $binPath -or -not (Test-Path $binPath)) { return }
|
|
||||||
$bytes = [System.IO.File]::ReadAllBytes($binPath)
|
|
||||||
if ($bytes.Length -le 32) { return }
|
|
||||||
$start = 0
|
|
||||||
if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { $start = 3 }
|
|
||||||
$text = [System.Text.Encoding]::UTF8.GetString($bytes, $start, $bytes.Length - $start)
|
|
||||||
$hm = [regex]::Match($text, '^\{6,(\d+),(\d+),')
|
|
||||||
if (-not $hm.Success) { return }
|
|
||||||
$G = [int]$hm.Groups[1].Value
|
|
||||||
$K = [int]$hm.Groups[2].Value
|
|
||||||
if ($K -eq 0) { return }
|
|
||||||
$best = $null
|
|
||||||
if ($elemUuid) {
|
|
||||||
$u = [regex]::Escape($elemUuid.ToLower())
|
|
||||||
foreach ($m in [regex]::Matches($text, "([0-2]),0,$u")) {
|
|
||||||
$f1 = [int]$m.Groups[1].Value
|
|
||||||
if ($null -eq $best -or $f1 -lt $best) { $best = $f1 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$blocked = $false; $code = ""; $reason = ""
|
|
||||||
if ($G -eq 1) { $blocked = $true; $code = "capability-off"; $reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)" }
|
|
||||||
elseif ($require -eq 'removed') {
|
|
||||||
if ($null -ne $best -and $best -ne 2) { $blocked = $true; $code = "not-removed"; $reason = "объект не снят с поддержки — удаление сломает обновления" }
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
if ($null -ne $best -and $best -eq 0) { $blocked = $true; $code = "locked"; $reason = "объект на замке — редактирование сломает обновления" }
|
|
||||||
}
|
|
||||||
if (-not $blocked) { return }
|
|
||||||
$mode = Get-EditMode $cfgDir
|
|
||||||
if ($mode -eq 'off') { return }
|
|
||||||
# Use Console.Error (not Write-Error) — under ErrorActionPreference=Stop the
|
|
||||||
# latter throws and would be swallowed by this function's own catch.
|
|
||||||
if ($mode -eq 'warn') { [Console]::Error.WriteLine("[support-guard] ПРЕДУПРЕЖДЕНИЕ: $reason. Цель: $rp"); return }
|
|
||||||
$head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
$cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
$offNote = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if ($code -eq "capability-off") {
|
|
||||||
$state = "Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «$rp» редактировать нельзя."
|
|
||||||
$fix = "Либо снять защиту явно (навык support-edit, два шага):`n 1. support-edit -Path ""$cfgDir"" -Capability on — включить возможность изменения (объекты пока остаются на замке);`n 2. support-edit -Path ""$rp"" -Set editable — открыть этот объект для редактирования.`n Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
} elseif ($code -eq "not-removed") {
|
|
||||||
$state = "Состояние: объект «$rp» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
$fix = "Либо сначала снять объект с поддержки, затем удалять:`n support-edit -Path ""$rp"" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно."
|
|
||||||
} else {
|
|
||||||
$state = "Состояние: объект «$rp» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
$fix = "Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):`n support-edit -Path ""$rp"" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);`n support-edit -Path ""$rp"" -Set off-support — снять с поддержки: обновления по объекту больше не приходят."
|
|
||||||
}
|
|
||||||
[Console]::Error.WriteLine("$head`n$state`n$cfe`n$fix`n$offNote")
|
|
||||||
exit 1
|
|
||||||
} catch { return }
|
|
||||||
}
|
|
||||||
|
|
||||||
# === 1. Load Form.xml ===
|
# === 1. Load Form.xml ===
|
||||||
|
|
||||||
if (-not (Test-Path $FormPath)) {
|
if (-not (Test-Path $FormPath)) {
|
||||||
@@ -155,7 +24,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 {
|
||||||
@@ -423,16 +291,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")
|
||||||
@@ -1006,31 +864,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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1109,22 +953,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>"
|
||||||
@@ -1193,17 +1021,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>"
|
||||||
+7
-259
@@ -1,4 +1,4 @@
|
|||||||
# form-edit v1.5 — 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,182 +11,6 @@ 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_is_external_root(xml_path):
|
|
||||||
if not os.path.isfile(xml_path):
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
mx = etree.parse(xml_path).getroot()
|
|
||||||
for child in mx:
|
|
||||||
if isinstance(child.tag, str):
|
|
||||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
|
|
||||||
def _sg_find_v8project(start_dir):
|
|
||||||
d = start_dir
|
|
||||||
for _ in range(20):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
pj = os.path.join(d, ".v8-project.json")
|
|
||||||
if os.path.isfile(pj):
|
|
||||||
return pj
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _sg_get_edit_mode(cfg_dir):
|
|
||||||
try:
|
|
||||||
pj = _sg_find_v8project(os.getcwd()) or _sg_find_v8project(cfg_dir)
|
|
||||||
if not pj:
|
|
||||||
return "deny"
|
|
||||||
proj = json.loads(open(pj, encoding="utf-8-sig").read())
|
|
||||||
cfg_full = os.path.normcase(os.path.abspath(cfg_dir)).rstrip("\\/")
|
|
||||||
for db in proj.get("databases", []):
|
|
||||||
src = db.get("configSrc")
|
|
||||||
if src:
|
|
||||||
src_full = os.path.normcase(os.path.abspath(src)).rstrip("\\/")
|
|
||||||
if cfg_full == src_full or cfg_full.startswith(src_full + os.sep):
|
|
||||||
if db.get("editingAllowedCheck"):
|
|
||||||
return db["editingAllowedCheck"]
|
|
||||||
if proj.get("editingAllowedCheck"):
|
|
||||||
return proj["editingAllowedCheck"]
|
|
||||||
return "deny"
|
|
||||||
except Exception:
|
|
||||||
return "deny"
|
|
||||||
|
|
||||||
|
|
||||||
def assert_edit_allowed(target_path, require):
|
|
||||||
try:
|
|
||||||
rp = os.path.abspath(target_path)
|
|
||||||
# Autonomous external object (EPF/ERF): never part of a config on support (issue #39).
|
|
||||||
if _sg_is_external_root(rp):
|
|
||||||
return
|
|
||||||
elem_uuid = _sg_root_uuid(rp)
|
|
||||||
cfg_dir = None
|
|
||||||
bin_path = None
|
|
||||||
d = rp if os.path.isdir(rp) else os.path.dirname(rp)
|
|
||||||
for _ in range(12):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
if _sg_is_external_root(d + ".xml"):
|
|
||||||
return
|
|
||||||
if not elem_uuid:
|
|
||||||
elem_uuid = _sg_root_uuid(d + ".xml")
|
|
||||||
if not cfg_dir:
|
|
||||||
cand = os.path.join(d, "Ext", "ParentConfigurations.bin")
|
|
||||||
if os.path.exists(cand) or os.path.exists(os.path.join(d, "Configuration.xml")):
|
|
||||||
cfg_dir = d
|
|
||||||
bin_path = cand
|
|
||||||
if elem_uuid and cfg_dir:
|
|
||||||
break
|
|
||||||
parent = os.path.dirname(d)
|
|
||||||
if parent == d:
|
|
||||||
break
|
|
||||||
d = parent
|
|
||||||
if not elem_uuid and cfg_dir:
|
|
||||||
elem_uuid = _sg_root_uuid(os.path.join(cfg_dir, "Configuration.xml"))
|
|
||||||
if not bin_path or not os.path.exists(bin_path):
|
|
||||||
return
|
|
||||||
data = open(bin_path, "rb").read()
|
|
||||||
if len(data) <= 32:
|
|
||||||
return
|
|
||||||
if data[:3] == b"\xef\xbb\xbf":
|
|
||||||
data = data[3:]
|
|
||||||
text = data.decode("utf-8", "replace")
|
|
||||||
h = re.match(r"\{6,(\d+),(\d+),", text)
|
|
||||||
if not h:
|
|
||||||
return
|
|
||||||
g = int(h.group(1))
|
|
||||||
k = int(h.group(2))
|
|
||||||
if k == 0:
|
|
||||||
return
|
|
||||||
best = None
|
|
||||||
if elem_uuid:
|
|
||||||
for m in re.finditer(r"([0-2]),0," + re.escape(elem_uuid.lower()), text):
|
|
||||||
f1 = int(m.group(1))
|
|
||||||
if best is None or f1 < best:
|
|
||||||
best = f1
|
|
||||||
blocked = False
|
|
||||||
code = ""
|
|
||||||
reason = ""
|
|
||||||
if g == 1:
|
|
||||||
blocked = True
|
|
||||||
code = "capability-off"
|
|
||||||
reason = "возможность изменения конфигурации выключена (вся конфигурация read-only)"
|
|
||||||
elif require == "removed":
|
|
||||||
if best is not None and best != 2:
|
|
||||||
blocked = True
|
|
||||||
code = "not-removed"
|
|
||||||
reason = "объект не снят с поддержки — удаление сломает обновления"
|
|
||||||
else:
|
|
||||||
if best is not None and best == 0:
|
|
||||||
blocked = True
|
|
||||||
code = "locked"
|
|
||||||
reason = "объект на замке — редактирование сломает обновления"
|
|
||||||
if not blocked:
|
|
||||||
return
|
|
||||||
mode = _sg_get_edit_mode(cfg_dir)
|
|
||||||
if mode == "off":
|
|
||||||
return
|
|
||||||
if mode == "warn":
|
|
||||||
sys.stderr.write(f"[support-guard] ПРЕДУПРЕЖДЕНИЕ: {reason}. Цель: {rp}\n")
|
|
||||||
return
|
|
||||||
head = "[support-guard] Редактирование отклонено: это объект типовой конфигурации на поддержке поставщика, прямое редактирование молча сломает будущие обновления."
|
|
||||||
cfe = "Рекомендуемый путь: внести доработку в расширение (навыки cfe-borrow / cfe-patch-method) — состояние поддержки менять не нужно, обновления вендора сохраняются."
|
|
||||||
off_note = "Снять проверку для этой базы: editingAllowedCheck = warn|off в .v8-project.json."
|
|
||||||
if code == "capability-off":
|
|
||||||
state = f"Состояние: у всей конфигурации выключена возможность изменения (режим read-only «из коробки») — поэтому объект «{rp}» редактировать нельзя."
|
|
||||||
fix = (
|
|
||||||
"Либо снять защиту явно (навык support-edit, два шага):\n"
|
|
||||||
f' 1. support-edit -Path "{cfg_dir}" -Capability on — включить возможность изменения (объекты пока остаются на замке);\n'
|
|
||||||
f' 2. support-edit -Path "{rp}" -Set editable — открыть этот объект для редактирования.\n'
|
|
||||||
" Изменение применяется в базу полной загрузкой выгрузки и обходит механизм обновлений вендора."
|
|
||||||
)
|
|
||||||
elif code == "not-removed":
|
|
||||||
state = f"Состояние: объект «{rp}» на поддержке (не снят с поддержки) — его удаление разорвёт обновления вендора."
|
|
||||||
fix = (
|
|
||||||
"Либо сначала снять объект с поддержки, затем удалять:\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — объект уходит из-под обновлений, после этого удаление безопасно.'
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
state = f"Состояние: объект «{rp}» на замке (возможность изменения конфигурации включена, но сам объект не редактируется)."
|
|
||||||
fix = (
|
|
||||||
"Либо разрешить редактирование этого объекта (навык support-edit, выбрать одно):\n"
|
|
||||||
f' support-edit -Path "{rp}" -Set editable — редактировать и дальше получать обновления вендора (возможны конфликты слияния);\n'
|
|
||||||
f' support-edit -Path "{rp}" -Set off-support — снять с поддержки: обновления по объекту больше не приходят.'
|
|
||||||
)
|
|
||||||
sys.stderr.write(head + "\n" + state + "\n" + cfe + "\n" + fix + "\n" + off_note + "\n")
|
|
||||||
sys.exit(1)
|
|
||||||
except SystemExit:
|
|
||||||
raise
|
|
||||||
except Exception:
|
|
||||||
return
|
|
||||||
|
|
||||||
|
|
||||||
# ── arg parsing ──────────────────────────────────────────────
|
# ── arg parsing ──────────────────────────────────────────────
|
||||||
|
|
||||||
parser = argparse.ArgumentParser(allow_abbrev=False)
|
parser = argparse.ArgumentParser(allow_abbrev=False)
|
||||||
@@ -239,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)
|
||||||
@@ -542,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"],
|
||||||
@@ -1173,26 +988,7 @@ if elements_list:
|
|||||||
# 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:
|
||||||
@@ -1203,8 +999,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
|
||||||
@@ -1260,19 +1055,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}>")
|
||||||
@@ -1334,14 +1116,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:
|
||||||
@@ -1475,39 +1249,13 @@ if elem_events_list:
|
|||||||
|
|
||||||
# ── 13. Save ────────────────────────────────────────────────
|
# ── 13. Save ────────────────────────────────────────────────
|
||||||
|
|
||||||
# Round-trip: определить стиль исходного файла (на диске он ещё не перезаписан).
|
|
||||||
try:
|
|
||||||
_fe_raw = open(resolved_form_path, "rb").read()
|
|
||||||
except OSError:
|
|
||||||
_fe_raw = None
|
|
||||||
if _fe_raw is not None:
|
|
||||||
_fe_bom = _fe_raw.startswith(b"\xef\xbb\xbf")
|
|
||||||
_fe_body = _fe_raw[3:] if _fe_bom else _fe_raw
|
|
||||||
_fe_crlf = b"\r\n" in _fe_body
|
|
||||||
_fe_enc_m = re.search(rb'encoding="([^"]+)"', _fe_body[:200])
|
|
||||||
_fe_enc = _fe_enc_m.group(1).decode("ascii") if _fe_enc_m else "utf-8"
|
|
||||||
_fe_final_nl = _fe_body.endswith(b"\n")
|
|
||||||
else:
|
|
||||||
_fe_bom, _fe_crlf, _fe_enc, _fe_final_nl = True, False, "utf-8", True
|
|
||||||
|
|
||||||
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
xml_bytes = etree.tostring(tree, xml_declaration=True, encoding="UTF-8")
|
||||||
# Восстановить регистр encoding как в оригинале.
|
# Fix XML declaration quotes
|
||||||
xml_bytes = xml_bytes.replace(
|
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
||||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
if not xml_bytes.endswith(b"\n"):
|
||||||
b'<?xml version="1.0" encoding="' + _fe_enc.encode("ascii") + b'"?>')
|
|
||||||
# Канонизировать переносы к LF (убирает от \r в tail'ах).
|
|
||||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
|
||||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
|
||||||
# Финальный перенос — как в оригинале.
|
|
||||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
|
||||||
if _fe_final_nl:
|
|
||||||
xml_bytes += b"\n"
|
xml_bytes += b"\n"
|
||||||
# EOL — как в оригинале.
|
# Write with BOM
|
||||||
if _fe_crlf:
|
|
||||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
|
||||||
# Write preserving BOM as in original.
|
|
||||||
with open(resolved_form_path, "wb") as f:
|
with open(resolved_form_path, "wb") as f:
|
||||||
if _fe_bom:
|
|
||||||
f.write(b'\xef\xbb\xbf')
|
f.write(b'\xef\xbb\xbf')
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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>"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Параметры
|
## Параметры
|
||||||
+1
-78
@@ -1,4 +1,4 @@
|
|||||||
# form-info v1.5 — Analyze 1C managed form structure
|
# form-info v1.3 — 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)]
|
||||||
@@ -368,81 +368,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 Test-ExternalObjectRoot([string]$xmlPath) {
|
|
||||||
if (-not (Test-Path $xmlPath)) { return $false }
|
|
||||||
try {
|
|
||||||
[xml]$mx = Get-Content -Path $xmlPath -Encoding UTF8
|
|
||||||
$el = $mx.DocumentElement.FirstChild
|
|
||||||
while ($el -and $el.NodeType -ne 'Element') { $el = $el.NextSibling }
|
|
||||||
if ($el) { return @('ExternalDataProcessor','ExternalReport') -contains $el.LocalName }
|
|
||||||
} catch {}
|
|
||||||
return $false
|
|
||||||
}
|
|
||||||
function 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
|
|
||||||
if (Test-ExternalObjectRoot $rp) { return $null }
|
|
||||||
$d = [System.IO.Path]::GetDirectoryName($rp)
|
|
||||||
for ($i = 0; $i -lt 12 -and $d; $i++) {
|
|
||||||
if (Test-ExternalObjectRoot "$d.xml") { return $null }
|
|
||||||
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 = @()
|
||||||
@@ -460,8 +385,6 @@ if ($formTitle) { $header += " — `"$formTitle`"" }
|
|||||||
if ($objectContext) { $header += " ($objectContext)" }
|
if ($objectContext) { $header += " ($objectContext)" }
|
||||||
$header += " ==="
|
$header += " ==="
|
||||||
$lines += $header
|
$lines += $header
|
||||||
$support = Get-SupportStatusForPath $FormPath
|
|
||||||
if ($null -ne $support) { $lines += "Поддержка: $support" }
|
|
||||||
|
|
||||||
# --- Form properties (Title excluded — shown in header) ---
|
# --- Form properties (Title excluded — shown in header) ---
|
||||||
|
|
||||||
+1
-91
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-info v1.5 — Analyze 1C managed form structure
|
# form-info v1.3 — 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,93 +336,6 @@ 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
|
|
||||||
def is_external_root(xml_path):
|
|
||||||
if not os.path.isfile(xml_path):
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
mx = etree.parse(xml_path).getroot()
|
|
||||||
for child in mx:
|
|
||||||
if isinstance(child.tag, str):
|
|
||||||
return child.tag.split("}")[-1] in ("ExternalDataProcessor", "ExternalReport")
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
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)
|
|
||||||
if is_external_root(rp):
|
|
||||||
return None
|
|
||||||
bin_path = None
|
|
||||||
d = os.path.dirname(rp)
|
|
||||||
for _ in range(12):
|
|
||||||
if not d:
|
|
||||||
break
|
|
||||||
if is_external_root(d + ".xml"):
|
|
||||||
return None
|
|
||||||
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():
|
||||||
@@ -528,9 +441,6 @@ def main():
|
|||||||
header += f" ({object_context})"
|
header += f" ({object_context})"
|
||||||
header += " ==="
|
header += " ==="
|
||||||
lines.append(header)
|
lines.append(header)
|
||||||
_support = get_support_status_for_path(form_path)
|
|
||||||
if _support is not None:
|
|
||||||
lines.append(f"Поддержка: {_support}")
|
|
||||||
|
|
||||||
# --- Form properties (Title excluded -- shown in header) ---
|
# --- Form properties (Title excluded -- shown in header) ---
|
||||||
prop_names = [
|
prop_names = [
|
||||||
@@ -31,7 +31,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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.4 — 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
|
||||||
+10
-50
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# remove-form v1.4 — 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
|
||||||
@@ -13,49 +13,13 @@ from lxml import etree
|
|||||||
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
||||||
|
|
||||||
|
|
||||||
def _detect_xml_style(path):
|
|
||||||
"""Стиль существующего файла для round-trip-сохранения: BOM / EOL / регистр encoding /
|
|
||||||
финальный перенос. None → файл новый (сохранить текущее поведение)."""
|
|
||||||
try:
|
|
||||||
raw = open(path, "rb").read()
|
|
||||||
except OSError:
|
|
||||||
return None
|
|
||||||
bom = raw.startswith(b"\xef\xbb\xbf")
|
|
||||||
body = raw[3:] if bom else raw
|
|
||||||
crlf = b"\r\n" in body
|
|
||||||
m = re.search(rb'encoding="([^"]+)"', body[:200])
|
|
||||||
enc = m.group(1).decode("ascii") if m else "utf-8"
|
|
||||||
final_nl = body.endswith(b"\n")
|
|
||||||
return {"bom": bom, "crlf": crlf, "enc": enc, "final_nl": final_nl}
|
|
||||||
|
|
||||||
|
|
||||||
def _finalize_xml_bytes(xml_bytes, style):
|
|
||||||
"""Привести сериализованные байты к стилю оригинала (или к дефолту, если style is None)."""
|
|
||||||
enc_decl = style["enc"] if style else "utf-8"
|
|
||||||
xml_bytes = xml_bytes.replace(
|
|
||||||
b"<?xml version='1.0' encoding='UTF-8'?>",
|
|
||||||
b'<?xml version="1.0" encoding="' + enc_decl.encode("ascii") + b'"?>')
|
|
||||||
# Канонизировать переносы к LF (убирает от \r в tail'ах)
|
|
||||||
xml_bytes = (xml_bytes.replace(b" \n", b"\n").replace(b" ", b"")
|
|
||||||
.replace(b"\r\n", b"\n").replace(b"\r", b"\n"))
|
|
||||||
# Финальный перенос — как в оригинале (новый файл → есть)
|
|
||||||
want_final_nl = style["final_nl"] if style else True
|
|
||||||
xml_bytes = xml_bytes.rstrip(b"\n")
|
|
||||||
if want_final_nl:
|
|
||||||
xml_bytes += b"\n"
|
|
||||||
# EOL — как в оригинале (новый файл → LF, текущее поведение)
|
|
||||||
if style and style["crlf"]:
|
|
||||||
xml_bytes = xml_bytes.replace(b"\n", b"\r\n")
|
|
||||||
return xml_bytes
|
|
||||||
|
|
||||||
|
|
||||||
def save_xml_with_bom(tree, path):
|
def save_xml_with_bom(tree, path):
|
||||||
"""Save XML tree preserving the existing file's BOM/EOL/encoding-case/final-newline."""
|
"""Save XML tree to file with UTF-8 BOM."""
|
||||||
style = _detect_xml_style(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 = _finalize_xml_bytes(xml_bytes, style)
|
xml_bytes = xml_bytes.replace(b"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" 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:
|
||||||
if style is None or style["bom"]:
|
|
||||||
f.write(b"\xef\xbb\xbf")
|
f.write(b"\xef\xbb\xbf")
|
||||||
f.write(xml_bytes)
|
f.write(xml_bytes)
|
||||||
|
|
||||||
@@ -121,15 +85,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)
|
||||||
+2
-2
@@ -23,7 +23,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/skills/form-validate/scripts/form-validate.py" -FormPath "Catalogs/Номенклатура/Forms/ФормаЭлемента"
|
powershell.exe -NoProfile -File .claude/skills/form-validate/scripts/form-validate.ps1 -FormPath "Catalogs/Номенклатура/Forms/ФормаЭлемента"
|
||||||
python ".codeassistant/skills/form-validate/scripts/form-validate.py" -FormPath "src/МояОбработка/Forms/Форма/Ext/Form.xml"
|
powershell.exe -NoProfile -File .claude/skills/form-validate/scripts/form-validate.ps1 -FormPath "src/МояОбработка/Forms/Форма/Ext/Form.xml"
|
||||||
```
|
```
|
||||||
|
|
||||||
+5
-88
@@ -1,4 +1,4 @@
|
|||||||
# form-validate v1.8 — Validate 1C managed form
|
# form-validate v1.4 — 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)]
|
||||||
@@ -156,7 +156,6 @@ 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 +185,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 +229,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 +241,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 +251,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 +270,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 +290,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 +344,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,65 +360,24 @@ 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 }
|
|
||||||
$dpNode = $node.SelectSingleNode("f:$bTag", $nsMgr)
|
|
||||||
if (-not $dpNode) { continue }
|
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:
|
|
||||||
# - 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++
|
$pathChecked++
|
||||||
|
|
||||||
# Extract root segment of path, strip array indices like [0]
|
# Extract root segment of path, strip array indices like [0]
|
||||||
$cleanPath = $dataPath -replace '\[\d+\]', ''
|
$cleanPath = $dataPath -replace '\[\d+\]', ''
|
||||||
# Strip leading '~' (current row of DynamicList: ~Список.Поле)
|
|
||||||
if ($cleanPath.StartsWith('~')) { $cleanPath = $cleanPath.Substring(1) }
|
|
||||||
$segments = $cleanPath -split '\.'
|
$segments = $cleanPath -split '\.'
|
||||||
$rootAttr = $segments[0]
|
$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)) {
|
if (-not $attrMap.ContainsKey($rootAttr)) {
|
||||||
Report-Error "[$tag] '$elName': $bTag='$dataPath' — attribute '$rootAttr' not found"
|
Report-Error "[$tag] '$elName': DataPath='$dataPath' — attribute '$rootAttr' not found"
|
||||||
$pathErrors++
|
$pathErrors++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
$pathMsg = ""
|
$pathMsg = ""
|
||||||
if ($pathChecked -gt 0) { $pathMsg = "$pathChecked paths checked" }
|
if ($pathChecked -gt 0) { $pathMsg = "$pathChecked paths checked" }
|
||||||
@@ -469,9 +386,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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+5
-75
@@ -1,5 +1,5 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# form-validate v1.8 — Validate 1C managed form
|
# form-validate v1.4 — 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
|
||||||
@@ -183,7 +183,6 @@ def main():
|
|||||||
|
|
||||||
# --- 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 +211,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 +252,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 +261,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 +271,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 +289,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 +300,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 +348,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,10 +368,7 @@ 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:
|
|
||||||
break
|
|
||||||
dp_node = node.find(f"{{{F_NS}}}{b_tag}")
|
|
||||||
if dp_node is None:
|
if dp_node is None:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -414,46 +376,14 @@ def main():
|
|||||||
if not data_path:
|
if not data_path:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Opaque platform-internal shapes — not validatable from Form.xml alone:
|
|
||||||
# - 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
|
path_checked += 1
|
||||||
|
|
||||||
clean_path = re.sub(r'\[\d+\]', '', data_path)
|
clean_path = re.sub(r'\[\d+\]', '', data_path)
|
||||||
# Strip leading '~' (current row of DynamicList: ~Список.Поле)
|
|
||||||
if clean_path.startswith('~'):
|
|
||||||
clean_path = clean_path[1:]
|
|
||||||
segments = clean_path.split(".")
|
segments = clean_path.split(".")
|
||||||
root_attr = segments[0]
|
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:
|
if root_attr not in attr_map:
|
||||||
report_error(f"[{tag}] '{el_name}': {b_tag}='{data_path}' — attribute '{root_attr}' not found")
|
report_error(f"[{tag}] '{el_name}': DataPath='{data_path}' \u2014 attribute '{root_attr}' not found")
|
||||||
path_errors += 1
|
path_errors += 1
|
||||||
|
|
||||||
path_msg = ""
|
path_msg = ""
|
||||||
@@ -463,7 +393,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:
|
||||||
@@ -731,7 +661,7 @@ def main():
|
|||||||
# ExternalDataProcessorObject/ExternalReportObject valid only in EPF/ERF context
|
# ExternalDataProcessorObject/ExternalReportObject valid only in EPF/ERF context
|
||||||
if is_config_context and prefix in ('ExternalDataProcessorObject', 'ExternalReportObject'):
|
if is_config_context and prefix in ('ExternalDataProcessorObject', 'ExternalReportObject'):
|
||||||
report_error(f'12. Type "{tv}": External* type in configuration context (use DataProcessorObject/ReportObject instead)')
|
report_error(f'12. Type "{tv}": External* type in configuration context (use DataProcessorObject/ReportObject instead)')
|
||||||
type_error_count += 1
|
type_invalid += 1
|
||||||
else:
|
else:
|
||||||
report_warn(f'12. Type "{tv}": unrecognized cfg prefix')
|
report_warn(f'12. Type "{tv}": unrecognized cfg prefix')
|
||||||
type_warn_count += 1
|
type_warn_count += 1
|
||||||
@@ -30,7 +30,7 @@ allowed-tools:
|
|||||||
## Команда
|
## Команда
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
python ".codeassistant/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,136 @@
|
|||||||
|
# help-add v1.3 — 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"
|
||||||
|
|
||||||
|
# --- 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"
|
||||||
|
}
|
||||||
|
|
||||||
|
$formatVersion = Detect-FormatVersion (Resolve-Path $SrcDir).Path
|
||||||
|
|
||||||
|
# --- Проверки ---
|
||||||
|
|
||||||
|
$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="$formatVersion">
|
||||||
|
<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"
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# add-help v1.3 — Add built-in help to 1C object
|
||||||
|
# Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from lxml import etree
|
||||||
|
|
||||||
|
NSMAP = {"md": "http://v8.1c.ru/8.3/MDClasses"}
|
||||||
|
|
||||||
|
|
||||||
|
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):
|
||||||
|
"""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"<?xml version='1.0' encoding='UTF-8'?>", b'<?xml version="1.0" encoding="utf-8"?>')
|
||||||
|
if not xml_bytes.endswith(b"\n"):
|
||||||
|
xml_bytes += b"\n"
|
||||||
|
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 built-in help to 1C object", allow_abbrev=False)
|
||||||
|
parser.add_argument("-ObjectName", required=True)
|
||||||
|
parser.add_argument("-Lang", default="ru")
|
||||||
|
parser.add_argument("-SrcDir", default="src")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
object_name = args.ObjectName
|
||||||
|
lang = args.Lang
|
||||||
|
src_dir = args.SrcDir
|
||||||
|
|
||||||
|
format_version = detect_format_version(os.path.abspath(src_dir))
|
||||||
|
|
||||||
|
# --- Checks ---
|
||||||
|
|
||||||
|
object_dir = os.path.join(src_dir, object_name)
|
||||||
|
ext_dir = os.path.join(object_dir, "Ext")
|
||||||
|
|
||||||
|
if not os.path.isdir(ext_dir):
|
||||||
|
print(f"Каталог объекта не найден: {ext_dir}. Проверьте путь ObjectName (например Catalogs/МойСправочник).", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
help_xml_path = os.path.join(ext_dir, "Help.xml")
|
||||||
|
if os.path.exists(help_xml_path):
|
||||||
|
print(f"Справка уже существует: {help_xml_path}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- 1. Help.xml ---
|
||||||
|
|
||||||
|
help_xml = (
|
||||||
|
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||||||
|
'<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"'
|
||||||
|
f' version="{format_version}">\n'
|
||||||
|
f'\t<Page>{lang}</Page>\n'
|
||||||
|
'</Help>'
|
||||||
|
)
|
||||||
|
|
||||||
|
write_text_with_bom(help_xml_path, help_xml)
|
||||||
|
|
||||||
|
# --- 2. Help/<lang>.html ---
|
||||||
|
|
||||||
|
help_dir = os.path.join(ext_dir, "Help")
|
||||||
|
os.makedirs(help_dir, exist_ok=True)
|
||||||
|
|
||||||
|
help_html_path = os.path.join(help_dir, f"{lang}.html")
|
||||||
|
|
||||||
|
help_html = (
|
||||||
|
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">\n'
|
||||||
|
'<html>\n'
|
||||||
|
'<head>\n'
|
||||||
|
' <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>\n'
|
||||||
|
' <link rel="stylesheet" type="text/css" href="v8help://service_book/service_style"/>\n'
|
||||||
|
'</head>\n'
|
||||||
|
'<body>\n'
|
||||||
|
f' <h1>{object_name}</h1>\n'
|
||||||
|
' <p>Описание.</p>\n'
|
||||||
|
'</body>\n'
|
||||||
|
'</html>'
|
||||||
|
)
|
||||||
|
|
||||||
|
write_text_with_bom(help_html_path, help_html)
|
||||||
|
|
||||||
|
# --- 3. Check IncludeHelpInContents in form metadata ---
|
||||||
|
|
||||||
|
forms_dir = os.path.join(object_dir, "Forms")
|
||||||
|
if os.path.isdir(forms_dir):
|
||||||
|
for entry in os.listdir(forms_dir):
|
||||||
|
if not entry.endswith(".xml"):
|
||||||
|
continue
|
||||||
|
form_meta_full = os.path.join(forms_dir, entry)
|
||||||
|
if not os.path.isfile(form_meta_full):
|
||||||
|
continue
|
||||||
|
|
||||||
|
parser_xml = etree.XMLParser(remove_blank_text=False)
|
||||||
|
form_tree = etree.parse(form_meta_full, parser_xml)
|
||||||
|
form_root = form_tree.getroot()
|
||||||
|
|
||||||
|
include_help = form_root.find(".//md:IncludeHelpInContents", NSMAP)
|
||||||
|
if include_help is not None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Add after <FormType>
|
||||||
|
form_type = form_root.find(".//md:FormType", NSMAP)
|
||||||
|
if form_type is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
parent = form_type.getparent()
|
||||||
|
ns = "http://v8.1c.ru/8.3/MDClasses"
|
||||||
|
new_elem = etree.SubElement(parent, f"{{{ns}}}IncludeHelpInContents")
|
||||||
|
new_elem.text = "false"
|
||||||
|
# Remove SubElement's auto-placement (it appends to end) and insert after FormType
|
||||||
|
parent.remove(new_elem)
|
||||||
|
|
||||||
|
# Find index of FormType in parent
|
||||||
|
form_type_idx = list(parent).index(form_type)
|
||||||
|
|
||||||
|
# Insert after FormType
|
||||||
|
parent.insert(form_type_idx + 1, new_elem)
|
||||||
|
|
||||||
|
# Whitespace handling: copy FormType's tail as new_elem's tail,
|
||||||
|
# and set FormType's tail to include newline + indent
|
||||||
|
new_elem.tail = form_type.tail
|
||||||
|
form_type.tail = "\n\t\t\t"
|
||||||
|
|
||||||
|
save_xml_with_bom(form_tree, form_meta_full)
|
||||||
|
|
||||||
|
print(f" IncludeHelpInContents добавлен: {entry}")
|
||||||
|
|
||||||
|
print(f"[OK] Создана справка: {object_name}")
|
||||||
|
print(f" Метаданные: {help_xml_path}")
|
||||||
|
print(f" Страница: {help_html_path}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user