Release 0.3.2: YAML config, default_baseconfs, autodiscover.
Конфиг утилиты переведён на YAML; default_baseconfs для reindex без -b; автопоиск config.local.yml/.yaml/.json; обобщённая документация. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -8,3 +8,5 @@ __pycache__/
|
|||||||
*.egg-info/
|
*.egg-info/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
config.local.json
|
config.local.json
|
||||||
|
config.local.yml
|
||||||
|
config.local.yaml
|
||||||
|
|||||||
+22
-6
@@ -1,10 +1,24 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
Все значимые изменения **tools/index** (индекс метаданных и модулей 1С) фиксируются в этом файле.
|
Все значимые изменения утилиты **index** (индекс метаданных и модулей 1С) фиксируются в этом файле.
|
||||||
|
|
||||||
Формат: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
Формат: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||||
Версионирование: [Semantic Versioning](https://semver.org/lang/ru/).
|
Версионирование: [Semantic Versioning](https://semver.org/lang/ru/).
|
||||||
|
|
||||||
|
## [0.3.2] - 2026-07-17
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- `--config` в формате **YAML** (`.yml`/`.yaml`) с поддержкой комментариев; пример `config.example.yml`.
|
||||||
|
- Блок **`default_baseconfs`** в конфиге: `reindex` без `-b` индексирует только этот список; без блока — автосканирование `<name>/src/`.
|
||||||
|
- **Автопоиск** локального конфига без `--config`: `config.local.yml` / `config.local.yaml` / `config.local.json`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Документация и тексты `--help`: обобщённые примеры вместо локальных имён выгрузок и проектов.
|
||||||
|
- Алиасы `--baseconf` — через `baseconf_aliases` в YAML-конфиге (не в коде).
|
||||||
|
- Список конфигураций для `reindex` без `-b`: автообнаружение или `default_baseconfs` из конфига.
|
||||||
|
|
||||||
## [0.3.1] - 2026-07-17
|
## [0.3.1] - 2026-07-17
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
@@ -15,7 +29,7 @@
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- `query_1c.py`: `-b` / `--baseconf` до подкоманды (`query_1c.py -b crm3-26 search …`) корректно применяется к запросу.
|
- `query_1c.py`: `-b` / `--baseconf` до подкоманды (`query_1c.py -b my-config search …`) корректно применяется к запросу.
|
||||||
|
|
||||||
## [0.3.0] - 2026-07-16
|
## [0.3.0] - 2026-07-16
|
||||||
|
|
||||||
@@ -48,7 +62,7 @@
|
|||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- Параметр конфигурации 1С: **`--baseconf` / `-b`** (алиасы `target`→`crm3-26`, `source`→`crm3-dev`).
|
- Параметр конфигурации 1С: **`--baseconf` / `-b`**; алиасы через `baseconf_aliases` в `--config`.
|
||||||
- **`--config` / `-c`** — только файл настроек утилиты (JSON), не выгрузка 1С.
|
- **`--config` / `-c`** — только файл настроек утилиты (JSON), не выгрузка 1С.
|
||||||
- Информативные ошибки: нет индекса / нет папки `src/` / baseconf не проиндексирован / объект не найден (с подсказками).
|
- Информативные ошибки: нет индекса / нет папки `src/` / baseconf не проиндексирован / объект не найден (с подсказками).
|
||||||
- Расширена документация `README.md` (примеры, режимы, применение в Cursor).
|
- Расширена документация `README.md` (примеры, режимы, применение в Cursor).
|
||||||
@@ -67,6 +81,8 @@
|
|||||||
- `query_1c.py`: `search`, `show`, `refs`, `modules`, `module`.
|
- `query_1c.py`: `search`, `show`, `refs`, `modules`, `module`.
|
||||||
- Инкремент по `mtime`+`size` файлов; индекс модулей `**/*.bsl`.
|
- Инкремент по `mtime`+`size` файлов; индекс модулей `**/*.bsl`.
|
||||||
|
|
||||||
[0.3.0]: https://git.p7net.ru/1c/index/-/tags/v0.3.0
|
[0.3.2]: v0.3.2
|
||||||
[0.2.0]: https://git.p7net.ru/1c/index/-/tags/v0.2.0
|
[0.3.1]: v0.3.1
|
||||||
[0.1.0]: https://git.p7net.ru/1c/index/-/tags/v0.1.0
|
[0.3.0]: v0.3.0
|
||||||
|
[0.2.0]: v0.2.0
|
||||||
|
[0.1.0]: v0.1.0
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Индекс метаданных и модулей конфигураций 1С
|
# Индекс метаданных и модулей конфигураций 1С
|
||||||
|
|
||||||
**Версия:** см. [`VERSION`](VERSION) (текущая: **0.3.1**) · [CHANGELOG](CHANGELOG.md)
|
**Версия:** см. [`VERSION`](VERSION) (текущая: **0.3.2**) · [CHANGELOG](CHANGELOG.md)
|
||||||
**Автор:** Michael BAG · [mk@p7net.ru](mailto:mk@p7net.ru)
|
**Автор:** Michael BAG · [mk@p7net.ru](mailto:mk@p7net.ru)
|
||||||
**Лицензия:** [GNU GPL v3](LICENSE) · [русский перевод (справочно)](LICENSE.ru)
|
**Лицензия:** [GNU GPL v3](LICENSE) · [русский перевод (справочно)](LICENSE.ru)
|
||||||
|
|
||||||
@@ -11,19 +11,16 @@
|
|||||||
| [`index_1c.py`](index_1c.py) | построение и обновление индекса |
|
| [`index_1c.py`](index_1c.py) | построение и обновление индекса |
|
||||||
| [`query_1c.py`](query_1c.py) | поиск и просмотр по готовому индексу |
|
| [`query_1c.py`](query_1c.py) | поиск и просмотр по готовому индексу |
|
||||||
|
|
||||||
Репозиторий утилиты: <https://git.p7net.ru/1c/index.git>
|
|
||||||
Правило для Cursor (в корне CRM3-26): `.cursor/rules/1c-meta-index.mdc`
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python tools/index/index_1c.py --version
|
python index_1c.py --version
|
||||||
python tools/index/query_1c.py --version
|
python query_1c.py --version
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Зачем это нужно
|
## Зачем это нужно
|
||||||
|
|
||||||
Обход десятков тысяч XML/BSL в `crm3-26/src` и соседних выгрузках через Grep в Cursor медленный. Индекс один раз разбирает метаданные и модули и даёт:
|
Обход десятков тысяч XML/BSL в `<выгрузка>/src` через Grep в IDE медленный. Индекс один раз разбирает метаданные и модули и даёт:
|
||||||
|
|
||||||
| Задача | Команда |
|
| Задача | Команда |
|
||||||
|--------|---------|
|
|--------|---------|
|
||||||
@@ -32,9 +29,9 @@ python tools/index/query_1c.py --version
|
|||||||
| Кто ссылается на справочник/документ | `query_1c.py refs` |
|
| Кто ссылается на справочник/документ | `query_1c.py refs` |
|
||||||
| Документ ↔ регистры движений | `query_1c.py movements` |
|
| Документ ↔ регистры движений | `query_1c.py movements` |
|
||||||
| Найти процедуру/фрагмент в BSL | `query_1c.py modules` |
|
| Найти процедуру/фрагмент в BSL | `query_1c.py modules` |
|
||||||
| Сравнить целевую и исходную конфигурацию | `-b target` / `-b source` |
|
| Сравнить несколько выгрузок в одном репозитории | `-b cfg1 -b cfg2` |
|
||||||
|
|
||||||
**Типичный workflow агента:**
|
**Типичный workflow:**
|
||||||
`reindex` (после выгрузки) → `object` / `search` → `refs` / `modules` → открыть конкретный `.xml` / `.bsl`.
|
`reindex` (после выгрузки) → `object` / `search` → `refs` / `modules` → открыть конкретный `.xml` / `.bsl`.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -43,22 +40,33 @@ python tools/index/query_1c.py --version
|
|||||||
|
|
||||||
| Параметр | Короткий | Назначение |
|
| Параметр | Короткий | Назначение |
|
||||||
|----------|----------|------------|
|
|----------|----------|------------|
|
||||||
| `--config` | `-c` | Файл **настроек утилиты** (JSON). **Не** конфигурация 1С. См. [`config.example.json`](config.example.json). |
|
| `--config` | `-c` | Файл **настроек утилиты** (YAML). **Не** конфигурация 1С. См. [`config.example.yml`](config.example.yml). |
|
||||||
| `--root` | `-r` | Корень проекта CRM3-26 (если запуск не из дерева проекта). |
|
| `--root` | `-r` | Корень проекта с выгрузками 1С (если запуск не из дерева проекта). |
|
||||||
| `--baseconf` | `-b` | Выгрузка конфигурации 1С: папка `<name>/src/` в репозитории. Можно несколько раз. |
|
| `--baseconf` | `-b` | Выгрузка конфигурации 1С: папка `<name>/src/` в репозитории. Можно несколько раз. |
|
||||||
| `--version` | | Версия утилиты. |
|
| `--version` | | Версия утилиты. |
|
||||||
|
|
||||||
Приоритет корня проекта: `--root` > `project_root` в `--config` > авто из расположения `tools/index/`.
|
Приоритет корня проекта: `--root` > `project_root` в `--config` > авто (каталог с `index_1c.py` и `VERSION`).
|
||||||
|
Если `--config` не указан, утилита пытается автоматически найти
|
||||||
|
`config.local.yml`, `config.local.yaml` или `config.local.json`.
|
||||||
|
|
||||||
### Алиасы `--baseconf`
|
### Алиасы `--baseconf`
|
||||||
|
|
||||||
| Алиас | Папка |
|
Краткие имена задаются в файле `--config`, поле **`baseconf_aliases`**:
|
||||||
|-------|-------|
|
|
||||||
| `target`, `crm3_26` | `crm3-26` |
|
|
||||||
| `source`, `crm3_old`, `crm3-old`, `crm3_dev` | `crm3-dev` |
|
|
||||||
|
|
||||||
Другие выгрузки без алиаса: `crm3-26.rhana`, `crm3-dev.rhana`, `ws-rhana`, `bu-corp`, …
|
```yaml
|
||||||
Полный список: `python tools/index/index_1c.py list`
|
project_root: "/path/to/project"
|
||||||
|
baseconf_aliases:
|
||||||
|
main: "my-config"
|
||||||
|
ext: "my-config.ext"
|
||||||
|
```
|
||||||
|
|
||||||
|
После этого `-b main` эквивалентно `-b my-config`.
|
||||||
|
|
||||||
|
Если в YAML задан блок `default_baseconfs`, то `reindex` без `-b` использует этот список.
|
||||||
|
Если блока нет — `reindex` без `-b` индексирует **все** каталоги с `src/` в корне проекта.
|
||||||
|
`query_1c.py` без `-b` ищет по **всем** конфигурациям в индексе.
|
||||||
|
|
||||||
|
Список выгрузок: `python index_1c.py list`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -78,9 +86,9 @@ python tools/index/query_1c.py --version
|
|||||||
|-------|-----------|
|
|-------|-----------|
|
||||||
| `reindex -j 12` | инкремент: только файлы с изменившимися `mtime`/`size` |
|
| `reindex -j 12` | инкремент: только файлы с изменившимися `mtime`/`size` |
|
||||||
| `reindex --full -j 12` | удалить всю БД и собрать заново все известные выгрузки |
|
| `reindex --full -j 12` | удалить всю БД и собрать заново все известные выгрузки |
|
||||||
| `reindex --full -b crm3-26` | пересобрать только указанную конфигурацию |
|
| `reindex --full -b my-config` | пересобрать только указанную конфигурацию |
|
||||||
| `reindex -b target -t Documents,Catalogs` | только выбранные типы объектов |
|
| `reindex -b main -t Documents,Catalogs` | только выбранные типы объектов |
|
||||||
| `reindex -b ws-rhana --no-modules` | метаданные без BSL |
|
| `reindex -b my-config --no-modules` | метаданные без BSL |
|
||||||
| `reindex --md` | дополнительно Markdown в `cache/1c_meta/md/<baseconf>/` |
|
| `reindex --md` | дополнительно Markdown в `cache/1c_meta/md/<baseconf>/` |
|
||||||
|
|
||||||
`-j` / `--workers` — число потоков (по умолчанию 4–16).
|
`-j` / `--workers` — число потоков (по умолчанию 4–16).
|
||||||
@@ -96,17 +104,17 @@ python tools/index/query_1c.py --version
|
|||||||
### Примеры переиндексации
|
### Примеры переиндексации
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# после обновления выгрузки целевой конфигурации
|
# после обновления одной выгрузки
|
||||||
python tools/index/index_1c.py reindex -b target -j 12
|
python index_1c.py reindex -b my-config -j 12
|
||||||
|
|
||||||
# полная пересборка всего проекта
|
# полная пересборка всего проекта
|
||||||
python tools/index/index_1c.py reindex --full -j 12
|
python index_1c.py reindex --full -j 12
|
||||||
|
|
||||||
# только документы и справочники исходной + расширения
|
# основная конфигурация + расширение, только документы и справочники
|
||||||
python tools/index/index_1c.py reindex -b source -b crm3-dev.rhana -t Documents,Catalogs -j 8
|
python index_1c.py reindex -b main -b ext -t Documents,Catalogs -j 8
|
||||||
|
|
||||||
python tools/index/index_1c.py status
|
python index_1c.py status
|
||||||
python tools/index/index_1c.py list
|
python index_1c.py list
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -122,7 +130,7 @@ python tools/index/index_1c.py list
|
|||||||
| `search` | строка | объекты метаданных (FTS) | `-b`, `--type`, `--limit` |
|
| `search` | строка | объекты метаданных (FTS) | `-b`, `--type`, `--limit` |
|
||||||
| `object` | имя/синоним объекта **или** реквизита | дерево структуры | `-b`, `--type`, `--clear`, `--limit` |
|
| `object` | имя/синоним объекта **или** реквизита | дерево структуры | `-b`, `--type`, `--clear`, `--limit` |
|
||||||
| `show` | имя объекта | полная карточка JSON | `-b` |
|
| `show` | имя объекта | полная карточка JSON | `-b` |
|
||||||
| `refs` | `Catalog.Партнеры` / `ЗаказКлиента` | обратные ссылки полей | `-b`, `--limit` (на каждую baseconf) |
|
| `refs` | `Catalog.Customers` / `Contract` | обратные ссылки полей | `-b`, `--limit` (на каждую baseconf) |
|
||||||
| `movements` | документ или регистр | регистратор ↔ регистры движений | `-b`, `--type`, `--limit` |
|
| `movements` | документ или регистр | регистратор ↔ регистры движений | `-b`, `--type`, `--limit` |
|
||||||
| `modules` | строка | поиск по BSL | `-b`, `-n` / `--names-only`, `--limit` |
|
| `modules` | строка | поиск по BSL | `-b`, `-n` / `--names-only`, `--limit` |
|
||||||
| `module` | путь или owner | символы модуля, строки | `-b` |
|
| `module` | путь или owner | символы модуля, строки | `-b` |
|
||||||
@@ -131,22 +139,22 @@ python tools/index/index_1c.py list
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
# полная структура документа
|
# полная структура документа
|
||||||
python tools/index/query_1c.py object ЗаказКлиента -b target
|
python query_1c.py object Contract -b my-config
|
||||||
|
|
||||||
# только реквизиты с именем/синонимом «Партнер» в документах
|
# только реквизиты с именем/синонимом «Partner» в документах
|
||||||
python tools/index/query_1c.py object Партнер -b target --type Document --clear
|
python query_1c.py object Partner -b my-config --type Document --clear
|
||||||
|
|
||||||
# совпал сам объект → --clear печатает только заголовок
|
# совпал сам объект → --clear печатает только заголовок
|
||||||
python tools/index/query_1c.py object ЗаказКлиента -b target --clear
|
python query_1c.py object Contract -b my-config --clear
|
||||||
```
|
```
|
||||||
|
|
||||||
Формат строки реквизита:
|
Формат строки реквизита:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
├── `Attribute.Партнер` — Клиент [обяз.] : CatalogRef.Партнеры
|
├── `Attribute.Partner` — Клиент [обяз.] : CatalogRef.Customers
|
||||||
├── `Attribute.СуммаДокумента` — … [необяз.] : DefinedType.ДенежнаяСуммаЛюбогоЗнака
|
├── `Attribute.Amount` — … [необяз.] : DefinedType.MoneyAmount
|
||||||
├── `TabularSection.Товары` — Товары
|
├── `TabularSection.Lines` — Строки
|
||||||
│ └── `Column.Номенклатура` — … [обяз.] : CatalogRef.Номенклатура
|
│ └── `Column.Item` — … [обяз.] : CatalogRef.Items
|
||||||
```
|
```
|
||||||
|
|
||||||
- **[обяз.]** — `FillChecking=ShowError`; **[необяз.]** — `DontCheck`
|
- **[обяз.]** — `FillChecking=ShowError`; **[необяз.]** — `DontCheck`
|
||||||
@@ -156,24 +164,24 @@ python tools/index/query_1c.py object ЗаказКлиента -b target --clear
|
|||||||
### `refs` — кто ссылается
|
### `refs` — кто ссылается
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python tools/index/query_1c.py refs "ЗаказКлиента"
|
python query_1c.py refs "Contract"
|
||||||
python tools/index/query_1c.py refs Catalog.Партнеры -b target --limit 50
|
python query_1c.py refs Catalog.Customers -b my-config --limit 50
|
||||||
python tools/index/query_1c.py refs Document.ЗаказКлиента -b source
|
python query_1c.py refs Document.Contract -b main
|
||||||
```
|
```
|
||||||
|
|
||||||
Без `-b` — все конфигурации в индексе; `--limit` действует **на каждую**.
|
Без `-b` — все конфигурации в индексе; `--limit` действует **на каждую**.
|
||||||
Составной тип поля: `→ DocumentRef.ЗаказКлиента (среди прочего: DocumentRef.…)`.
|
Составной тип поля: `→ DocumentRef.Contract (среди прочего: DocumentRef.…)`.
|
||||||
|
|
||||||
### `movements` — регистратор ↔ регистры движений
|
### `movements` — регистратор ↔ регистры движений
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# документ → регистры, в которых он регистратор
|
# документ → регистры, в которых он регистратор
|
||||||
python tools/index/query_1c.py movements ЗаказКлиента -b target
|
python query_1c.py movements Contract -b my-config
|
||||||
python tools/index/query_1c.py movements Document.РеализацияТоваровУслуг -b target
|
python query_1c.py movements Document.Sales -b my-config
|
||||||
|
|
||||||
# регистр → документы-регистраторы
|
# регистр → документы-регистраторы
|
||||||
python tools/index/query_1c.py movements AccumulationRegister.ТоварыНаСкладах -b target
|
python query_1c.py movements AccumulationRegister.Stock -b my-config
|
||||||
python tools/index/query_1c.py movements ТоварыНаСкладах -b target --type AccumulationRegister
|
python query_1c.py movements Stock -b my-config --type AccumulationRegister
|
||||||
```
|
```
|
||||||
|
|
||||||
Данные из свойства метаданных `RegisterRecords` (таблица `register_records` в индексе).
|
Данные из свойства метаданных `RegisterRecords` (таблица `register_records` в индексе).
|
||||||
@@ -182,18 +190,18 @@ python tools/index/query_1c.py movements ТоварыНаСкладах -b targe
|
|||||||
### `modules` / `module`
|
### `modules` / `module`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python tools/index/query_1c.py modules "ОбработатьHealth" -b ws-rhana
|
python query_1c.py modules "ProcessData" -b my-config
|
||||||
python tools/index/query_1c.py modules "РВС_Transfer" -b ws-rhana -n
|
python query_1c.py modules "MyModule" -b my-config.ext -n
|
||||||
python tools/index/query_1c.py module CommonModules/РВС_TransferAPIДокументы -b ws-rhana
|
python query_1c.py module CommonModules/MyModule -b my-config
|
||||||
```
|
```
|
||||||
|
|
||||||
### Прочие примеры
|
### Прочие примеры
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python tools/index/query_1c.py search "ЗаказКлиента"
|
python query_1c.py search "Contract"
|
||||||
python tools/index/query_1c.py search "Партнер" --type Document -b crm3-26
|
python query_1c.py search "Partner" --type Document -b my-config
|
||||||
python tools/index/query_1c.py show Document.ЗаказКлиента -b target
|
python query_1c.py show Document.Contract -b main
|
||||||
python tools/index/query_1c.py search "Партнер" -b source -b crm3-dev.rhana
|
python query_1c.py search "Partner" -b main -b ext
|
||||||
```
|
```
|
||||||
|
|
||||||
### Ошибки и подсказки
|
### Ошибки и подсказки
|
||||||
@@ -201,7 +209,7 @@ python tools/index/query_1c.py search "Партнер" -b source -b crm3-dev.rha
|
|||||||
| Ситуация | Поведение |
|
| Ситуация | Поведение |
|
||||||
|----------|-----------|
|
|----------|-----------|
|
||||||
| Нет `index.sqlite` | подсказка `index_1c.py reindex --full` |
|
| Нет `index.sqlite` | подсказка `index_1c.py reindex --full` |
|
||||||
| `-b` без папки `src/` | список доступных выгрузок + алиасы |
|
| `-b` без папки `src/` | список доступных выгрузок |
|
||||||
| `-b` есть в репо, нет в индексе | список проиндексированных + команда `reindex -b …` |
|
| `-b` есть в репо, нет в индексе | список проиндексированных + команда `reindex -b …` |
|
||||||
| `show` / `object` не нашли | похожие имена из индекса |
|
| `show` / `object` не нашли | похожие имена из индекса |
|
||||||
|
|
||||||
@@ -210,29 +218,29 @@ python tools/index/query_1c.py search "Партнер" -b source -b crm3-dev.rha
|
|||||||
## Файл настроек утилиты (`--config`)
|
## Файл настроек утилиты (`--config`)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cp tools/index/config.example.json tools/index/config.local.json
|
cp config.example.yml config.local.yml
|
||||||
# project_root: "/path/to/crm3-26"
|
# project_root: "/path/to/project"
|
||||||
python tools/index/query_1c.py --config tools/index/config.local.json search "Заказ"
|
python query_1c.py --config config.local.yml search "Contract"
|
||||||
```
|
```
|
||||||
|
|
||||||
`config.local.json` в `.gitignore` (локальные пути).
|
`config.local.yml` в `.gitignore` (локальные пути и алиасы).
|
||||||
|
Legacy-вариант `config.local.json` тоже поддерживается и подхватывается авто-поиском.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Применение в Cursor
|
## Применение в Cursor / IDE
|
||||||
|
|
||||||
1. После выгрузки из EDT/конфигуратора: `python tools/index/index_1c.py reindex -j 12` (или `-b target`).
|
1. После выгрузки из EDT/конфигуратора: `python index_1c.py reindex -j 12` (или `-b my-config`).
|
||||||
2. Метаданные и связи — через `query_1c.py`, не Grep по всему `src/`.
|
2. Метаданные и связи — через `query_1c.py`, не Grep по всему `src/`.
|
||||||
3. Разделять контекст: `-b target` vs `-b source`.
|
3. При нескольких выгрузках — ограничивать `-b` нужной baseconf.
|
||||||
4. Код: `modules` → открыть `rel_path`; структура документа: `object`.
|
4. Код: `modules` → открыть `rel_path`; структура документа: `object`.
|
||||||
5. Правило агента: `.cursor/rules/1c-meta-index.mdc`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Артефакты кэша
|
## Артефакты кэша
|
||||||
|
|
||||||
```text
|
```text
|
||||||
cache/1c_meta/ # в корне проекта CRM3-26 (gitignore)
|
cache/1c_meta/ # в корне проекта (обычно в .gitignore)
|
||||||
index.sqlite # единая БД
|
index.sqlite # единая БД
|
||||||
INDEX.md
|
INDEX.md
|
||||||
manifest.json
|
manifest.json
|
||||||
@@ -251,8 +259,6 @@ Per-config `search.sqlite` устарели и не используются.
|
|||||||
| **E-mail** | [mk@p7net.ru](mailto:mk@p7net.ru) |
|
| **E-mail** | [mk@p7net.ru](mailto:mk@p7net.ru) |
|
||||||
| **Предложения, вопросы, ошибки** | пишите на **mk@p7net.ru** |
|
| **Предложения, вопросы, ошибки** | пишите на **mk@p7net.ru** |
|
||||||
|
|
||||||
Репозиторий: <https://git.p7net.ru/1c/index.git>
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Лицензирование
|
## Лицензирование
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
"project_root": "/path/to/crm3-26",
|
|
||||||
"comment": "Файл настроек утилиты tools/index (НЕ конфигурация 1С). Копируйте в config.local.json и укажите --config config.local.json"
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Пример локальной конфигурации tools/index.
|
||||||
|
# Скопируйте в config.local.yml и передавайте:
|
||||||
|
# python index_1c.py --config config.local.yml reindex
|
||||||
|
# python query_1c.py --config config.local.yml search "..."
|
||||||
|
#
|
||||||
|
# ВАЖНО:
|
||||||
|
# - Это файл настроек утилиты, НЕ конфигурация 1С.
|
||||||
|
# - Файл обычно не коммитят (локальные пути/алиасы).
|
||||||
|
|
||||||
|
# Корень проекта, в котором лежат выгрузки (<name>/src/).
|
||||||
|
project_root: "/path/to/project"
|
||||||
|
|
||||||
|
# Короткие алиасы для --baseconf.
|
||||||
|
# Пример: -b main эквивалентно -b my-config
|
||||||
|
baseconf_aliases:
|
||||||
|
main: "my-config"
|
||||||
|
ext: "my-config.ext"
|
||||||
|
|
||||||
|
# Необязательный whitelist baseconf для reindex без -b.
|
||||||
|
# Если блок задан, то reindex (без -b) возьмет ТОЛЬКО эти конфигурации.
|
||||||
|
# Если блока нет — работает автосканирование всех <name>/src/ в project_root.
|
||||||
|
default_baseconfs:
|
||||||
|
- main
|
||||||
|
- ext
|
||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
__version__ = "0.3.1"
|
__version__ = "0.3.2"
|
||||||
__status__ = "in development"
|
__status__ = "in development"
|
||||||
__author__ = "Michael BAG"
|
__author__ = "Michael BAG"
|
||||||
__email__ = "mk@p7net.ru"
|
__email__ = "mk@p7net.ru"
|
||||||
|
|||||||
+83
-14
@@ -3,7 +3,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
@@ -21,25 +20,89 @@ class BaseconfError(Exception):
|
|||||||
|
|
||||||
|
|
||||||
def load_tool_config(path: Path) -> dict[str, Any]:
|
def load_tool_config(path: Path) -> dict[str, Any]:
|
||||||
"""Файл настроек утилиты index (JSON). Не путать с конфигурацией 1С."""
|
"""Файл настроек утилиты index (YAML; legacy JSON поддерживается)."""
|
||||||
|
ext = path.suffix.lower()
|
||||||
try:
|
try:
|
||||||
data = json.loads(path.read_text(encoding="utf-8"))
|
raw = path.read_text(encoding="utf-8")
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
raise BaseconfError(f"Не удалось прочитать --config {path}: {e}", exit_code=1) from e
|
raise BaseconfError(f"Не удалось прочитать --config {path}: {e}", exit_code=1) from e
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
|
if ext == ".json":
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
|
||||||
|
data = json.loads(raw)
|
||||||
|
except Exception as e:
|
||||||
raise BaseconfError(f"Некорректный JSON в --config {path}: {e}", exit_code=1) from e
|
raise BaseconfError(f"Некорректный JSON в --config {path}: {e}", exit_code=1) from e
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
raise BaseconfError(f"--config {path}: ожидается JSON-объект", exit_code=1)
|
raise BaseconfError(f"--config {path}: ожидается JSON-объект", exit_code=1)
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
try:
|
||||||
|
import yaml # type: ignore
|
||||||
|
except Exception as e:
|
||||||
|
raise BaseconfError(
|
||||||
|
"Для чтения --config в формате YAML нужен пакет pyyaml: pip install pyyaml",
|
||||||
|
exit_code=1,
|
||||||
|
) from e
|
||||||
|
try:
|
||||||
|
data = yaml.safe_load(raw)
|
||||||
|
except Exception as e:
|
||||||
|
raise BaseconfError(f"Некорректный YAML в --config {path}: {e}", exit_code=1) from e
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise BaseconfError(f"--config {path}: ожидается YAML-объект", exit_code=1)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def discover_local_tool_config() -> Path | None:
|
||||||
|
"""Автопоиск локального конфига без --config."""
|
||||||
|
candidates = ("config.local.yml", "config.local.yaml", "config.local.json")
|
||||||
|
roots = [Path.cwd(), project_root_from_here()]
|
||||||
|
seen: set[Path] = set()
|
||||||
|
for root in roots:
|
||||||
|
for rel in (Path("tools/index"), Path(".")):
|
||||||
|
base = (root / rel).resolve()
|
||||||
|
if base in seen or not base.is_dir():
|
||||||
|
continue
|
||||||
|
seen.add(base)
|
||||||
|
for name in candidates:
|
||||||
|
p = base / name
|
||||||
|
if p.is_file():
|
||||||
|
return p
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def apply_tool_config(data: dict[str, Any]) -> None:
|
||||||
|
"""Применить настройки из YAML (--config): алиасы и дефолтные baseconf."""
|
||||||
|
from .config import set_config_aliases, set_default_baseconfs
|
||||||
|
|
||||||
|
aliases = data.get("baseconf_aliases")
|
||||||
|
if aliases is not None:
|
||||||
|
if not isinstance(aliases, dict):
|
||||||
|
raise BaseconfError("--config: baseconf_aliases должен быть объектом YAML")
|
||||||
|
set_config_aliases({str(k): str(v) for k, v in aliases.items()})
|
||||||
|
default_baseconfs = data.get("default_baseconfs")
|
||||||
|
if default_baseconfs is not None:
|
||||||
|
if not isinstance(default_baseconfs, list):
|
||||||
|
raise BaseconfError("--config: default_baseconfs должен быть YAML-списком")
|
||||||
|
set_default_baseconfs([str(x) for x in default_baseconfs])
|
||||||
|
else:
|
||||||
|
set_default_baseconfs([])
|
||||||
|
|
||||||
|
|
||||||
def resolve_project_root(args: argparse.Namespace) -> Path:
|
def resolve_project_root(args: argparse.Namespace) -> Path:
|
||||||
"""Корень проекта: --root → project_root из --config → авто."""
|
"""Корень проекта: --root → --config/auto-config → авто."""
|
||||||
if getattr(args, "root", None):
|
if getattr(args, "root", None):
|
||||||
return Path(args.root).resolve()
|
return Path(args.root).resolve()
|
||||||
cfg_path = getattr(args, "config", None)
|
cfg_path = getattr(args, "config", None)
|
||||||
|
if not cfg_path:
|
||||||
|
auto = discover_local_tool_config()
|
||||||
|
if auto is not None:
|
||||||
|
cfg_path = str(auto)
|
||||||
|
setattr(args, "config", cfg_path)
|
||||||
if cfg_path:
|
if cfg_path:
|
||||||
data = load_tool_config(Path(cfg_path))
|
data = load_tool_config(Path(cfg_path))
|
||||||
|
apply_tool_config(data)
|
||||||
pr = data.get("project_root")
|
pr = data.get("project_root")
|
||||||
if pr:
|
if pr:
|
||||||
return Path(pr).resolve()
|
return Path(pr).resolve()
|
||||||
@@ -52,13 +115,16 @@ def add_tool_args(parser: argparse.ArgumentParser) -> None:
|
|||||||
"--config",
|
"--config",
|
||||||
"-c",
|
"-c",
|
||||||
metavar="FILE",
|
metavar="FILE",
|
||||||
help="JSON с настройками утилиты (project_root и др.), см. config.example.json",
|
help=(
|
||||||
|
"YAML с настройками утилиты (project_root и др.), см. config.example.yml. "
|
||||||
|
"Без параметра: автопоиск config.local.yml/.yaml/.json"
|
||||||
|
),
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--root",
|
"--root",
|
||||||
"-r",
|
"-r",
|
||||||
metavar="DIR",
|
metavar="DIR",
|
||||||
help="Корень проекта CRM3-26 (перекрывает project_root из --config)",
|
help="Корень проекта с выгрузками 1С (перекрывает project_root из --config)",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -69,7 +135,10 @@ def add_baseconf_args(
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Фильтр по выгрузке конфигурации 1С в репозитории."""
|
"""Фильтр по выгрузке конфигурации 1С в репозитории."""
|
||||||
if mode == "index":
|
if mode == "index":
|
||||||
default_hint = "Без параметра — индексировать все выгрузки с src/ в репозитории."
|
default_hint = (
|
||||||
|
"Без параметра — default_baseconfs из --config; "
|
||||||
|
"если блок не задан, индексировать все выгрузки с src/."
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
default_hint = "Без параметра — поиск по всем проиндексированным."
|
default_hint = "Без параметра — поиск по всем проиндексированным."
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
@@ -80,8 +149,8 @@ def add_baseconf_args(
|
|||||||
dest="baseconf",
|
dest="baseconf",
|
||||||
help=(
|
help=(
|
||||||
"Конфигурация 1С в репозитории (папка <name>/src/). "
|
"Конфигурация 1С в репозитории (папка <name>/src/). "
|
||||||
"Можно несколько раз или через запятую: -b target,source. "
|
"Можно несколько раз или через запятую: -b cfg1,cfg2. "
|
||||||
"Алиасы: target→crm3-26, source→crm3-dev. "
|
"Краткие имена (алиасы) — в baseconf_aliases файла --config. "
|
||||||
f"{default_hint}"
|
f"{default_hint}"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -192,7 +261,7 @@ def validate_baseconfs(
|
|||||||
lines.extend(
|
lines.extend(
|
||||||
[
|
[
|
||||||
"",
|
"",
|
||||||
"Алиасы: target→crm3-26, source→crm3-dev, crm3_old→crm3-dev",
|
"Краткие имена (алиасы) для -b задаются в baseconf_aliases файла --config.",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
raise BaseconfError("\n".join(lines))
|
raise BaseconfError("\n".join(lines))
|
||||||
@@ -216,7 +285,7 @@ def validate_baseconfs(
|
|||||||
lines.extend(
|
lines.extend(
|
||||||
[
|
[
|
||||||
"",
|
"",
|
||||||
f"Переиндексация: python tools/index/index_1c.py reindex --full -b {not_indexed[0]}",
|
f"Переиндексация: python index_1c.py reindex --full -b {not_indexed[0]}",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
raise BaseconfError("\n".join(lines))
|
raise BaseconfError("\n".join(lines))
|
||||||
@@ -297,7 +366,7 @@ def index_db_missing_message(project_root: Path) -> str:
|
|||||||
return (
|
return (
|
||||||
f"Индекс не найден: {path}\n"
|
f"Индекс не найден: {path}\n"
|
||||||
"Сначала выполните:\n"
|
"Сначала выполните:\n"
|
||||||
" python tools/index/index_1c.py reindex --full -j 12\n"
|
" python index_1c.py reindex --full -j 12\n"
|
||||||
"или для одной конфигурации:\n"
|
"или для одной конфигурации:\n"
|
||||||
" python tools/index/index_1c.py reindex --full -b crm3-26"
|
" python index_1c.py reindex --full -b <имя-выгрузки>"
|
||||||
)
|
)
|
||||||
|
|||||||
+47
-26
@@ -5,28 +5,10 @@ from __future__ import annotations
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
# Папки выгрузок относительно корня проекта (есть src/).
|
# Алиасы имён конфигураций 1С для CLI (--baseconf / -b), задаются через --config
|
||||||
DEFAULT_CONFIGS: tuple[str, ...] = (
|
# (поле baseconf_aliases в YAML). См. config.example.yml.
|
||||||
"crm3-26",
|
_RUNTIME_ALIASES: dict[str, str] = {}
|
||||||
"crm3-26.rhana",
|
_RUNTIME_DEFAULT_BASECONFS: list[str] = []
|
||||||
"crm3-dev",
|
|
||||||
"crm3-dev.rhana",
|
|
||||||
"crm3-dev.docs",
|
|
||||||
"ws-rhana",
|
|
||||||
"bu-corp",
|
|
||||||
"bu-corp.rhana",
|
|
||||||
"diadoc.ext.rhana",
|
|
||||||
)
|
|
||||||
|
|
||||||
# Алиасы имён конфигураций 1С для CLI (--baseconf / -b).
|
|
||||||
CONFIG_ALIASES: dict[str, str] = {
|
|
||||||
"crm3_26": "crm3-26",
|
|
||||||
"crm3_old": "crm3-dev",
|
|
||||||
"crm3-old": "crm3-dev",
|
|
||||||
"crm3_dev": "crm3-dev",
|
|
||||||
"target": "crm3-26",
|
|
||||||
"source": "crm3-dev",
|
|
||||||
}
|
|
||||||
|
|
||||||
# Папка EDT → канонический тип (английский идентификатор выгрузки).
|
# Папка EDT → канонический тип (английский идентификатор выгрузки).
|
||||||
OBJECT_TYPE_FOLDERS: dict[str, str] = {
|
OBJECT_TYPE_FOLDERS: dict[str, str] = {
|
||||||
@@ -192,13 +174,52 @@ class ConfigPaths:
|
|||||||
|
|
||||||
|
|
||||||
def project_root_from_here() -> Path:
|
def project_root_from_here() -> Path:
|
||||||
"""tools/index/index1c → корень проекта."""
|
"""Корень проекта: каталог с index_1c.py и VERSION."""
|
||||||
return Path(__file__).resolve().parents[3]
|
here = Path(__file__).resolve().parent
|
||||||
|
for candidate in (here.parent, here.parent.parent, here.parent.parent.parent):
|
||||||
|
if (candidate / "index_1c.py").is_file() and (candidate / "VERSION").is_file():
|
||||||
|
return candidate
|
||||||
|
return here.parent
|
||||||
|
|
||||||
|
|
||||||
|
def set_config_aliases(aliases: dict[str, str] | None) -> None:
|
||||||
|
"""Задать алиасы baseconf из файла --config (baseconf_aliases)."""
|
||||||
|
global _RUNTIME_ALIASES
|
||||||
|
_RUNTIME_ALIASES = {str(k): str(v) for k, v in (aliases or {}).items()}
|
||||||
|
|
||||||
|
|
||||||
|
def get_config_aliases() -> dict[str, str]:
|
||||||
|
return dict(_RUNTIME_ALIASES)
|
||||||
|
|
||||||
|
|
||||||
|
def set_default_baseconfs(names: list[str] | None) -> None:
|
||||||
|
"""Задать default_baseconfs из файла --config (YAML)."""
|
||||||
|
global _RUNTIME_DEFAULT_BASECONFS
|
||||||
|
_RUNTIME_DEFAULT_BASECONFS = [str(x) for x in (names or []) if str(x).strip()]
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_baseconfs() -> list[str]:
|
||||||
|
"""Список baseconf по умолчанию для reindex без -b."""
|
||||||
|
return list(_RUNTIME_DEFAULT_BASECONFS)
|
||||||
|
|
||||||
|
|
||||||
def resolve_config_name(name: str) -> str:
|
def resolve_config_name(name: str) -> str:
|
||||||
key = name.strip()
|
key = name.strip()
|
||||||
return CONFIG_ALIASES.get(key, CONFIG_ALIASES.get(key.lower(), key))
|
aliases = get_config_aliases()
|
||||||
|
return aliases.get(key, aliases.get(key.lower(), key))
|
||||||
|
|
||||||
|
|
||||||
|
def list_config_dirs(project_root: Path) -> list[str]:
|
||||||
|
"""Все каталоги с выгрузкой 1С (<name>/src/) в корне проекта."""
|
||||||
|
if not project_root.is_dir():
|
||||||
|
return []
|
||||||
|
found: list[str] = []
|
||||||
|
for child in sorted(project_root.iterdir()):
|
||||||
|
if not child.is_dir() or child.name.startswith("."):
|
||||||
|
continue
|
||||||
|
if (child / "src").is_dir():
|
||||||
|
found.append(child.name)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
def resolve_object_type(name: str) -> str:
|
def resolve_object_type(name: str) -> str:
|
||||||
@@ -217,7 +238,7 @@ def resolve_object_type(name: str) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def discover_configs(project_root: Path, names: list[str] | None = None) -> list[ConfigPaths]:
|
def discover_configs(project_root: Path, names: list[str] | None = None) -> list[ConfigPaths]:
|
||||||
wanted = [resolve_config_name(n) for n in names] if names else list(DEFAULT_CONFIGS)
|
wanted = [resolve_config_name(n) for n in names] if names else list_config_dirs(project_root)
|
||||||
found: list[ConfigPaths] = []
|
found: list[ConfigPaths] = []
|
||||||
for name in wanted:
|
for name in wanted:
|
||||||
root = project_root / name
|
root = project_root / name
|
||||||
|
|||||||
+1
-1
@@ -245,7 +245,7 @@ def init_db(conn: sqlite3.Connection) -> None:
|
|||||||
if ver > SCHEMA_VERSION:
|
if ver > SCHEMA_VERSION:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"Индекс новее утилиты (схема {ver}, утилита {SCHEMA_VERSION}). "
|
f"Индекс новее утилиты (схема {ver}, утилита {SCHEMA_VERSION}). "
|
||||||
"Обновите tools/index."
|
"Обновите утилиту index до более новой версии."
|
||||||
)
|
)
|
||||||
if ver < SCHEMA_VERSION:
|
if ver < SCHEMA_VERSION:
|
||||||
migrate_schema(conn, ver)
|
migrate_schema(conn, ver)
|
||||||
|
|||||||
+2
-2
@@ -23,7 +23,7 @@ def open_index(project_root: Path, *, readonly: bool = True) -> sqlite3.Connecti
|
|||||||
path = dbmod.global_db_path(cache_dir(project_root))
|
path = dbmod.global_db_path(cache_dir(project_root))
|
||||||
if not path.is_file():
|
if not path.is_file():
|
||||||
raise FileNotFoundError(
|
raise FileNotFoundError(
|
||||||
f"Индекс не найден: {path}. Запустите: python tools/index/index_1c.py reindex --full"
|
f"Индекс не найден: {path}. Запустите: python index_1c.py reindex --full"
|
||||||
)
|
)
|
||||||
# мягкая миграция схемы (например 2→3: таблица register_records)
|
# мягкая миграция схемы (например 2→3: таблица register_records)
|
||||||
probe = dbmod.connect(path, readonly=True)
|
probe = dbmod.connect(path, readonly=True)
|
||||||
@@ -403,7 +403,7 @@ def find_refs_to(
|
|||||||
|
|
||||||
Возвращает (строки, totals_by_config).
|
Возвращает (строки, totals_by_config).
|
||||||
При поиске по нескольким конфигурациям ``limit`` — максимум **на каждую**
|
При поиске по нескольким конфигурациям ``limit`` — максимум **на каждую**
|
||||||
конфигурацию (чтобы crm3-26 не вытеснял crm3-dev из-за ORDER BY + LIMIT).
|
конфигурацию (чтобы одна baseconf не вытесняла другую из-за ORDER BY + LIMIT).
|
||||||
"""
|
"""
|
||||||
kind = ""
|
kind = ""
|
||||||
name = target
|
name = target
|
||||||
|
|||||||
+2
-2
@@ -272,8 +272,8 @@ def write_global_index_md(cache_root: Path, summary: dict[str, Any]) -> Path:
|
|||||||
f"Режим: `{summary.get('mode', '?')}`, БД: `cache/1c_meta/index.sqlite`.",
|
f"Режим: `{summary.get('mode', '?')}`, БД: `cache/1c_meta/index.sqlite`.",
|
||||||
f"Потоки: {summary.get('workers', '?')}, время: {summary.get('elapsed_sec', '?')} с.",
|
f"Потоки: {summary.get('workers', '?')}, время: {summary.get('elapsed_sec', '?')} с.",
|
||||||
"",
|
"",
|
||||||
"Поиск: `python tools/index/query_1c.py search \"…\"`",
|
"Поиск: `python query_1c.py search \"…\"`",
|
||||||
"Переиндексация: `python tools/index/index_1c.py reindex` (инкремент) / `--full`.",
|
"Переиндексация: `python index_1c.py reindex` (инкремент) / `--full`.",
|
||||||
"",
|
"",
|
||||||
"## Конфигурации",
|
"## Конфигурации",
|
||||||
"",
|
"",
|
||||||
|
|||||||
+25
-14
@@ -2,19 +2,19 @@
|
|||||||
"""Переиндексация метаданных и модулей конфигураций 1С → cache/1c_meta/index.sqlite.
|
"""Переиндексация метаданных и модулей конфигураций 1С → cache/1c_meta/index.sqlite.
|
||||||
|
|
||||||
Параметры:
|
Параметры:
|
||||||
--config, -c файл настроек утилиты (JSON)
|
--config, -c файл настроек утилиты (YAML)
|
||||||
--baseconf, -b какие выгрузки 1С индексировать (crm3-26, target, …)
|
--baseconf, -b какие выгрузки 1С индексировать (имя каталога с src/)
|
||||||
|
|
||||||
Примеры:
|
Примеры:
|
||||||
|
|
||||||
python tools/index/index_1c.py reindex -j 12
|
python index_1c.py reindex -j 12
|
||||||
python tools/index/index_1c.py reindex --full -j 12
|
python index_1c.py reindex --full -j 12
|
||||||
python tools/index/index_1c.py reindex --full -b crm3-26 -j 12
|
python index_1c.py reindex --full -b my-config -j 12
|
||||||
python tools/index/index_1c.py reindex -b target -b ws-rhana -t Documents,Catalogs
|
python index_1c.py reindex -b main -b my-config.ext -t Documents,Catalogs
|
||||||
python tools/index/index_1c.py status
|
python index_1c.py status
|
||||||
python tools/index/index_1c.py list
|
python index_1c.py list
|
||||||
|
|
||||||
Поиск: python tools/index/query_1c.py …
|
Поиск: python query_1c.py …
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -39,10 +39,11 @@ from index1c.cli import ( # noqa: E402
|
|||||||
validate_baseconfs,
|
validate_baseconfs,
|
||||||
)
|
)
|
||||||
from index1c.config import ( # noqa: E402
|
from index1c.config import ( # noqa: E402
|
||||||
CONFIG_ALIASES,
|
|
||||||
DEFAULT_SKIP_TYPES,
|
DEFAULT_SKIP_TYPES,
|
||||||
cache_dir,
|
cache_dir,
|
||||||
discover_configs,
|
discover_configs,
|
||||||
|
get_default_baseconfs,
|
||||||
|
get_config_aliases,
|
||||||
resolve_object_type,
|
resolve_object_type,
|
||||||
)
|
)
|
||||||
from index1c import db as dbmod # noqa: E402
|
from index1c import db as dbmod # noqa: E402
|
||||||
@@ -70,7 +71,17 @@ def _select_configs_for_reindex(args: argparse.Namespace, root: Path) -> list:
|
|||||||
sys.exit(e.exit_code)
|
sys.exit(e.exit_code)
|
||||||
return discover_configs(root, names)
|
return discover_configs(root, names)
|
||||||
|
|
||||||
# без -b: все известные с src/
|
# без -b: default_baseconfs из --config или автосканирование.
|
||||||
|
defaults = get_default_baseconfs()
|
||||||
|
if defaults:
|
||||||
|
try:
|
||||||
|
names = validate_baseconfs(root, defaults, require_indexed=False)
|
||||||
|
except BaseconfError as e:
|
||||||
|
print(str(e), file=sys.stderr)
|
||||||
|
sys.exit(e.exit_code)
|
||||||
|
return discover_configs(root, names)
|
||||||
|
|
||||||
|
# fallback: все каталоги с src/ в корне проекта
|
||||||
return discover_configs(root, None)
|
return discover_configs(root, None)
|
||||||
|
|
||||||
|
|
||||||
@@ -80,7 +91,7 @@ def cmd_reindex(args: argparse.Namespace) -> int:
|
|||||||
if not configs:
|
if not configs:
|
||||||
print(
|
print(
|
||||||
"Нет конфигураций для индексации (нужна папка <name>/src/).\n"
|
"Нет конфигураций для индексации (нужна папка <name>/src/).\n"
|
||||||
"Укажите -b crm3-26 или проверьте: python tools/index/index_1c.py list",
|
"Укажите -b <имя-выгрузки> или проверьте: python index_1c.py list",
|
||||||
file=sys.stderr,
|
file=sys.stderr,
|
||||||
)
|
)
|
||||||
return 1
|
return 1
|
||||||
@@ -150,7 +161,7 @@ def cmd_list_configs(args: argparse.Namespace) -> int:
|
|||||||
found = discover_configs(root, None)
|
found = discover_configs(root, None)
|
||||||
print("Выгрузки 1С в репозитории (для --baseconf / -b):")
|
print("Выгрузки 1С в репозитории (для --baseconf / -b):")
|
||||||
for c in found:
|
for c in found:
|
||||||
aliases = [k for k, v in CONFIG_ALIASES.items() if v == c.name]
|
aliases = [k for k, v in get_config_aliases().items() if v == c.name]
|
||||||
alias_s = f" алиасы: {', '.join(aliases)}" if aliases else ""
|
alias_s = f" алиасы: {', '.join(aliases)}" if aliases else ""
|
||||||
print(f"- {c.name}{alias_s}")
|
print(f"- {c.name}{alias_s}")
|
||||||
db_path = dbmod.global_db_path(cache_dir(root))
|
db_path = dbmod.global_db_path(cache_dir(root))
|
||||||
@@ -176,7 +187,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
epilog=(
|
epilog=(
|
||||||
"Конфигурация 1С: --baseconf (-b). Файл настроек утилиты: --config (-c).\n"
|
"Конфигурация 1С: --baseconf (-b). Файл настроек утилиты: --config (-c).\n"
|
||||||
"Алиасы baseconf: target→crm3-26, source→crm3-dev"
|
"Алиасы/default для baseconf — в YAML (--config), см. config.example.yml"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
|
|||||||
+11
-14
@@ -2,22 +2,19 @@
|
|||||||
"""Запросы к единому индексу конфигураций 1С (cache/1c_meta/index.sqlite).
|
"""Запросы к единому индексу конфигураций 1С (cache/1c_meta/index.sqlite).
|
||||||
|
|
||||||
Параметры:
|
Параметры:
|
||||||
--config, -c файл настроек утилиты (JSON), не конфигурация 1С
|
--config, -c файл настроек утилиты (YAML), не конфигурация 1С
|
||||||
--baseconf, -b выгрузка конфигурации 1С в репозитории (crm3-26, target, …)
|
--baseconf, -b выгрузка конфигурации 1С в репозитории (имя каталога с src/)
|
||||||
|
|
||||||
Примеры:
|
Примеры:
|
||||||
|
|
||||||
python tools/index/query_1c.py search \"ЗаказКлиента\"
|
python query_1c.py search \"Contract\"
|
||||||
python tools/index/query_1c.py search \"Партнер\" --type Document -b crm3-26
|
python query_1c.py search \"Partner\" --type Document -b my-config
|
||||||
python tools/index/query_1c.py show ЗаказКлиента -b target
|
python query_1c.py show Document.Contract -b main
|
||||||
python tools/index/query_1c.py show Document.ЗаказКлиента -b crm3-26
|
python query_1c.py modules \"ProcessData\" -b my-config.ext
|
||||||
python tools/index/query_1c.py modules \"РВС_Transfer\" -b ws-rhana
|
python query_1c.py refs Catalog.Customers -b main
|
||||||
python tools/index/query_1c.py refs Catalog.Партнеры -b source
|
python query_1c.py movements Document.Contract -b my-config
|
||||||
python tools/index/query_1c.py movements ЗаказКлиента -b target
|
python query_1c.py object Contract -b my-config --clear
|
||||||
python tools/index/query_1c.py movements AccumulationRegister.ТоварыНаСкладах -b target
|
python query_1c.py module CommonModules/MyModule
|
||||||
python tools/index/query_1c.py object ЗаказКлиента -b target
|
|
||||||
python tools/index/query_1c.py object Партнер -b crm3-26 --clear
|
|
||||||
python tools/index/query_1c.py module CommonModules/РВС_TransferAPIДокументы
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -360,7 +357,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
epilog=(
|
epilog=(
|
||||||
"Конфигурация 1С — параметр --baseconf (-b): папка выгрузки в репозитории.\n"
|
"Конфигурация 1С — параметр --baseconf (-b): папка выгрузки в репозитории.\n"
|
||||||
"Можно указать до или после подкоманды; несколько раз или через запятую.\n"
|
"Можно указать до или после подкоманды; несколько раз или через запятую.\n"
|
||||||
"Файл настроек утилиты — --config (-c): см. tools/index/config.example.json"
|
"Файл настроек утилиты — --config (-c): см. config.example.yml"
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
p.add_argument(
|
p.add_argument(
|
||||||
|
|||||||
Reference in New Issue
Block a user