add: generator tools (sources)
This commit is contained in:
@@ -0,0 +1,715 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// service_spec_gen: builds unified service YAML from API.
|
||||
//
|
||||
// Design goals:
|
||||
// - One YAML per service, stored in resources_yaml.
|
||||
// - The YAML includes all instance operations, subresource operations, and actions.
|
||||
// - MAN and parameter metadata are embedded in the same YAML so docs and Go
|
||||
// generators have a single source of truth.
|
||||
//
|
||||
// Env:
|
||||
// - NUBES_API_TOKEN (preferred) or TOKEN_FILE
|
||||
// - NUBES_API_ENDPOINT (default: https://deck-api.ngcloud.ru/api/v1/index.cfm)
|
||||
// - NUBES_SERVICE_ID (optional for single service)
|
||||
// - NUBES_SERVICE_NAME (optional override for single service)
|
||||
// - NUBES_SERVICES_FILE (default: devops/config/services_list.txt)
|
||||
// - NUBES_OUTPUT_DIR (default: <repo>/resources_yaml)
|
||||
|
||||
func main() {
|
||||
// Load env and services list configuration first so we can derive output paths.
|
||||
cfg, err := loadConfig()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// API client uses proxy endpoint with bearer token.
|
||||
client := newAPIClient(cfg.ApiEndpoint, cfg.ApiToken)
|
||||
|
||||
// If a single service is requested, override the list from services_list.txt.
|
||||
services := cfg.Services
|
||||
if cfg.SingleServiceID > 0 {
|
||||
services = []serviceRef{{ID: cfg.SingleServiceID, Name: cfg.SingleServiceName}}
|
||||
}
|
||||
|
||||
// Unified YAML output directory. We never emit resources_ops_yaml anymore.
|
||||
outputDir := cfg.OutputDir
|
||||
if outputDir == "" {
|
||||
// Resolve the repo root only if we need the default output dir.
|
||||
repoRoot, err := findRepoRoot()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
outputDir = filepath.Join(repoRoot, "resources_yaml")
|
||||
}
|
||||
if err := validateOutputDir(outputDir); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.MkdirAll(outputDir, 0o755); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
for _, svc := range services {
|
||||
if svc.ID <= 0 {
|
||||
continue
|
||||
}
|
||||
// Fetch service metadata and the operation list.
|
||||
info, err := client.getService(svc.ID)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// Prefer the explicit name from services_list.txt; otherwise derive from API.
|
||||
name := strings.TrimSpace(svc.Name)
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(info.ShortName)
|
||||
}
|
||||
if name == "" {
|
||||
name = strings.TrimSpace(info.DisplayName)
|
||||
}
|
||||
name = normalizeServiceName(name)
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("service_%d", svc.ID)
|
||||
}
|
||||
|
||||
// Collect operations and derive lifecycle defaults based on suspend/resume.
|
||||
ops, hasSuspend, _, _, err := client.collectOperations(info.Operations)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
suspendOnDestroyDefault := hasSuspend
|
||||
adoptExistingOnCreateDefault := false
|
||||
|
||||
// Build the unified service YAML spec. This is the only YAML for the service.
|
||||
spec := ServiceSpec{
|
||||
Name: name,
|
||||
ServiceID: svc.ID,
|
||||
ServiceDisplayName: strings.TrimSpace(info.DisplayName),
|
||||
ServiceShortName: strings.TrimSpace(info.ShortName),
|
||||
ServiceMan: strings.TrimSpace(info.Man),
|
||||
Lifecycle: Lifecycle{
|
||||
SuspendOnDestroyDefault: suspendOnDestroyDefault,
|
||||
AdoptExistingOnCreateDefault: adoptExistingOnCreateDefault,
|
||||
},
|
||||
Outputs: OutputSection{Params: defaultOutputParams()},
|
||||
Operations: ops,
|
||||
}
|
||||
|
||||
// Write <service_id>_<name>.yaml to resources_yaml.
|
||||
outPath := filepath.Join(outputDir, fmt.Sprintf("%d_%s.yaml", svc.ID, name))
|
||||
buf, err := yaml.Marshal(spec)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := os.WriteFile(outPath, buf, 0o644); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("written %s\n", outPath)
|
||||
}
|
||||
}
|
||||
|
||||
// ===== config =====
|
||||
|
||||
type config struct {
|
||||
ApiEndpoint string
|
||||
ApiToken string
|
||||
Services []serviceRef
|
||||
SingleServiceID int
|
||||
SingleServiceName string
|
||||
OutputDir string
|
||||
}
|
||||
|
||||
type serviceRef struct {
|
||||
ID int
|
||||
Name string
|
||||
}
|
||||
|
||||
func loadConfig() (config, error) {
|
||||
// API endpoint defaults to production; token is required.
|
||||
apiEndpoint := getenvDefault("NUBES_API_ENDPOINT", "https://deck-api.ngcloud.ru/api/v1/index.cfm")
|
||||
apiEndpoint = normalizeAPIEndpoint(apiEndpoint)
|
||||
apiToken, err := loadToken()
|
||||
if err != nil {
|
||||
return config{}, err
|
||||
}
|
||||
|
||||
// Optional single-service mode for debugging and local inspection.
|
||||
singleID := 0
|
||||
if raw := strings.TrimSpace(os.Getenv("NUBES_SERVICE_ID")); raw != "" {
|
||||
val, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return config{}, fmt.Errorf("invalid NUBES_SERVICE_ID: %s", raw)
|
||||
}
|
||||
singleID = val
|
||||
}
|
||||
|
||||
singleName := strings.TrimSpace(os.Getenv("NUBES_SERVICE_NAME"))
|
||||
outputDir := strings.TrimSpace(os.Getenv("NUBES_OUTPUT_DIR"))
|
||||
|
||||
services := []serviceRef{}
|
||||
if singleID == 0 {
|
||||
// services_list.txt is the source of truth for which services to generate.
|
||||
listPath := strings.TrimSpace(os.Getenv("NUBES_SERVICES_FILE"))
|
||||
if listPath == "" {
|
||||
repoRoot, err := findRepoRoot()
|
||||
if err != nil {
|
||||
return config{}, err
|
||||
}
|
||||
listPath = filepath.Join(repoRoot, "devops", "config", "services_list.txt")
|
||||
}
|
||||
list, err := readServicesList(listPath)
|
||||
if err != nil {
|
||||
return config{}, err
|
||||
}
|
||||
services = list
|
||||
}
|
||||
|
||||
return config{
|
||||
ApiEndpoint: apiEndpoint,
|
||||
ApiToken: apiToken,
|
||||
Services: services,
|
||||
SingleServiceID: singleID,
|
||||
SingleServiceName: singleName,
|
||||
OutputDir: outputDir,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getenvDefault(key string, def string) string {
|
||||
val := strings.TrimSpace(os.Getenv(key))
|
||||
if val == "" {
|
||||
return def
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
func loadToken() (string, error) {
|
||||
// Prefer explicit env token, then TOKEN_FILE, then the latest *.token.
|
||||
if tok := strings.TrimSpace(os.Getenv("NUBES_API_TOKEN")); tok != "" {
|
||||
return tok, nil
|
||||
}
|
||||
if tf := strings.TrimSpace(os.Getenv("TOKEN_FILE")); tf != "" {
|
||||
b, err := os.ReadFile(tf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
repoRoot, err := findRepoRoot()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
latest, err := findLatestToken(repoRoot)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if latest == "" {
|
||||
return "", errors.New("NUBES_API_TOKEN or TOKEN_FILE is required")
|
||||
}
|
||||
b, err := os.ReadFile(latest)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
|
||||
func findLatestToken(dir string) (string, error) {
|
||||
// Pick the newest *.token file by mtime.
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var latest string
|
||||
var latestTime int64
|
||||
for _, e := range entries {
|
||||
if e.IsDir() || !strings.HasSuffix(e.Name(), ".token") {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
mt := info.ModTime().Unix()
|
||||
if mt > latestTime {
|
||||
latestTime = mt
|
||||
latest = filepath.Join(dir, e.Name())
|
||||
}
|
||||
}
|
||||
return latest, nil
|
||||
}
|
||||
|
||||
func readServicesList(path string) ([]serviceRef, error) {
|
||||
// Each non-empty line is: <service_id> <name> [# comment]
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lines := strings.Split(string(b), "\n")
|
||||
services := []serviceRef{}
|
||||
for _, raw := range lines {
|
||||
line := strings.TrimSpace(strings.ReplaceAll(raw, "\r", ""))
|
||||
if line == "" || strings.HasPrefix(line, "#") {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(line, "#") {
|
||||
line = strings.TrimSpace(strings.SplitN(line, "#", 2)[0])
|
||||
}
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid service id in %s: %s", path, parts[0])
|
||||
}
|
||||
name := ""
|
||||
if len(parts) > 1 {
|
||||
name = parts[1]
|
||||
}
|
||||
services = append(services, serviceRef{ID: id, Name: name})
|
||||
}
|
||||
return services, nil
|
||||
}
|
||||
|
||||
func findRepoRoot() (string, error) {
|
||||
// We locate the repo by finding the universal_rebuild directory.
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
current := wd
|
||||
for i := 0; i < 8; i++ {
|
||||
candidate := filepath.Join(current, "universal_rebuild")
|
||||
info, err := os.Stat(candidate)
|
||||
if err == nil && info.IsDir() {
|
||||
return candidate, nil
|
||||
}
|
||||
parent := filepath.Dir(current)
|
||||
if parent == current {
|
||||
break
|
||||
}
|
||||
current = parent
|
||||
}
|
||||
return "", errors.New("failed to locate universal_rebuild repo root")
|
||||
}
|
||||
|
||||
// ===== api client =====
|
||||
|
||||
type apiClient struct {
|
||||
endpoint string
|
||||
token string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
type serviceResponse struct {
|
||||
Service serviceInfo `json:"svc"`
|
||||
}
|
||||
|
||||
type serviceInfo struct {
|
||||
ID int `json:"svcId"`
|
||||
DisplayName string `json:"svc"`
|
||||
ShortName string `json:"svcShort"`
|
||||
Man string `json:"man"`
|
||||
Operations []operationInfo `json:"operations"`
|
||||
}
|
||||
|
||||
type operationInfo struct {
|
||||
SvcOperationId int `json:"svcOperationId"`
|
||||
Operation string `json:"operation"`
|
||||
}
|
||||
|
||||
type serviceOperationResponse struct {
|
||||
ServiceOperation serviceOperationInfo `json:"svcOperation"`
|
||||
}
|
||||
|
||||
type serviceOperationInfo struct {
|
||||
SvcOperationId int `json:"svcOperationId"`
|
||||
Operation string `json:"operation"`
|
||||
Man string `json:"man"`
|
||||
CfsParams []cfsParam `json:"cfsParams"`
|
||||
}
|
||||
|
||||
type cfsParam struct {
|
||||
ID int `json:"svcOperationCfsParamId"`
|
||||
Code string `json:"svcOperationCfsParam"`
|
||||
DataType string `json:"dataType"`
|
||||
ValueList []interface{} `json:"valueList"`
|
||||
RefSvcId *int `json:"refSvcId"`
|
||||
IsRequired bool `json:"isRequired"`
|
||||
DefaultValue interface{} `json:"defaultValue"`
|
||||
Func string `json:"func"`
|
||||
Regex string `json:"regex"`
|
||||
UniqueScope string `json:"uniqueScope"`
|
||||
MaxLength *int `json:"maxlength"`
|
||||
MinLength *int `json:"minlength"`
|
||||
MaxValue interface{} `json:"maxvalue"`
|
||||
MinValue interface{} `json:"minvalue"`
|
||||
Descr string `json:"descr"`
|
||||
Man string `json:"man"`
|
||||
Sort *int `json:"sort"`
|
||||
DependsOnCfsParams interface{} `json:"dependsOnCfsParams"`
|
||||
IsModifiable *bool `json:"isModifiable"`
|
||||
IsSensitive bool `json:"isSensitive"`
|
||||
}
|
||||
|
||||
func (c *apiClient) getService(serviceID int) (serviceInfo, error) {
|
||||
// /services/{id} returns display names, MAN, and a list of operations.
|
||||
endpoint := fmt.Sprintf("/services/%d", serviceID)
|
||||
var res serviceResponse
|
||||
if err := c.getViaProxy(endpoint, &res); err != nil {
|
||||
return serviceInfo{}, err
|
||||
}
|
||||
return res.Service, nil
|
||||
}
|
||||
|
||||
func (c *apiClient) getServiceOperation(svcOperationId int) (serviceOperationInfo, error) {
|
||||
// /serviceOperation/{id} returns params and MAN for a single operation.
|
||||
endpoint := fmt.Sprintf("/serviceOperation/%d", svcOperationId)
|
||||
var res serviceOperationResponse
|
||||
if err := c.getViaProxy(endpoint, &res); err != nil {
|
||||
return serviceOperationInfo{}, err
|
||||
}
|
||||
return res.ServiceOperation, nil
|
||||
}
|
||||
|
||||
func (c *apiClient) getViaProxy(endpoint string, out interface{}) error {
|
||||
// The API uses a proxy query parameter called "endpoint".
|
||||
req, err := http.NewRequest("GET", c.endpoint, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
q := req.URL.Query()
|
||||
q.Set("endpoint", endpoint)
|
||||
req.URL.RawQuery = q.Encode()
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
}
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
dec := json.NewDecoder(resp.Body)
|
||||
return dec.Decode(out)
|
||||
}
|
||||
|
||||
func (c *apiClient) collectOperations(ops []operationInfo) ([]OperationSpec, bool, bool, bool, error) {
|
||||
// Resolve each operation in detail and classify it into instance/subresource/action.
|
||||
result := make([]OperationSpec, 0, len(ops))
|
||||
hasSuspend := false
|
||||
hasResume := false
|
||||
hasDelete := false
|
||||
for _, op := range ops {
|
||||
opName := normalizeOperationName(op.Operation)
|
||||
if opName == "" {
|
||||
continue
|
||||
}
|
||||
opInfo, err := c.getServiceOperation(op.SvcOperationId)
|
||||
if err != nil {
|
||||
return nil, false, false, false, err
|
||||
}
|
||||
// Params are captured with full metadata, including MAN/descr/constraints.
|
||||
params := make([]ParamSpec, 0, len(opInfo.CfsParams))
|
||||
for _, p := range opInfo.CfsParams {
|
||||
params = append(params, ParamSpec{
|
||||
ID: p.ID,
|
||||
Code: p.Code,
|
||||
DataType: strings.TrimSpace(p.DataType),
|
||||
Required: p.IsRequired,
|
||||
Default: normalizeDefault(p.DefaultValue),
|
||||
ValueList: normalizeValueList(p.ValueList),
|
||||
RefSvcId: p.RefSvcId,
|
||||
Func: strings.TrimSpace(p.Func),
|
||||
Regex: strings.TrimSpace(p.Regex),
|
||||
UniqueScope: strings.TrimSpace(p.UniqueScope),
|
||||
MaxLength: p.MaxLength,
|
||||
MinLength: p.MinLength,
|
||||
MaxValue: normalizeDefault(p.MaxValue),
|
||||
MinValue: normalizeDefault(p.MinValue),
|
||||
Descr: strings.TrimSpace(p.Descr),
|
||||
Man: strings.TrimSpace(p.Man),
|
||||
Sort: p.Sort,
|
||||
DependsOn: p.DependsOnCfsParams,
|
||||
IsModifiable: p.IsModifiable,
|
||||
IsSensitive: p.IsSensitive,
|
||||
})
|
||||
}
|
||||
sort.Slice(params, func(i, j int) bool { return params[i].ID < params[j].ID })
|
||||
|
||||
// Operation name determines kind and action.
|
||||
kind, action, subresource := classifyOperation(opName)
|
||||
if kind == "instance" && action == "suspend" {
|
||||
hasSuspend = true
|
||||
}
|
||||
if kind == "instance" && action == "resume" {
|
||||
hasResume = true
|
||||
}
|
||||
if kind == "instance" && action == "delete" {
|
||||
hasDelete = true
|
||||
}
|
||||
result = append(result, OperationSpec{
|
||||
Name: opName,
|
||||
ID: opInfo.SvcOperationId,
|
||||
Kind: kind,
|
||||
Action: action,
|
||||
Subresource: subresource,
|
||||
Man: strings.TrimSpace(opInfo.Man),
|
||||
Params: params,
|
||||
})
|
||||
}
|
||||
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
if result[i].Name == result[j].Name {
|
||||
return result[i].ID < result[j].ID
|
||||
}
|
||||
return result[i].Name < result[j].Name
|
||||
})
|
||||
return result, hasSuspend, hasResume, hasDelete, nil
|
||||
}
|
||||
|
||||
func classifyOperation(name string) (string, string, string) {
|
||||
// Canonical classification rules:
|
||||
// - create/modify/delete/suspend/resume -> instance
|
||||
// - create_*/modify_*/delete_* -> subresource
|
||||
// - everything else -> action
|
||||
n := strings.ToLower(strings.TrimSpace(name))
|
||||
if n == "create" || n == "modify" || n == "delete" || n == "suspend" || n == "resume" {
|
||||
return "instance", n, ""
|
||||
}
|
||||
if strings.HasPrefix(n, "create_") {
|
||||
sub := strings.TrimPrefix(n, "create_")
|
||||
if sub != "" {
|
||||
return "subresource", "create", sub
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(n, "modify_") {
|
||||
sub := strings.TrimPrefix(n, "modify_")
|
||||
if sub != "" {
|
||||
return "subresource", "modify", sub
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(n, "delete_") {
|
||||
sub := strings.TrimPrefix(n, "delete_")
|
||||
if sub != "" {
|
||||
return "subresource", "delete", sub
|
||||
}
|
||||
}
|
||||
return "action", n, ""
|
||||
}
|
||||
|
||||
func normalizeValueList(values []interface{}) []string {
|
||||
// YAML stores value_list as strings for stable docs rendering.
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]string, 0, len(values))
|
||||
for _, v := range values {
|
||||
out = append(out, fmt.Sprintf("%v", v))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func normalizeDefault(value interface{}) interface{} {
|
||||
// Keep numeric defaults as-is, but trim strings.
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
switch t := value.(type) {
|
||||
case string:
|
||||
return strings.TrimSpace(t)
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// ===== spec =====
|
||||
|
||||
type ServiceSpec struct {
|
||||
Name string `yaml:"name"`
|
||||
ServiceID int `yaml:"service_id"`
|
||||
ServiceDisplayName string `yaml:"service_display_name,omitempty"`
|
||||
ServiceShortName string `yaml:"service_short_name,omitempty"`
|
||||
ServiceMan string `yaml:"service_man,omitempty"`
|
||||
Lifecycle Lifecycle `yaml:"lifecycle"`
|
||||
Outputs OutputSection `yaml:"outputs"`
|
||||
Operations []OperationSpec `yaml:"operations"`
|
||||
}
|
||||
|
||||
type Lifecycle struct {
|
||||
SuspendOnDestroyDefault bool `yaml:"suspend_on_destroy_default"`
|
||||
AdoptExistingOnCreateDefault bool `yaml:"adopt_existing_on_create_default"`
|
||||
}
|
||||
|
||||
type OutputSection struct {
|
||||
Params []OutputParam `yaml:"params"`
|
||||
}
|
||||
|
||||
type OutputParam struct {
|
||||
Code string `yaml:"code"`
|
||||
Type string `yaml:"type"`
|
||||
Sensitive bool `yaml:"sensitive,omitempty"`
|
||||
}
|
||||
|
||||
type OperationSpec struct {
|
||||
Name string `yaml:"name"`
|
||||
ID int `yaml:"id"`
|
||||
Kind string `yaml:"kind"`
|
||||
Action string `yaml:"action"`
|
||||
Subresource string `yaml:"subresource,omitempty"`
|
||||
Man string `yaml:"man,omitempty"`
|
||||
Params []ParamSpec `yaml:"params"`
|
||||
}
|
||||
|
||||
type ParamSpec struct {
|
||||
ID int `yaml:"id"`
|
||||
Code string `yaml:"code"`
|
||||
DataType string `yaml:"data_type,omitempty"`
|
||||
Required bool `yaml:"required"`
|
||||
Default interface{} `yaml:"default,omitempty"`
|
||||
ValueList []string `yaml:"value_list,omitempty"`
|
||||
RefSvcId *int `yaml:"ref_svc_id,omitempty"`
|
||||
Func string `yaml:"func,omitempty"`
|
||||
Regex string `yaml:"regex,omitempty"`
|
||||
UniqueScope string `yaml:"unique_scope,omitempty"`
|
||||
MaxLength *int `yaml:"maxlength,omitempty"`
|
||||
MinLength *int `yaml:"minlength,omitempty"`
|
||||
MaxValue interface{} `yaml:"maxvalue,omitempty"`
|
||||
MinValue interface{} `yaml:"minvalue,omitempty"`
|
||||
Descr string `yaml:"descr,omitempty"`
|
||||
Man string `yaml:"man,omitempty"`
|
||||
Sort *int `yaml:"sort,omitempty"`
|
||||
DependsOn interface{} `yaml:"depends_on,omitempty"`
|
||||
IsModifiable *bool `yaml:"is_modifiable,omitempty"`
|
||||
IsSensitive bool `yaml:"is_sensitive,omitempty"`
|
||||
}
|
||||
|
||||
func defaultOutputParams() []OutputParam {
|
||||
// Standard outputs expected by the provider core and docs.
|
||||
return []OutputParam{
|
||||
{Code: "state_params", Type: "map"},
|
||||
{Code: "state_out", Type: "map"},
|
||||
{Code: "state_params_flat", Type: "map"},
|
||||
{Code: "state_out_flat", Type: "map"},
|
||||
{Code: "vault_secrets", Type: "map", Sensitive: true},
|
||||
{Code: "vault_url", Type: "string"},
|
||||
{Code: "vault_user_path", Type: "string"},
|
||||
{Code: "vault_fields", Type: "list"},
|
||||
}
|
||||
}
|
||||
|
||||
func validateOutputDir(path string) error {
|
||||
// Guardrail: legacy ops YAML is deprecated; unified YAML only lives in resources_yaml.
|
||||
base := strings.ToLower(strings.TrimSpace(filepath.Base(path)))
|
||||
if base == "resources_ops_yaml" {
|
||||
return fmt.Errorf("invalid output dir %q: use resources_yaml for unified service specs", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newAPIClient(endpoint string, token string) *apiClient {
|
||||
// Short timeout prevents hanging forever on network or API stalls.
|
||||
return &apiClient{
|
||||
endpoint: endpoint,
|
||||
token: token,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeServiceName(raw string) string {
|
||||
// Service name must be filesystem-safe and ASCII for stable file naming.
|
||||
return normalizeIdentifier(raw)
|
||||
}
|
||||
|
||||
func normalizeOperationName(raw string) string {
|
||||
// Normalize operation names into snake_case used by generators.
|
||||
return normalizeIdentifier(raw)
|
||||
}
|
||||
|
||||
func normalizeIdentifier(raw string) string {
|
||||
// Convert to ASCII snake_case: letters/digits kept, everything else becomes underscore.
|
||||
// CamelCase is split into words by inserting underscores before uppercase letters.
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return ""
|
||||
}
|
||||
var out []rune
|
||||
lastUnderscore := false
|
||||
prevLowerOrDigit := false
|
||||
for _, r := range raw {
|
||||
if r >= 'A' && r <= 'Z' {
|
||||
if prevLowerOrDigit && !lastUnderscore {
|
||||
out = append(out, '_')
|
||||
}
|
||||
out = append(out, r+'a'-'A')
|
||||
lastUnderscore = false
|
||||
prevLowerOrDigit = true
|
||||
continue
|
||||
}
|
||||
if r >= 'a' && r <= 'z' {
|
||||
out = append(out, r)
|
||||
lastUnderscore = false
|
||||
prevLowerOrDigit = true
|
||||
continue
|
||||
}
|
||||
if r >= '0' && r <= '9' {
|
||||
out = append(out, r)
|
||||
lastUnderscore = false
|
||||
prevLowerOrDigit = true
|
||||
continue
|
||||
}
|
||||
// Any non-ASCII or punctuation becomes a separator.
|
||||
if !lastUnderscore && len(out) > 0 {
|
||||
out = append(out, '_')
|
||||
lastUnderscore = true
|
||||
}
|
||||
prevLowerOrDigit = false
|
||||
}
|
||||
result := strings.Trim(outToString(out), "_")
|
||||
return collapseUnderscores(result)
|
||||
}
|
||||
|
||||
func outToString(runes []rune) string {
|
||||
return string(runes)
|
||||
}
|
||||
|
||||
func collapseUnderscores(value string) string {
|
||||
if value == "" {
|
||||
return value
|
||||
}
|
||||
for strings.Contains(value, "__") {
|
||||
value = strings.ReplaceAll(value, "__", "_")
|
||||
}
|
||||
return strings.Trim(value, "_")
|
||||
}
|
||||
|
||||
func normalizeAPIEndpoint(raw string) string {
|
||||
// Accept base API URL with or without index.cfm; normalize to index.cfm.
|
||||
endpoint := strings.TrimSpace(raw)
|
||||
if endpoint == "" {
|
||||
return endpoint
|
||||
}
|
||||
if strings.HasSuffix(endpoint, "/index.cfm") {
|
||||
return endpoint
|
||||
}
|
||||
return strings.TrimRight(endpoint, "/") + "/index.cfm"
|
||||
}
|
||||
Reference in New Issue
Block a user