Skip to content

Commit a2c6969

Browse files
committed
v0.1.0
1 parent 58efe9d commit a2c6969

File tree

9 files changed

+1346
-0
lines changed

9 files changed

+1346
-0
lines changed

CHANGELOG.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
## [Unreleased]
9+
10+
## [0.1.0] - 2025-12-07
11+
12+
### Added
13+
- **Initial Release**: First stable release of fileprep library
14+
- **File Format Support**: CSV, TSV, LTSV, Parquet, Excel (.xlsx) with compression support (gzip, bzip2, xz, zstd)
15+
- **Preprocessing Tags (`prep`)**: Comprehensive struct tag-based preprocessing
16+
- Basic preprocessors: `trim`, `ltrim`, `rtrim`, `lowercase`, `uppercase`, `default`
17+
- String transformation: `replace`, `prefix`, `suffix`, `truncate`, `strip_html`, `strip_newline`, `collapse_space`
18+
- Character filtering: `remove_digits`, `remove_alpha`, `keep_digits`, `keep_alpha`, `trim_set`
19+
- Padding: `pad_left`, `pad_right`
20+
- Advanced: `normalize_unicode`, `nullify`, `coerce`, `fix_scheme`, `regex_replace`
21+
- **Validation Tags (`validate`)**: Compatible with go-playground/validator syntax
22+
- Basic validators: `required`, `boolean`
23+
- Character type validators: `alpha`, `alphaunicode`, `alphaspace`, `alphanumeric`, `alphanumunicode`, `numeric`, `number`, `ascii`, `printascii`, `multibyte`
24+
- Numeric comparison: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `min`, `max`, `len`
25+
- String validators: `oneof`, `lowercase`, `uppercase`, `eq_ignore_case`, `ne_ignore_case`
26+
- String content: `startswith`, `startsnotwith`, `endswith`, `endsnotwith`, `contains`, `containsany`, `containsrune`, `excludes`, `excludesall`, `excludesrune`
27+
- Format validators: `email`, `uri`, `url`, `http_url`, `https_url`, `url_encoded`, `datauri`, `uuid`
28+
- Network validators: `ip_addr`, `ip4_addr`, `ip6_addr`, `cidr`, `cidrv4`, `cidrv6`, `fqdn`, `hostname`, `hostname_rfc1123`, `hostname_port`
29+
- Cross-field validators: `eqfield`, `nefield`, `gtfield`, `gtefield`, `ltfield`, `ltefield`, `fieldcontains`, `fieldexcludes`
30+
- **Name-Based Column Binding**: Automatic snake_case conversion with `name` tag override
31+
- **filesql Integration**: Returns `io.Reader` for direct use with filesql
32+
- **Detailed Error Reporting**: Row and column information for each validation error
33+
34+
### Technical Details
35+
- **Memory Optimization**: In-place record processing, pre-allocated output buffers, streaming parsers for CSV/TSV/LTSV
36+
- **XLSX Streaming**: Uses excelize streaming API to reduce memory usage for large files
37+
- **Parquet Buffer Reuse**: Reusable row buffer across row groups to reduce allocations
38+
- **Format-Specific Limitations**:
39+
- XLSX: Only the first sheet is processed
40+
- LTSV: Maximum line size is 10MB

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2025 CHIKAMATSU Naohiro
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
[![MultiPlatformUnitTest](https://github.com/nao1215/fileprep/actions/workflows/unit_test.yml/badge.svg)](https://github.com/nao1215/fileprep/actions/workflows/unit_test.yml)
66
![Coverage](https://raw.githubusercontent.com/nao1215/octocovs-central-repo/main/badges/nao1215/fileprep/coverage.svg)
77

8+
[日本語](doc/ja/README.md) | [Español](doc/es/README.md) | [Français](doc/fr/README.md) | [한국어](doc/ko/README.md) | [Русский](doc/ru/README.md) | [中文](doc/zh-cn/README.md)
9+
810
![fileprep-logo](./doc/images/fileprep-logo-small.png)
911

1012
**fileprep** is a Go library for cleaning, normalizing, and validating structured data—CSV, TSV, LTSV, Parquet, and Excel—through lightweight struct-tag rules, with seamless support for gzip, bzip2, xz, and zstd streams.

doc/es/README.md

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
# fileprep
2+
3+
[![Go Reference](https://pkg.go.dev/badge/github.com/nao1215/fileprep.svg)](https://pkg.go.dev/github.com/nao1215/fileprep)
4+
[![Go Report Card](https://goreportcard.com/badge/github.com/nao1215/fileprep)](https://goreportcard.com/report/github.com/nao1215/fileprep)
5+
[![MultiPlatformUnitTest](https://github.com/nao1215/fileprep/actions/workflows/unit_test.yml/badge.svg)](https://github.com/nao1215/fileprep/actions/workflows/unit_test.yml)
6+
![Coverage](https://raw.githubusercontent.com/nao1215/octocovs-central-repo/main/badges/nao1215/fileprep/coverage.svg)
7+
8+
[English](../../README.md) | [日本語](../ja/README.md) | [Français](../fr/README.md) | [한국어](../ko/README.md) | [Русский](../ru/README.md) | [中文](../zh-cn/README.md)
9+
10+
![fileprep-logo](../images/fileprep-logo-small.png)
11+
12+
**fileprep** es una biblioteca de Go para limpiar, normalizar y validar datos estructurados (CSV, TSV, LTSV, Parquet y Excel) mediante reglas ligeras basadas en etiquetas struct, con soporte transparente para flujos gzip, bzip2, xz y zstd.
13+
14+
## ¿Por qué fileprep?
15+
16+
Desarrollé [nao1215/filesql](https://github.com/nao1215/filesql), que permite ejecutar consultas SQL en archivos como CSV, TSV, LTSV, Parquet y Excel. También creé [nao1215/csv](https://github.com/nao1215/csv) para la validación de archivos CSV.
17+
18+
Mientras estudiaba aprendizaje automático, me di cuenta: "Si extiendo [nao1215/csv](https://github.com/nao1215/csv) para soportar los mismos formatos de archivo que [nao1215/filesql](https://github.com/nao1215/filesql), podría combinarlos para realizar operaciones tipo ETL". Esta idea llevó a la creación de **fileprep**: una biblioteca que conecta el preprocesamiento/validación de datos con las consultas SQL basadas en archivos.
19+
20+
## Características
21+
22+
- Soporte de múltiples formatos: CSV, TSV, LTSV, Parquet, Excel (.xlsx)
23+
- Soporte de compresión: gzip (.gz), bzip2 (.bz2), xz (.xz), zstd (.zst)
24+
- Vinculación de columnas por nombre: Los campos coinciden automáticamente con nombres de columna en `snake_case`, personalizable con la etiqueta `name`
25+
- Preprocesamiento basado en etiquetas struct (`prep`): trim, lowercase, uppercase, valores por defecto
26+
- Validación basada en etiquetas struct (`validate`): required y más
27+
- Integración con [filesql](https://github.com/nao1215/filesql): Devuelve `io.Reader` para uso directo con filesql
28+
- Informe detallado de errores: Información de fila y columna para cada error
29+
30+
## Instalación
31+
32+
```bash
33+
go get github.com/nao1215/fileprep
34+
```
35+
36+
## Requisitos
37+
38+
- Versión de Go: 1.24 o posterior
39+
- Sistemas Operativos:
40+
- Linux
41+
- macOS
42+
- Windows
43+
44+
## Inicio Rápido
45+
46+
```go
47+
package main
48+
49+
import (
50+
"fmt"
51+
"os"
52+
"strings"
53+
54+
"github.com/nao1215/fileprep"
55+
)
56+
57+
// User representa un registro de usuario con preprocesamiento y validación
58+
type User struct {
59+
Name string `prep:"trim" validate:"required"`
60+
Email string `prep:"trim,lowercase"`
61+
Age string
62+
}
63+
64+
func main() {
65+
csvData := `name,email,age
66+
John Doe ,[email protected],30
67+
Jane Smith,[email protected],25
68+
`
69+
70+
processor := fileprep.NewProcessor(fileprep.FileTypeCSV)
71+
var users []User
72+
73+
reader, result, err := processor.Process(strings.NewReader(csvData), &users)
74+
if err != nil {
75+
fmt.Printf("Error: %v\n", err)
76+
return
77+
}
78+
79+
fmt.Printf("Procesadas %d filas, %d válidas\n", result.RowCount, result.ValidRowCount)
80+
81+
for _, user := range users {
82+
fmt.Printf("Nombre: %q, Email: %q\n", user.Name, user.Email)
83+
}
84+
85+
// reader puede pasarse directamente a filesql
86+
_ = reader
87+
}
88+
```
89+
90+
Salida:
91+
```
92+
Procesadas 2 filas, 2 válidas
93+
Nombre: "John Doe", Email: "[email protected]"
94+
Nombre: "Jane Smith", Email: "[email protected]"
95+
```
96+
97+
## Etiquetas de Preprocesamiento (`prep`)
98+
99+
Se pueden combinar múltiples etiquetas: `prep:"trim,lowercase,default=N/A"`
100+
101+
### Preprocesadores Básicos
102+
103+
| Etiqueta | Descripción | Ejemplo |
104+
|----------|-------------|---------|
105+
| `trim` | Eliminar espacios al inicio/final | `prep:"trim"` |
106+
| `ltrim` | Eliminar espacios al inicio | `prep:"ltrim"` |
107+
| `rtrim` | Eliminar espacios al final | `prep:"rtrim"` |
108+
| `lowercase` | Convertir a minúsculas | `prep:"lowercase"` |
109+
| `uppercase` | Convertir a mayúsculas | `prep:"uppercase"` |
110+
| `default=value` | Establecer valor por defecto si está vacío | `prep:"default=N/A"` |
111+
112+
### Transformación de Cadenas
113+
114+
| Etiqueta | Descripción | Ejemplo |
115+
|----------|-------------|---------|
116+
| `replace=old:new` | Reemplazar todas las ocurrencias | `prep:"replace=;:,"` |
117+
| `prefix=value` | Agregar cadena al inicio | `prep:"prefix=ID_"` |
118+
| `suffix=value` | Agregar cadena al final | `prep:"suffix=_END"` |
119+
| `truncate=N` | Limitar a N caracteres | `prep:"truncate=100"` |
120+
| `strip_html` | Eliminar etiquetas HTML | `prep:"strip_html"` |
121+
| `strip_newline` | Eliminar saltos de línea | `prep:"strip_newline"` |
122+
| `collapse_space` | Colapsar múltiples espacios en uno | `prep:"collapse_space"` |
123+
124+
## Etiquetas de Validación (`validate`)
125+
126+
Se pueden combinar múltiples etiquetas: `validate:"required,email"`
127+
128+
### Validadores Básicos
129+
130+
| Etiqueta | Descripción | Ejemplo |
131+
|----------|-------------|---------|
132+
| `required` | El campo no debe estar vacío | `validate:"required"` |
133+
| `boolean` | Debe ser true, false, 0 o 1 | `validate:"boolean"` |
134+
| `email` | Dirección de correo válida | `validate:"email"` |
135+
| `url` | URL válida | `validate:"url"` |
136+
| `uuid` | UUID válido | `validate:"uuid"` |
137+
138+
### Validadores de Campo Cruzado
139+
140+
| Etiqueta | Descripción | Ejemplo |
141+
|----------|-------------|---------|
142+
| `eqfield=Field` | Valor igual a otro campo | `validate:"eqfield=Password"` |
143+
| `nefield=Field` | Valor diferente a otro campo | `validate:"nefield=OldPassword"` |
144+
145+
## Formatos de Archivo Soportados
146+
147+
| Formato | Extensión | Comprimido |
148+
|---------|-----------|------------|
149+
| CSV | `.csv` | `.csv.gz`, `.csv.bz2`, `.csv.xz`, `.csv.zst` |
150+
| TSV | `.tsv` | `.tsv.gz`, `.tsv.bz2`, `.tsv.xz`, `.tsv.zst` |
151+
| LTSV | `.ltsv` | `.ltsv.gz`, `.ltsv.bz2`, `.ltsv.xz`, `.ltsv.zst` |
152+
| Excel | `.xlsx` | `.xlsx.gz`, `.xlsx.bz2`, `.xlsx.xz`, `.xlsx.zst` |
153+
| Parquet | `.parquet` | `.parquet.gz`, `.parquet.bz2`, `.parquet.xz`, `.parquet.zst` |
154+
155+
**Nota sobre archivos Excel**: Solo se procesa la **primera hoja**. Las hojas siguientes en libros de trabajo de múltiples hojas serán ignoradas.
156+
157+
## Uso de Memoria
158+
159+
fileprep carga el **archivo completo en memoria** para su procesamiento. Esto permite acceso aleatorio y operaciones de múltiples pasadas, pero tiene implicaciones para archivos grandes:
160+
161+
| Tamaño de Archivo | Memoria Aprox. | Recomendación |
162+
|-------------------|----------------|---------------|
163+
| < 100 MB | ~2-3x tamaño del archivo | Procesamiento directo |
164+
| 100-500 MB | ~500 MB - 1.5 GB | Monitorear memoria, considerar fragmentación |
165+
| > 500 MB | > 1.5 GB | Dividir archivos o usar alternativas de streaming |
166+
167+
## Proyectos Relacionados
168+
169+
- [nao1215/filesql](https://github.com/nao1215/filesql) - Driver SQL para CSV, TSV, LTSV, Parquet, Excel
170+
- [nao1215/csv](https://github.com/nao1215/csv) - Lectura de CSV con validación y DataFrame simple
171+
172+
## Contribuciones
173+
174+
¡Las contribuciones son bienvenidas! Por favor consulte la [Guía de Contribución](../../CONTRIBUTING.md) para más detalles.
175+
176+
## Soporte
177+
178+
Si encuentra útil este proyecto, por favor considere:
179+
180+
- Darle una estrella en GitHub - ayuda a otros a descubrir el proyecto
181+
- [Convertirse en patrocinador](https://github.com/sponsors/nao1215) - su apoyo mantiene vivo el proyecto
182+
183+
## Licencia
184+
185+
Este proyecto está licenciado bajo la Licencia MIT - vea el archivo [LICENSE](../../LICENSE) para más detalles.

0 commit comments

Comments
 (0)