utils

package
v1.30.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2025 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CountMatchingFiles added in v1.17.1

func CountMatchingFiles(dirPath string, options DirectoryScanOptions) (int, error)

CountMatchingFiles faz uma varredura rápida para contar quantos arquivos em um diretório correspondem aos critérios das opções, sem ler seu conteúdo.

func DetectFileType

func DetectFileType(filePath string) string

DetectFileType detecta o tipo de arquivo com base na extensão

func ExpandPath

func ExpandPath(path string) (string, error)

ExpandPath expande o caractere ~ no início de um caminho para o diretório home do usuário. Se o caminho não começar com ~, ele é retornado sem modificações. A função não suporta a expansão de ~username, retornando um erro nesse caso.

func FormatDirectoryContent

func FormatDirectoryContent(files []FileInfo, maxTotalSize int64) string

FormatDirectoryContent formata o conteúdo de vários arquivos em uma única string organizada com separadores claros e formatação adequada para cada tipo de arquivo.

func GetEnvOrDefault

func GetEnvOrDefault(key, defaultValue string) string

GetEnvOrDefault retorna o valor da variável de ambiente ou um valor padrão se não estiver definida

func GetEnvVariablesSanitized added in v1.15.0

func GetEnvVariablesSanitized() string

GetEnvVariablesSanitized retorna variáveis de ambiente com valores sensíveis redigidos.

func GetFileBlame

func GetFileBlame(filepath string) (string, error)

Função auxiliar para obter blame de um arquivo

func GetFileDiff

func GetFileDiff(filepath string) (string, error)

Função auxiliar para obter diferenças específicas de um arquivo

func GetFileHistory

func GetFileHistory(filepath string) (string, error)

Função auxiliar para obter o histórico de um arquivo específico

func GetGitInfo

func GetGitInfo(executor CommandExecutor) (string, error)

GetGitInfo agora aceita um CommandExecutor.

func GetHomeDir

func GetHomeDir() (string, error)

GetHomeDir retorna o diretório home do usuário atual.

func GetShellConfigFilePath

func GetShellConfigFilePath(shellName string) string

GetShellConfigFilePath retorna o caminho do arquivo de configuração do shell com base no nome do shell.

func GetShellHistory

func GetShellHistory() (string, error)

GetShellHistory lê o arquivo de histórico do shell e retorna seu conteúdo.

func GetShellHistoryFile

func GetShellHistoryFile() (string, error)

GetShellHistoryFile retorna o caminho do arquivo de histórico do shell.

func GetUserShell

func GetUserShell() string

GetUserShell retorna o shell do usuário atual.

func InitializeLogger

func InitializeLogger() (*zap.Logger, error)

InitializeLogger configura e inicializa um logger robusto com base nas variáveis de ambiente. Em ambiente de desenvolvimento ('dev'), os logs são enviados para o console de forma colorida e legível, e também para um arquivo em formato JSON. Em ambiente de produção ('prod'), os logs são enviados apenas para o arquivo em formato JSON. Suporta rotação de logs com lumberjack.

func IsTemporaryError

func IsTemporaryError(err error) bool

IsTemporaryError verifica se o erro é temporário e pode ser retryado. Agora usa errors.Unwrap para desembrulhar e As para checar APIError com status 429 ou 5xx, além de timeouts.

func LogStartupInfo added in v1.10.1

func LogStartupInfo(logger *zap.Logger)

func NewHTTPClient

func NewHTTPClient(logger *zap.Logger, timeout time.Duration) *http.Client

NewHTTPClient cria um cliente HTTP com LoggingTransport e timeout configurado

func NewJSONReader

func NewJSONReader(data []byte) io.Reader

NewJSONReader cria um io.Reader a partir de um []byte para enviar em requisições HTTP

func ParseSize added in v1.19.1

func ParseSize(sizeStr string) (int64, error)

ParseSize converte uma string de tamanho legível (como "50MB") para bytes.

func ReadFileContent

func ReadFileContent(filePath string, maxSize int64) (string, error)

ReadFileContent lê o conteúdo de um arquivo, expandindo ~ para o diretório home, mostrando um indicador de progresso para arquivos grandes.

func Retry added in v1.27.1

func Retry[T any](ctx context.Context, logger *zap.Logger, maxAttempts int, initialBackoff time.Duration, fn func(context.Context) (T, error)) (T, error)

