convertcontent2utf8

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2025 License: MIT Imports: 7 Imported by: 0

README

ConvertContent2UTF8

Go Report Card GoDoc GitHub release

一个专注于文本文档UTF8编码转换的Go语言库,基于encoding-processor构建,提供批量处理和进度监控功能。

English | 中文

✨ 特性

  • 🔄 单文件转换: 支持单个文件的编码转换
  • 📁 批量处理: 支持多文件批量转换,内置并发控制
  • 🌊 目录递归: 支持目录递归遍历和转换
  • 📊 进度监控: 实时进度回调,支持自定义进度显示
  • ⚙️ 高度可配置: 丰富的配置选项,满足不同场景需求
  • 🛡️ 完善错误处理: 结构化错误信息和恢复机制
  • 🔍 智能编码检测: 基于encoding-processor的智能编码检测
  • 💾 安全备份: 支持自动备份和文件恢复
  • 🚀 高性能: 并发处理,支持大规模文件转换

📦 安装

go get github.com/mirbf/ConvertContent2UTF8

🚀 快速开始

基础使用
package main

import (
    "fmt"
    "log"
    
    "github.com/mirbf/ConvertContent2UTF8"
)

func main() {
    // 单文件转换
    result, err := ConvertContent2UTF8.ConvertFile("input.txt", "output.txt")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("转换完成: %s -> %s\n", result.SourceEncoding, result.TargetEncoding)
}
批量文件转换
files := []string{"file1.txt", "file2.txt", "file3.txt"}

result, err := ConvertContent2UTF8.ConvertFiles(files,
    ConvertContent2UTF8.WithOverwrite(true),
    ConvertContent2UTF8.WithConcurrency(8),
)

if err != nil {
    log.Fatal(err)
}

fmt.Printf("处理完成: 成功 %d, 失败 %d\n", 
    result.SuccessfulFiles, result.FailedFiles)
目录递归转换
result, err := ConvertContent2UTF8.ConvertDirectory("/path/to/directory",
    ConvertContent2UTF8.WithRecursive(true),
    ConvertContent2UTF8.WithFileFilter(func(filename string) bool {
        return strings.HasSuffix(filename, ".txt") || 
               strings.HasSuffix(filename, ".md")
    }),
)
带进度回调的转换
result, err := ConvertContent2UTF8.ConvertFiles(files,
    ConvertContent2UTF8.WithProgress(func(p ConvertContent2UTF8.Progress) {
        percentage := float64(p.ProcessedFiles) / float64(p.TotalFiles) * 100
        fmt.Printf("进度: %.1f%% - %s [%s]\n", 
            percentage, p.CurrentFile, p.Status)
        
        if p.EstimatedTime > 0 {
            fmt.Printf("预计剩余时间: %v\n", p.EstimatedTime)
        }
    }),
)

📚 API 接口

核心函数
// 单文件转换
func ConvertFile(inputFile, outputFile string, options ...Option) (*ConvertResult, error)

// 批量文件转换  
func ConvertFiles(files []string, options ...Option) (*BatchResult, error)

// 目录递归转换
func ConvertDirectory(dirPath string, options ...Option) (*BatchResult, error)
配置选项
选项 说明 默认值
WithProgress(callback) 进度回调函数
WithTargetEncoding(encoding) 目标编码 UTF-8
WithConcurrency(limit) 并发限制 4
WithFileFilter(filter) 文件过滤器 .txt文件
WithBackup(create) 创建备份 true
WithOverwrite(overwrite) 覆盖已存在文件 false
WithMinConfidence(confidence) 最小检测置信度 0.8
WithDryRun(dryRun) 试运行模式 false
WithSkipHidden(skip) 跳过隐藏文件 true
WithRecursive(recursive) 递归处理目录 false
WithMaxFileSize(size) 最大文件大小限制 100MB

📊 数据结构

