hostSync/cmd/format.go

101 lines
2.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"os"
"strings"
"github.com/evil7/hostsync/core"
"github.com/evil7/hostsync/utils"
"github.com/spf13/cobra"
)
// formatCmd 格式化命令
var formatCmd = &cobra.Command{
Use: "format [blockName]",
Short: "格式化配置文件",
Long: `格式化hosts配置文件整理缩进和间距。
可以格式化整个文件或指定块。
示例:
hostsync format # 格式化整个文件
hostsync format github # 格式化指定块
hostsync format --sort # 格式化并排序`,
Args: cobra.MaximumNArgs(1),
Run: runFormat,
}
var sortEntries bool
func init() {
formatCmd.Flags().BoolVar(&sortEntries, "sort", false, "格式化并排序")
}
func runFormat(cmd *cobra.Command, args []string) {
utils.CheckAdmin()
hm := core.NewHostsManager()
if err := hm.Load(); err != nil {
utils.LogError("加载hosts文件失败: %v\n", err)
os.Exit(1)
}
if len(args) == 0 {
// 格式化整个文件
formatAllBlocks(hm)
} else {
// 格式化指定块
blockName := args[0]
formatBlock(hm, blockName)
}
if err := hm.Save(); err != nil {
utils.LogError("保存文件失败: %v", err)
os.Exit(1)
}
utils.LogSuccess("格式化完成")
}
func formatAllBlocks(hm *core.HostsManager) {
utils.LogInfo("格式化所有块 (%d 个)", len(hm.Blocks))
if sortEntries {
// 排序所有块中的条目
for _, block := range hm.Blocks {
sortBlockEntries(block)
}
utils.LogInfo("已按域名排序")
}
}
func formatBlock(hm *core.HostsManager, blockName string) {
if !utils.ValidateBlockName(blockName) {
utils.LogError("无效的块名称: %s", blockName)
utils.LogInfo("块名称只能包含字母、数字、下划线和连字符")
os.Exit(1)
}
block := hm.GetBlock(blockName)
if block == nil {
utils.LogError("块不存在: %s", blockName)
os.Exit(1)
}
utils.LogInfo("格式化块: %s", blockName)
if sortEntries {
sortBlockEntries(block)
utils.LogInfo("已按域名排序")
}
}
func sortBlockEntries(block *core.HostBlock) {
// 按域名排序
for i := 0; i < len(block.Entries)-1; i++ {
for j := i + 1; j < len(block.Entries); j++ {
if strings.Compare(block.Entries[i].Domain, block.Entries[j].Domain) > 0 {
block.Entries[i], block.Entries[j] = block.Entries[j], block.Entries[i]
}
}
}
}