Compare commits

..

5 Commits

Author SHA1 Message Date
dcabfc7afd исправление документации 2026-02-20 00:21:34 +03:00
b176ba4996 рефакторинг 2026-02-20 00:03:57 +03:00
d18251ef44 исправление параметра 2026-02-19 21:55:54 +03:00
7c45e1855f update README 2026-02-19 19:52:03 +03:00
9250b12bcb cleanup 2026-02-19 18:09:03 +03:00
10 changed files with 28 additions and 32 deletions

View File

@@ -1,7 +1,14 @@
# cgpcli # cgpcli
[![Go Reference](https://pkg.go.dev/badge/git.vsu.ru/ai/cgpcli.svg)](https://pkg.go.dev/git.vsu.ru/ai/cgpcli)
[![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg)](LICENSE.md)
`cgpcli` is a Go client library for the **CommuniGate Pro** CLI. It provides a reliable bridge between CGP's unique syntax and native Go types with a focus on efficiency and correct type mapping. `cgpcli` is a Go client library for the **CommuniGate Pro** CLI. It provides a reliable bridge between CGP's unique syntax and native Go types with a focus on efficiency and correct type mapping.
## Documentation
Full API documentation and usage examples are available at [pkg.go.dev](https://pkg.go.dev/git.vsu.ru/ai/cgpcli).
## Installation ## Installation
```bash ```bash

4
build
View File

@@ -40,12 +40,12 @@ elif [ "$1" == "sandbox-test-one" ]; then
echo "" echo ""
echo "--- Running tests on sandbox ---" echo "--- Running tests on sandbox ---"
ssh "${REMOTE_HOST}" "cd ${REMOTE_PATH} && ./build test-once $2" ssh "${REMOTE_HOST}" "cd ${REMOTE_PATH} && ./build test-one $2"
elif [ "$1" == "test" ]; then elif [ "$1" == "test" ]; then
. .env . .env
go test -v go test -v
elif [ "$1" == "test-once" ]; then elif [ "$1" == "test-one" ]; then
. .env . .env
go test -v -run $2 go test -v -run $2
elif [ "$1" == "bench" ]; then elif [ "$1" == "bench" ]; then

View File

@@ -20,7 +20,7 @@ func main() {
if mode == "ro" { if mode == "ro" {
suffix = "_RO" suffix = "_RO"
defaultAccount = "testadmin@vsu.ru" // или любой другой боевой defaultAccount = "testadmin@domain.name"
fmt.Println(">>> MODE: READ-ONLY (PRODUCTION) <<<") fmt.Println(">>> MODE: READ-ONLY (PRODUCTION) <<<")
} else { } else {
fmt.Println(">>> MODE: LOCAL TEST <<<") fmt.Println(">>> MODE: LOCAL TEST <<<")

View File

@@ -36,8 +36,6 @@ func main() {
// 2. Читаем алерты // 2. Читаем алерты
fmt.Println("\n--- GETSERVERALERTS (Checking types) ---") fmt.Println("\n--- GETSERVERALERTS (Checking types) ---")
// Пока используем GetServerAlerts, который возвращает map[string]any (или уже map[string]string?)
// Чтобы увидеть "сырые" типы от парсера, проверим через Any.
res, err := cli.Query("GETSERVERALERTS") res, err := cli.Query("GETSERVERALERTS")
if err != nil { if err != nil {
log.Fatalf("Get error: %v", err) log.Fatalf("Get error: %v", err)

View File

@@ -32,7 +32,6 @@ func main() {
} }
fmt.Println("\n--- Directory Integration ---") fmt.Println("\n--- Directory Integration ---")
// Настройки интеграции (LDAP, Active Directory и т.д.)
integration, err := cli.Query("GETDIRECTORYINTEGRATION") integration, err := cli.Query("GETDIRECTORYINTEGRATION")
if err != nil { if err != nil {
fmt.Printf("GetIntegration error: %v\n", err) fmt.Printf("GetIntegration error: %v\n", err)

View File

@@ -28,7 +28,6 @@ func main() {
fmt.Println("--- Testing LISTDOMAINOBJECTS with Enum Flags ---") fmt.Println("--- Testing LISTDOMAINOBJECTS with Enum Flags ---")
// 3. Вызов функции с использованием битовой маски // 3. Вызов функции с использованием битовой маски
// Например: запрашиваем Аккаунты и Форвардеры, игнорируя Алиасы
mask := cgpcli.TypeAccount | cgpcli.TypeForwarder | cgpcli.TypeAlias mask := cgpcli.TypeAccount | cgpcli.TypeForwarder | cgpcli.TypeAlias
res, err := cli.ListDomainObjects("test.domain.name", 100, "", mask, "") res, err := cli.ListDomainObjects("test.domain.name", 100, "", mask, "")
@@ -36,14 +35,13 @@ func main() {
log.Fatalf("ListDomainObjects error: %v", err) log.Fatalf("ListDomainObjects error: %v", err)
} }
// 4. Красивый вывод через нашу утилиту // 4. Красивый вывод
fmt.Println("\nStructure via PrettyPrint:") fmt.Println("\nStructure via PrettyPrint:")
cgpcli.PrettyPrint(res) cgpcli.PrettyPrint(res)
// 5. Демонстрация работы с типизированными данными // 5. Демонстрация работы с типизированными данными
fmt.Printf("\n--- Summary (Total: %d, Cookie: '%s') ---\n", res.Total, res.Cookie) fmt.Printf("\n--- Summary (Total: %d, Cookie: '%s') ---\n", res.Total, res.Cookie)
// Сортируем ключи для красивого вывода в консоль
keys := make([]string, 0, len(res.Objects)) keys := make([]string, 0, len(res.Objects))
for k := range res.Objects { for k := range res.Objects {
keys = append(keys, k) keys = append(keys, k)
@@ -53,7 +51,6 @@ func main() {
for _, name := range keys { for _, name := range keys {
obj := res.Objects[name] obj := res.Objects[name]
// Благодаря Enum мы можем делать чистые проверки
typeLabel := obj.Type.String() typeLabel := obj.Type.String()
if len(obj.Targets) > 0 { if len(obj.Targets) > 0 {

View File

@@ -10,7 +10,6 @@ import (
) )
func main() { func main() {
// Используем переменные окружения из ваших тестов
cgpuser := os.Getenv("CGPUSER") cgpuser := os.Getenv("CGPUSER")
cgppass := os.Getenv("CGPPASS") cgppass := os.Getenv("CGPPASS")
@@ -18,7 +17,6 @@ func main() {
log.Fatal("Error: please set CGPUSER and CGPPASS environment variables") log.Fatal("Error: please set CGPUSER and CGPPASS environment variables")
} }
// Используем ваш конструктор New (APOP, без TLS для теста на 127.0.0.1)
cli, err := cgpcli.New("127.0.0.1", cgpuser, cgppass, cgpcli.APOP, false) cli, err := cgpcli.New("127.0.0.1", cgpuser, cgppass, cgpcli.APOP, false)
if err != nil { if err != nil {
log.Fatalf("Failed to connect: %v", err) log.Fatalf("Failed to connect: %v", err)
@@ -28,13 +26,11 @@ func main() {
fmt.Println("Connected to 127.0.0.1. Enumerating OIDs...") fmt.Println("Connected to 127.0.0.1. Enumerating OIDs...")
fmt.Println(strings.Repeat("-", 40)) fmt.Println(strings.Repeat("-", 40))
// Запрашиваем список
stats, err := cli.ListAllStats() stats, err := cli.ListAllStats()
if err != nil { if err != nil {
log.Fatalf("Error during enumeration: %v", err) log.Fatalf("Error during enumeration: %v", err)
} }
// Выводим с порядковыми номерами
for i, name := range stats { for i, name := range stats {
fmt.Printf("%04d | %s\n", i+1, name) fmt.Printf("%04d | %s\n", i+1, name)
} }

View File

@@ -18,7 +18,6 @@ func main() {
} }
// 2. Инициализация клиента // 2. Инициализация клиента
// Используем ваш конструктор New
cli, err := cgpcli.New("127.0.0.1", cgpuser, cgppass, cgpcli.APOP, false) cli, err := cgpcli.New("127.0.0.1", cgpuser, cgppass, cgpcli.APOP, false)
if err != nil { if err != nil {
log.Fatalf("Failed to connect: %v", err) log.Fatalf("Failed to connect: %v", err)
@@ -31,7 +30,6 @@ func main() {
fmt.Printf("Updating RealName for %s to: %s\n", targetAccount, russianName) fmt.Printf("Updating RealName for %s to: %s\n", targetAccount, russianName)
// 1. Устанавливаем русское имя // 1. Устанавливаем русское имя
// UpdateAccountSettings отправляет данные через Marshal
err = cli.UpdateAccountSettings(targetAccount, map[string]any{ err = cli.UpdateAccountSettings(targetAccount, map[string]any{
"RealName": russianName, "RealName": russianName,
}) })

View File

@@ -66,25 +66,20 @@ func (cli *Cli) CreateAccountStorage(domain, storage string) error {
// DeleteDirectoryRecords deletes Domain object records from the Directory. // DeleteDirectoryRecords deletes Domain object records from the Directory.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the authenticated user Domain. // - domain: an optional Domain name. If empty, applies to the authenticated user Domain.
// //
// This method executes the DELETEDIRECTORYRECORDS CLI command. // This method executes the DELETEDIRECTORYRECORDS CLI command.
// //
// Returns: // Returns:
// - error: an error if the command fails. // - error: an error if the command fails.
func (cli *Cli) DeleteDirectoryRecords(domain string) error { func (cli *Cli) DeleteDirectoryRecords(domain string) error {
const cmd = "DELETEDIRECTORYRECORDS" return cli.QueryNV("DELETEDIRECTORYRECORDS", Atom(domain))
if domain != "" {
return cli.QueryNV(cmd, domain)
} else {
return cli.QueryNV(cmd)
}
} }
// GetAccountDefaultPrefs retrieves the Default Account Preferences for the specified Domain. // GetAccountDefaultPrefs retrieves the Default Account Preferences for the specified Domain.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the administrator Domain. // - domain: an optional Domain name. If empty, applies to the administrator Domain.
// //
// This method executes the GETACCOUNTDEFAULTPREFS CLI command. // This method executes the GETACCOUNTDEFAULTPREFS CLI command.
// //
@@ -98,7 +93,7 @@ func (cli *Cli) GetAccountDefaultPrefs(domain string) (map[string]any, error) {
// GetAccountDefaults retrieves the default Account settings for the specified Domain. // GetAccountDefaults retrieves the default Account settings for the specified Domain.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the administrator Domain. // - domain: an optional Domain name. If empty, applies to the administrator Domain.
// //
// This method executes the GETACCOUNTDEFAULTS CLI command. // This method executes the GETACCOUNTDEFAULTS CLI command.
// //
@@ -143,7 +138,7 @@ func (cli *Cli) GetDomainAliases(domain string) ([]string, error) {
// GetDomainEffectiveSettings retrieves both explicitly set and default Domain settings. // GetDomainEffectiveSettings retrieves both explicitly set and default Domain settings.
// //
// Parameters: // Parameters:
// - domain: the name of an existing Domain. If empty, uses the current context. // - domain: an optional name of an existing Domain. If empty, uses the current context.
// //
// This method executes the GETDOMAINEFFECTIVESETTINGS CLI command. // This method executes the GETDOMAINEFFECTIVESETTINGS CLI command.
// //
@@ -188,7 +183,7 @@ func (cli *Cli) GetDomainMailRules(domain string) ([]MailRule, error) {
// GetDomainSettings retrieves explicitly set (non-default) Domain settings. // GetDomainSettings retrieves explicitly set (non-default) Domain settings.
// //
// Parameters: // Parameters:
// - domain: the name of an existing Domain. If empty, uses the current context. // - domain: an optional name of an existing Domain. If empty, uses the current context.
// //
// This method executes the GETDOMAINSETTINGS CLI command. // This method executes the GETDOMAINSETTINGS CLI command.
// //
@@ -219,7 +214,7 @@ func (cli *Cli) GetDomainSignalRules(domain string) ([]SignalRule, error) {
// InsertDirectoryRecords inserts records for Domain objects into the Directory. // InsertDirectoryRecords inserts records for Domain objects into the Directory.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the authenticated user Domain. // - domain: an optional Domain name. If empty, applies to the authenticated user Domain.
// //
// This method executes the INSERTDIRECTORYRECORDS CLI command. // This method executes the INSERTDIRECTORYRECORDS CLI command.
// //
@@ -561,7 +556,7 @@ func (cli *Cli) SuspendDomain(domain string) error {
// UpdateAccountDefaultPrefs modifies the Domain Default Account Preferences. // UpdateAccountDefaultPrefs modifies the Domain Default Account Preferences.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the authenticated user Domain. // - domain: an optional Domain name. If empty, applies to the authenticated user Domain.
// - settings: a dictionary used to modify the Domain Default Account Preferences. // - settings: a dictionary used to modify the Domain Default Account Preferences.
// //
// This method executes the UPDATEACCOUNTDEFAULTPREFS CLI command. // This method executes the UPDATEACCOUNTDEFAULTPREFS CLI command.
@@ -578,7 +573,7 @@ func (cli *Cli) UpdateAccountDefaultPrefs(domain string, settings map[string]any
// UpdateAccountDefaults modifies the Default Account settings for the specified Domain. // UpdateAccountDefaults modifies the Default Account settings for the specified Domain.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the administrator Domain. // - domain: an optional Domain name. If empty, applies to the administrator Domain.
// - settings: a dictionary used to modify the Domain Default Account settings. // - settings: a dictionary used to modify the Domain Default Account settings.
// //
// This method executes the UPDATEACCOUNTDEFAULTS CLI command. // This method executes the UPDATEACCOUNTDEFAULTS CLI command.
@@ -595,7 +590,7 @@ func (cli *Cli) UpdateAccountDefaults(domain string, settings map[string]any) er
// UpdateAccountTemplate modifies the Account Template settings for the Domain. // UpdateAccountTemplate modifies the Account Template settings for the Domain.
// //
// Parameters: // Parameters:
// - domain: the Domain name. If empty, applies to the administrator Domain. // - domain: an optional Domain name. If empty, applies to the administrator Domain.
// - settings: a dictionary used to modify the Domain Account Template. // - settings: a dictionary used to modify the Domain Account Template.
// //
// This method executes the UPDATEACCOUNTTEMPLATE CLI command. // This method executes the UPDATEACCOUNTTEMPLATE CLI command.
@@ -612,7 +607,7 @@ func (cli *Cli) UpdateAccountTemplate(domain string, settings map[string]any) er
// UpdateDomainSettings updates specific Domain settings without modifying others. // UpdateDomainSettings updates specific Domain settings without modifying others.
// //
// Parameters: // Parameters:
// - domain: the name of an existing Domain. If empty, uses the current context. // - domain: an optional name of an existing Domain. If empty, uses the current context.
// - settings: a dictionary containing the settings to update. // - settings: a dictionary containing the settings to update.
// //
// This method executes the UPDATEDOMAINSETTINGS CLI command. // This method executes the UPDATEDOMAINSETTINGS CLI command.

View File

@@ -129,6 +129,12 @@ func TestDomainAdministration(t *testing.T) {
if err := cli.DeleteDirectoryRecords(targetDomain); err != nil { if err := cli.DeleteDirectoryRecords(targetDomain); err != nil {
t.Errorf("DeleteDirectoryRecords failed: %v", err) t.Errorf("DeleteDirectoryRecords failed: %v", err)
} }
if err := cli.InsertDirectoryRecords(""); err != nil {
t.Errorf("InsertDirectoryRecords failed: %v", err)
}
if err := cli.DeleteDirectoryRecords(""); err != nil {
t.Errorf("DeleteDirectoryRecords failed: %v", err)
}
}) })
// 7. Состояние домена // 7. Состояние домена