Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

6.4 KB
Raw Blame
//
//  Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

package utility

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

// JSONFloat64 is a float64 that always marshals with a decimal point.
// 0 encodes as 0.0. The value itself is kept, so progress of 0.96 stays 0.96.
type JSONFloat64 float64

func (f JSONFloat64) MarshalJSON() ([]byte, error) {
	s := strconv.FormatFloat(float64(f), 'f', -1, 64)
	if !strings.Contains(s, ".") {
		s += ".0"
	}
	return []byte(s), nil
}

// GetProjectBaseDirectory returns the current working directory.
// If an error occurs while getting the current directory, it returns ".".
//
// Returns:
//   - string: The current working directory path, or "." if an error occurs.
//
// Example:
//
//	baseDir := utility.GetProjectBaseDirectory()
//	configPath := filepath.Join(baseDir, "conf", "config.json")
func GetProjectBaseDirectory() string {
	cwd, err := os.Getwd()
	if err != nil {
		return "."
	}
	return cwd
}

// ConfigBool reads a Python JSON bool/string flag.
func ConfigBool[M ~map[string]any](config M, key string) bool {
	value, ok := config[key]
	if !ok {
		return false
	}
	switch typed := value.(type) {
	case bool:
		return typed
	case string:
		return typed == "1" || typed == "true" || typed == "TRUE"
	default:
		return false
	}
}

// FormatTimeToString converts time.Time to string in specified format
func FormatTimeToString(t *time.Time, format string) interface{} {
	if t == nil {
		return nil
	}
	return t.Format(format)
}

// ConvertHexToPositionIntArray converts hex string to position int array (grouped by 5)
func ConvertHexToPositionIntArray(hexStr string) interface{} {
	if hexStr == "" {
		return nil
	}

	parts := strings.Split(hexStr, "_")
	var intVals []int
	for _, part := range parts {
		if part == "" {
			continue
		}
		val, err := strconv.ParseInt(part, 16, 64)
		if err != nil {
			continue
		}
		intVals = append(intVals, int(val))
	}

	if len(intVals) == 0 {
		return nil
	}

	// Group by 5 elements
	var result [][]int
	for i := 0; i < len(intVals); i += 5 {
		end := min(i+5, len(intVals))
		result = append(result, intVals[i:end])
	}

	return result
}

// ConvertHexToIntArray converts hex string to int array (split by "_")
func ConvertHexToIntArray(hexStr string) interface{} {
	if hexStr == "" {
		return nil
	}

	parts := strings.Split(hexStr, "_")
	var result []int
	for _, part := range parts {
		if part == "" {
			continue
		}
		val, err := strconv.ParseInt(part, 16, 64)
		if err != nil {
			continue
		}
		result = append(result, int(val))
	}

	if len(result) == 0 {
		return nil
	}
	return result
}

// ConvertIntArrayToHex converts int array to hex string
// e.g. [1, 2] -> "00000001_00000002"
func ConvertIntArrayToHex(list []interface{}) string {
	var hexParts []string
	for _, num := range list {
		if n, ok := num.(float64); ok {
			hexParts = append(hexParts, fmt.Sprintf("%08x", int64(n)))
		} else if n, ok := num.(int64); ok {
			hexParts = append(hexParts, fmt.Sprintf("%08x", n))
		} else if n, ok := num.(int); ok {
			hexParts = append(hexParts, fmt.Sprintf("%08x", n))
		}
	}
	return strings.Join(hexParts, "_")
}

// IsEmpty checks if value is empty (nil, empty array, or empty string)
func IsEmpty(v interface{}) bool {
	if v == nil {
		return true
	}
	if arr, ok := v.([]interface{}); ok {
		return len(arr) == 0
	}
	if arr, ok := v.([]string); ok {
		return len(arr) == 0
	}
	if arr, ok := v.([]int); ok {
		return len(arr) == 0
	}
	if strVal, ok := v.(string); ok && strVal == "" {
		return true
	}
	return false
}

// IsNumericValue checks if a value is numeric (int, uint, float, or numeric string)
func IsNumericValue(v interface{}) bool {
	if v == nil {
		return false
	}
	switch val := v.(type) {
	case int, int8, int16, int32, int64:
		return true
	case uint, uint8, uint16, uint32, uint64:
		return true
	case float32, float64:
		return true
	case string:
		_, err := strconv.ParseFloat(val, 64)
		return err == nil
	default:
		return false
	}
}

// SetFieldArray copies value to dest key, or sets empty array if value is empty
func SetFieldArray(result map[string]interface{}, destKey string, v interface{}) {
	if IsEmpty(v) {
		result[destKey] = []interface{}{}
	} else {
		result[destKey] = v
	}
}

// ConvertToStringSlice converts an interface{} to []string
// e.g. []interface{}{"a", "b", "c"} -> []string{"a", "b", "c"}
// e.g. "hello" -> []string{"hello"}
func ConvertToStringSlice(v interface{}) []string {
	if v == nil {
		return nil
	}
	switch val := v.(type) {
	case []interface{}:
		result := make([]string, 0, len(val))
		for _, item := range val {
			if s, ok := item.(string); ok {
				result = append(result, s)
			} else {
				result = append(result, fmt.Sprintf("%v", item))
			}
		}
		return result
	case []string:
		return val
	case string:
		return []string{val}
	default:
		return nil
	}
}

// ConvertToString converts an interface{} to space-separated string
// For []interface{}, joins elements with space; for other types, returns string representation
// e.g. []interface{}{"a", "b", "c"} -> "a b c"
// e.g. "hello" -> "hello"
func ConvertToString(v interface{}) string {
	if v == nil {
		return ""
	}
	switch val := v.(type) {
	case []interface{}:
		parts := make([]string, 0, len(val))
		for _, item := range val {
			if s, ok := item.(string); ok {
				parts = append(parts, s)
			} else {
				parts = append(parts, fmt.Sprintf("%v", item))
			}
		}
		return strings.Join(parts, " ")
	default:
		return fmt.Sprintf("%v", v)
	}
}

// ConvertMapToJSONString converts a map to JSON string for Infinity JSON columns
// If v is a map[string]interface{}, marshals it to JSON string
// If v is nil, returns "{}"
// Otherwise returns v as-is
//
// e.g. map[string]interface{}{"key": "value"}) -> `"{\"key\":\"value\"}"`
func ConvertMapToJSONString(v interface{}) interface{} {
	if v == nil {
		return "{}"
	}
	if m, ok := v.(map[string]interface{}); ok {
		jsonBytes, _ := json.Marshal(m)
		return string(jsonBytes)
	}
	return v
}