Progress 进度信息
type Progress struct {
    CurrentFile    string         // 当前处理的文件
    ProcessedFiles int            // 已处理文件数
    TotalFiles     int            // 总文件数
    Status         ProgressStatus // 当前状态
    StartTime      time.Time      // 开始时间
    ElapsedTime    time.Duration  // 已耗时
    EstimatedTime  time.Duration  // 预计剩余时间
    ProcessedBytes int64          // 已处理字节数
    ErrorCount     int            // 错误数量
}
ConvertResult 转换结果
type ConvertResult struct {
    InputFile           string        // 输入文件
    OutputFile          string        // 输出文件
    SourceEncoding      string        // 源编码
    TargetEncoding      string        // 目标编码
    BytesProcessed      int64         // 处理字节数
    ProcessingTime      time.Duration // 处理时间
    DetectionConfidence float64       // 检测置信度
    BackupFile          string        // 备份文件
}
BatchResult 批量处理结果
type BatchResult struct {
    TotalFiles      int              // 总文件数
    ProcessedFiles  int              // 已处理文件数
    SuccessfulFiles int              // 成功文件数
    FailedFiles     int              // 失败文件数
    SkippedFiles    int              // 跳过文件数
    TotalBytes      int64            // 总字节数
    ProcessingTime  time.Duration    // 处理时间
    Results         []*ConvertResult // 详细结果
    Errors          []FileError      // 错误列表
}

🔤 支持的编码

基于 encoding-processor,支持以下编码格式:

  • Unicode: UTF-8, UTF-16, UTF-16LE, UTF-16BE, UTF-32*, UTF-32LE*, UTF-32BE*
  • 中文: GBK, GB2312, GB18030, BIG5
  • 日文: Shift_JIS, EUC-JP
  • 韩文: EUC-KR
  • 西欧: ISO-8859-1, ISO-8859-2, ISO-8859-5, ISO-8859-15
  • Windows: Windows-1250, Windows-1251, Windows-1252, Windows-1254
  • 其他: KOI8-R, CP866, Macintosh

💡 使用示例

查看 examples/main.go 了解完整的使用示例。

运行示例:

cd examples
go run main.go

🧪 测试

# 运行所有测试
go test -v

# 运行性能测试
go test -bench=.

# 查看测试覆盖率
go test -cover

# 并发安全测试
go test -race

🎯 设计原则

  • 专注职责: 专注于批量处理和用户便利性,编码检测和转换依赖成熟的encoding-processor库
  • 并发安全: 所有公共接口都支持并发调用
  • 错误透明: 完善的错误处理和恢复机制
  • 进度可视: 详细的进度信息和回调支持
  • 配置灵活: 丰富的配置选项满足不同场景需求

📋 依赖

  • Go: 1.20+
  • github.com/mirbf/encoding-processor: v0.3.0+ - 编码检测和转换核心库
版本兼容性

本库要求 encoding-processor 最低版本为 v0.3.0,这确保了:

  • 智能编码检测功能的可用性
  • API 稳定性和向后兼容
  • 使用者可以安全升级到 v0.3.x 的任意版本

🤝 贡献

欢迎提交 Issue 和 Pull Request!请阅读 CONTRIBUTING.md 了解贡献指南。

📜 许可证

MIT License

🆕 更新日志

查看 CHANGELOG.md 了解版本更新记录。

🔒 安全

查看 SECURITY.md 了解安全政策和最佳实践。


⭐ 如果这个项目对你有帮助,请给我们一个 star!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BatchResult

type BatchResult struct {
	TotalFiles      int              `json:"total_files"`
	ProcessedFiles  int              `json:"processed_files"`
	SuccessfulFiles int              `json:"successful_files"`
	FailedFiles     int              `json:"failed_files"`
	SkippedFiles    int              `json:"skipped_files"`
	TotalBytes      int64            `json:"total_bytes"`
	ProcessingTime  time.Duration    `json:"processing_time"`
	Results         []*ConvertResult `json:"results"`
	Errors          []FileError      `json:"errors,omitempty"`
}

BatchResult 批量转换结果

func ConvertDirectory

func ConvertDirectory(dirPath string, options ...Option) (*BatchResult, error)

ConvertDirectory 递归转换目录中的文件

func ConvertFiles

func ConvertFiles(files []string, options ...Option) (*BatchResult, error)

ConvertFiles 批量转换文件

type Config