Retry executa uma função com retry exponencial para erros temporários. - maxAttempts: Número máximo de tentativas (lido de ENV ou default). - initialBackoff: Tempo inicial de espera entre tentativas (lido de ENV ou default). - fn: Função a executar, que recebe ctx e retorna um resultado genérico T e erro.

func SanitizeSensitiveText added in v1.15.0

func SanitizeSensitiveText(s string) string

SanitizeSensitiveText remove/mascara tokens em qualquer texto antes de ir para histórico/LLM

func ShouldSkipDir

func ShouldSkipDir(dirName string) bool

ShouldSkipDir verifica se um diretório deve ser ignorado

Types

type APIClient

type APIClient struct {
	// contains filtered or unexported fields
}

APIClient é um cliente HTTP especializado para APIs REST

func NewAPIClient

func NewAPIClient(logger *zap.Logger, baseURL string, headers map[string]string) *APIClient

NewAPIClient cria um novo cliente API com cabeçalhos padrão

func (*APIClient) Get

func (c *APIClient) Get(ctx context.Context, path string) ([]byte, error)

Get faz uma requisição GET

func (*APIClient) Post

func (c *APIClient) Post(ctx context.Context, path string, payload interface{}) ([]byte, error)

Post faz uma requisição POST

func (*APIClient) Request

func (c *APIClient) Request(ctx context.Context, method, path string, body []byte) ([]byte, error)

Request faz uma requisição HTTP com retry exponencial

type APIError added in v1.27.1

type APIError struct {
	StatusCode int
	Message    string
}

APIError é um erro estruturado para respostas HTTP com status code.

func (*APIError) Error added in v1.27.1

func (e *APIError) Error() string

type CommandExecutor added in v1.18.0

type CommandExecutor interface {
	Run(name string, arg ...string) error
	Output(name string, arg ...string) ([]byte, error)
}

CommandExecutor define uma interface para executar comandos. Isso nos permite mockar a execução de comandos nos testes.

func NewOSCommandExecutor added in v1.18.0

func NewOSCommandExecutor() CommandExecutor

NewOSCommandExecutor cria um novo executor de comandos do sistema operacional.

type DirectoryScanOptions

type DirectoryScanOptions struct {
	MaxTotalSize      int64 // Tamanho máximo do conteúdo total (em bytes)
	MaxFilesToProcess int   // Número máximo de arquivos a processar
	Logger            *zap.Logger
	Extensions        []string            // Extensões de arquivo a incluir (vazio = todas)
	ExcludeDirs       []string            // Diretórios a excluir
	ExcludePatterns   []string            // Padrões de nome de arquivo a excluir (ex: "*.tmp")
	IncludeHidden     bool                // Incluir arquivos/diretórios ocultos?
	OnFileProcessed   func(info FileInfo) // Callback para cada arquivo processado
}

DirectoryScanOptions configura opções para escaneamento de diretórios

func DefaultDirectoryScanOptions

func DefaultDirectoryScanOptions(logger *zap.Logger) DirectoryScanOptions

DefaultDirectoryScanOptions retorna opções padrão para escaneamento

type FileInfo

type FileInfo struct {
	Path    string
	Content string
	Size    int64
	Type    string
}

FileInfo armazena informações e conteúdo de um arquivo

func ProcessDirectory

func ProcessDirectory(dirPath string, options DirectoryScanOptions) ([]FileInfo, error)

ProcessDirectory processa um diretório recursivamente de forma concorrente e segura.

type LoggingTransport

type LoggingTransport struct {
	Logger      *zap.Logger
	Transport   http.RoundTripper
	MaxBodySize int
}

LoggingTransport é um http.RoundTripper que adiciona logs às requisições e respostas

func (*LoggingTransport) RoundTrip

func (t *LoggingTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implementa a interface http.RoundTripper

type OSCommandExecutor added in v1.18.0

type OSCommandExecutor struct{}

OSCommandExecutor é a implementação real que usa os/exec.

func (*OSCommandExecutor) Output added in v1.18.0

func (e *OSCommandExecutor) Output(name string, arg ...string) ([]byte, error)

Output executa um comando e retorna sua saída padrão.

func (*OSCommandExecutor) Run added in v1.18.0

func (e *OSCommandExecutor) Run(name string, arg ...string) error

Run executa um comando e espera ele terminar.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL