ReadFileContent lê o conteúdo de um arquivo, expandindo ~ para o diretório home, mostrando um indicador de progresso para arquivos grandes.
(filePath string, maxSize int64)
| 54 | // ReadFileContent lê o conteúdo de um arquivo, expandindo ~ para o diretório home, |
| 55 | // mostrando um indicador de progresso para arquivos grandes. |
| 56 | func ReadFileContent(filePath string, maxSize int64) (string, error) { |
| 57 | // Definir um limite de tamanho padrão (1MB) se maxSize não for especificado |
| 58 | if maxSize == 0 { |
| 59 | maxSize = 1 * 1024 * 1024 // 1MB |
| 60 | } |
| 61 | |
| 62 | // Expandir ~ para o diretório home |
| 63 | expandedPath, err := ExpandPath(filePath) |
| 64 | if err != nil { |
| 65 | return "", err |
| 66 | } |
| 67 | |
| 68 | // Tornar o caminho absoluto |
| 69 | absPath, err := filepath.Abs(expandedPath) |
| 70 | if err != nil { |
| 71 | return "", fmt.Errorf("não foi possível determinar o caminho absoluto: %w", err) |
| 72 | } |
| 73 | |
| 74 | // Verificar se o arquivo existe |
| 75 | info, err := os.Stat(absPath) |
| 76 | if os.IsNotExist(err) { |
| 77 | return "", fmt.Errorf("o arquivo não existe: %s", absPath) |
| 78 | } |
| 79 | if err != nil { |
| 80 | return "", fmt.Errorf("erro ao acessar o arquivo: %w", err) |
| 81 | } |
| 82 | |
| 83 | // Verificar se é um arquivo regular |
| 84 | if !info.Mode().IsRegular() { |
| 85 | return "", fmt.Errorf("o caminho não aponta para um arquivo regular: %s", absPath) |
| 86 | } |
| 87 | |
| 88 | // L1: Block access to known sensitive paths |
| 89 | if IsSensitivePath(absPath) { |
| 90 | return "", fmt.Errorf("access denied: %s is a sensitive path", absPath) |
| 91 | } |
| 92 | |
| 93 | // Verificar o tamanho do arquivo |
| 94 | if info.Size() > maxSize { |
| 95 | return "", fmt.Errorf("o arquivo '%s' é muito grande (%.2f MB, limite de %.2f MB)", |
| 96 | absPath, float64(info.Size())/1024/1024, float64(maxSize)/1024/1024) |
| 97 | } |
| 98 | |
| 99 | // Para arquivos grandes, mostrar um indicador de progresso |
| 100 | showProgress := info.Size() > 1024*1024 // Maior que 1MB |
| 101 | |
| 102 | var content string |
| 103 | |
| 104 | if showProgress { |
| 105 | // Ler o conteúdo com indicador de progresso |
| 106 | file, err := os.Open(absPath) //#nosec G304 -- path supplied by user/agent through validated tool surface (boundary check upstream) |
| 107 | if err != nil { |
| 108 | return "", fmt.Errorf("erro ao abrir o arquivo: %w", err) |
| 109 | } |
| 110 | defer func() { _ = file.Close() }() |
| 111 | |
| 112 | var data strings.Builder |
| 113 | buffer := make([]byte, 8192) // 8KB por vez |