type Config struct {
	// 目标编码,默认UTF-8
	TargetEncoding string

	// 进度回调函数
	ProgressCallback func(Progress)

	// 并发限制,默认为4
	ConcurrencyLimit int

	// 文件过滤器
	FileFilter func(string) bool

	// encoding-processor选项
	CreateBackup      bool
	OverwriteExisting bool
	MinConfidence     float64
	DryRun            bool

	// 其他选项
	SkipHidden  bool  // 跳过隐藏文件
	Recursive   bool  // 目录递归处理
	MaxFileSize int64 // 最大文件大小限制
}

Config 配置结构

type ConvertResult

type ConvertResult struct {
	InputFile           string                      `json:"input_file"`
	OutputFile          string                      `json:"output_file"`
	SourceEncoding      string                      `json:"source_encoding"`
	TargetEncoding      string                      `json:"target_encoding"`
	BytesProcessed      int64                       `json:"bytes_processed"`
	ProcessingTime      time.Duration               `json:"processing_time"`
	DetectionConfidence float64                     `json:"detection_confidence"`
	BackupFile          string                      `json:"backup_file,omitempty"`
	ProcessorResult     *encoding.FileProcessResult `json:"-"` // 底层库结果
}

ConvertResult 单文件转换结果

func ConvertFile

func ConvertFile(inputFile, outputFile string, options ...Option) (*ConvertResult, error)

ConvertFile 转换单个文件

type FileError

type FileError struct {
	File      string    `json:"file"`
	Operation string    `json:"operation"`
	Error     string    `json:"error"`
	Timestamp time.Time `json:"timestamp"`
}

FileError 文件处理错误

type Option

type Option func(*Config)

Option 配置选项函数类型

func WithBackup

func WithBackup(create bool) Option

WithBackup 设置是否创建备份

func WithConcurrency

func WithConcurrency(limit int) Option

WithConcurrency 设置并发限制

func WithDryRun

func WithDryRun(dryRun bool) Option

WithDryRun 设置试运行模式

func WithFileFilter

func WithFileFilter(filter func(string) bool) Option

WithFileFilter 设置文件过滤器

func WithMaxFileSize

func WithMaxFileSize(size int64) Option

WithMaxFileSize 设置最大文件大小限制

func WithMinConfidence

func WithMinConfidence(confidence float64) Option

WithMinConfidence 设置最小检测置信度

func WithOverwrite

func WithOverwrite(overwrite bool) Option

WithOverwrite 设置是否覆盖已存在文件

func WithProgress

func WithProgress(callback func(Progress)) Option

WithProgress 设置进度回调

func WithRecursive

func WithRecursive(recursive bool) Option

WithRecursive 设置是否递归处理目录

func WithSkipHidden

func WithSkipHidden(skip bool) Option

WithSkipHidden 设置是否跳过隐藏文件

func WithTargetEncoding

func WithTargetEncoding(encoding string) Option

WithTargetEncoding 设置目标编码

type Progress

type Progress struct {
	// 核心进度信息
	CurrentFile    string         `json:"current_file"`
	ProcessedFiles int            `json:"processed_files"`
	TotalFiles     int            `json:"total_files"`
	Status         ProgressStatus `json:"status"`

	// 时间信息
	StartTime     time.Time     `json:"start_time"`
	ElapsedTime   time.Duration `json:"elapsed_time"`
	EstimatedTime time.Duration `json:"estimated_time,omitempty"`

	// 可选详细信息
	FileSize       int64 `json:"file_size,omitempty"`
	ProcessedBytes int64 `json:"processed_bytes,omitempty"`
	ErrorCount     int   `json:"error_count"`
}

Progress 进度信息结构

type ProgressStatus

type ProgressStatus string

ProgressStatus 进度状态枚举

const (
	StatusStarting   ProgressStatus = "starting"
	StatusProcessing ProgressStatus = "processing"
	StatusCompleted  ProgressStatus = "completed"
	StatusFailed     ProgressStatus = "failed"
	StatusSkipped    ProgressStatus = "skipped"
)

Directories

Path Synopsis
cmd
test command

Jump to

Keyboard shortcuts

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