Skip to content

Commit

Permalink
整理rename功能
Browse files Browse the repository at this point in the history
  • Loading branch information
jianyun8023 committed Feb 24, 2023
1 parent 9a43cdd commit 35ff440
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 47 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

# Output of the go coverage tool, specifically when used with LiteIDE
*.out
.idea
.fleet

# Dependency directories (remove the comment below to include it)
# vendor/
26 changes: 13 additions & 13 deletions cmd/clname.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

// Used for downloading books from sanqiu website.
var c = &ClnameConfig{
ReNameReg: regexp.MustCompile(`(?m)([\((【].{7,}[\))】])*\s*(([\((【].{7,}[\))】]))$`),
ReNameReg: regexp.MustCompile(`(?m)([((【].{7,}[))】])*\s*([((【].{7,}[))】])$`),
}

// renameBookCmd used for download books from sanqiu.cc
Expand All @@ -24,14 +24,14 @@ var clnameCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
// Validate config.

ValidateConfig(c)
ValidateConfig(c)

if IsDir(c.Path) {
m, _ := filepath.Glob(path.Join(c.Path, "*.epub"))
for _, val := range m {
// fmt.Println(val)
epubpath := val
err := ParseEpub(epubpath, c)
err := ParseEpub(epubpath, c)
if err != nil && !c.Skip {
panic(fmt.Errorf("file %v %v", epubpath, err))
} else if err != nil && c.Skip {
Expand All @@ -41,7 +41,7 @@ var clnameCmd = &cobra.Command{

} else {
epubpath := c.Path
err := ParseEpub(epubpath, c)
err := ParseEpub(epubpath, c)
if err != nil && !c.Skip {
panic(fmt.Errorf("file %v %v", epubpath, err))
} else if err != nil && c.Skip {
Expand All @@ -63,13 +63,13 @@ func ValidateConfig(c *ClnameConfig) {
}

func init() {
clnameCmd.Flags().StringVarP(&c.Path, "path", "p", "./",
clnameCmd.Flags().StringVarP(&c.Path, "path", "p", "./",
"目录或者文件")
clnameCmd.Flags().BoolVarP(&c.Debug, "dotry", "t", false,
clnameCmd.Flags().BoolVarP(&c.Debug, "dotry", "t", false,
"尝试运行")
clnameCmd.Flags().BoolVarP(&c.Skip, "skip", "j", false,
clnameCmd.Flags().BoolVarP(&c.Skip, "skip", "j", false,
"跳过无法解析的书籍")
clnameCmd.Flags().BoolVarP(&c.Debug, "debug", "d", false, "The number of download threads.")
clnameCmd.Flags().BoolVarP(&c.Debug, "debug", "d", false, "The number of download threads.")
}

func ParseEpub(file string, c *ClnameConfig) error {
Expand All @@ -91,7 +91,7 @@ func ParseEpub(file string, c *ClnameConfig) error {
return nil
}

fmt.Printf("路径: \033[1;31;40m%v\033[0m 新名称: \033[1;32;40m%v\033[0m 旧名称: \033[1;33;40m%v\033[0m\n", file, newTitle, title)
fmt.Printf("路径: \033[1;31;40m%v\033[0m 新名称: \033[1;32;40m%v\033[0m 旧名称: \033[1;33;40m%v\033[0m\n", file, newTitle, title)

if c.DoTry {
return nil
Expand All @@ -113,10 +113,10 @@ func ParseEpub(file string, c *ClnameConfig) error {
}

type ClnameConfig struct {
Path string
DoTry bool
Debug bool
Skip bool
Path string
DoTry bool
Debug bool
Skip bool

ReNameReg *regexp.Regexp
}
Expand Down
52 changes: 36 additions & 16 deletions cmd/rename.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,47 @@ The rename command will rename or move files according to a template that you
specify. The template can include the file extension, so if you want to keep
the original extension, you can include it in the template. You can also use
a sequence number in the template to number the files sequentially.`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {

if len(args) == 0 {
fmt.Printf("Error: 需要指定扫描路径")
os.Exit(1)
}
array, err := cmd.Flags().GetStringArray("format")
if err != nil {
panic(err)
}
config := RenameConfig{
Debug: cmd.Flag("debug").Value.String() == "true",
DoTry: cmd.Flag("do-try").Value.String() == "true",
Format: cmd.Flag("format").Value.String(),
Formats: array,
Recursive: cmd.Flag("recursive").Value.String() == "true",
Move: cmd.Flag("move").Value.String() == "true",
SourceDir: args[0],
OutputDir: cmd.Flag("output").Value.String(),
Move: cmd.Flag("output").Value.String() != "",
Template: cmd.Flag("template").Value.String(),
StartIndex: parseIntFlag(cmd, "start-num"),
}

if config.Debug {
fmt.Println("Debugging information:")
fmt.Printf(" - Format: %s\n", config.Format)
fmt.Printf(" - DoTry: %v\n", config.DoTry)
fmt.Printf(" - Format: %v\n", config.Formats)
fmt.Printf(" - Recursive: %v\n", config.Recursive)
fmt.Printf(" - Move: %v\n", config.Move)
fmt.Printf(" - SourceDir: %s\n", config.SourceDir)
fmt.Printf(" - OutputDir: %s\n", config.OutputDir)
fmt.Printf(" - Template: %s\n", config.Template)
fmt.Printf(" - StartIndex: %d\n", config.StartIndex)
}

rename(config)

},
}

func rename(config RenameConfig) {

files, err := findFiles(config.Format, config.Recursive)
files, err := findFiles(config.SourceDir, config.Formats, config.Recursive)
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
Expand Down Expand Up @@ -112,28 +122,36 @@ func rename(config RenameConfig) {
}
}

func findFiles(format string, recursive bool) ([]string, error) {
func findFiles(dir string, formats []string, recursive bool) ([]string, error) {
var files []string

matches, err := filepath.Glob(format)
matches, err := filepath.Glob(filepath.Join(dir, "*"))
if err != nil {
return nil, err
}

for _, match := range matches {

included := false
for _, includedStr := range formats {
if strings.Contains(match, includedStr) {
included = true
break
}
}

info, err := os.Stat(match)
if err != nil {
return nil, err
}

if !info.IsDir() {
if !info.IsDir() && included {
files = append(files, match)
} else if recursive {
subFiles, err := findFiles(filepath.Join(match, format), true)
subFiles, err := findFiles(match, formats, true)
if err != nil {
return nil, err
}

files = append(files, subFiles...)
}
}
Expand All @@ -145,12 +163,13 @@ func findFiles(format string, recursive bool) ([]string, error) {
func init() {
renameCmd.Flags().Bool("debug", false, "Enable debugging information")
renameCmd.Flags().Bool("do-try", false, "Only print out actions that would be performed")
renameCmd.Flags().StringP("format", "f", "*", "File format to match (e.g. '*.txt')")
renameCmd.Flags().StringArrayP("format", "f", []string{"*"}, "File format to match (e.g. 'txt')")
renameCmd.Flags().BoolP("recursive", "r", false, "Recursively search for files")
renameCmd.Flags().BoolP("move", "m", false, "Move files instead of renaming them")
renameCmd.Flags().String("output", "", "Output directory for moved files")
renameCmd.Flags().String("template", "file-$n", "Template for new filename")
renameCmd.Flags().StringP("output", "o", "", "Output directory for moved files")
renameCmd.Flags().StringP("template", "t", "file-$n", "Template for new filename (e.g. 'file-$n')")
renameCmd.Flags().Int("start-num", 1, "Starting number for sequence")
_ = rootCmd.MarkFlagRequired("format")
_ = rootCmd.MarkFlagRequired("template")
}

func buildNewName(template string, index int, file string) string {
Expand All @@ -173,9 +192,10 @@ func parseIntFlag(cmd *cobra.Command, name string) int {
type RenameConfig struct {
Debug bool
DoTry bool
Format string
Formats []string
Recursive bool
Move bool
SourceDir string
OutputDir string
Template string
StartIndex int
Expand Down
26 changes: 11 additions & 15 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,28 @@
package cmd

import (
"os"
"os"

"github.com/spf13/cobra"
"github.com/spf13/cobra"
)

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "booktool",
Short: "A command line base downloader for downloading books from internet.",
Long: `You can use this command to download book from these websites.
1. Self-hosted talebook websites
2. https://www.sanqiu.cc
3. Telegram channel`,
Use: "bookImporter",
Short: "Import books into your library",
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
err := rootCmd.Execute()
if err != nil {
os.Exit(1)
}
}

func init() {
rootCmd.AddCommand(clnameCmd)
rootCmd.AddCommand(renameCmd)
rootCmd.AddCommand(clnameCmd)
rootCmd.AddCommand(renameCmd)
rootCmd.SetVersionTemplate("v0.0.1")
}
4 changes: 1 addition & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ package main
import "github.com/jianyun8023/bookImporter/cmd"

func main() {
cmd.Execute()
cmd.Execute()
}


0 comments on commit 35ff440

Please sign in to comment.