Skip to content

Commit

Permalink
improve alias feature
Browse files Browse the repository at this point in the history
  • Loading branch information
sagan committed Mar 6, 2024
1 parent 8ea6932 commit d67a630
Show file tree
Hide file tree
Showing 18 changed files with 110 additions and 73 deletions.
27 changes: 21 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# ptool

自用的 PT (private tracker) 网站辅助工具([Github](https://github.com/sagan/ptool))。提供全自动刷流(brush)、自动辅种(使用 iyuu 接口)、BT 客户端控制等功能。
自用的 PT (private tracker) 网站和 Bittorrent 客户端辅助工具([Github](https://github.com/sagan/ptool))。提供全自动刷流(brush)、自动辅种(使用 iyuu 接口)、BT 客户端控制等功能。

主要特性:

Expand Down Expand Up @@ -102,7 +102,7 @@ ptool <command> args... [flags]
- search : 在某个站点搜索指定关键词的种子。
- add : 将种子添加到 BT 客户端。
- dltorrent : 下载站点的种子。
- BT 客户端控制命令集: clientctl / show / pause / resume / delete / reannounce / recheck / getcategories / createcategory / removecategories / setcategory / gettags / createtags / deletetags / addtags / removetags / renametag / edittracker / addtrackers / removetrackers / setsavepath。
- BT 客户端控制命令集: clientctl / show / pause / resume / delete / reannounce / recheck / getcategories / createcategory / deletecategories / setcategory / gettags / createtags / deletetags / addtags / removetags / renametag / edittracker / addtrackers / removetrackers / setsavepath。
- parsetorrent : 显示种子(torrent)文件信息。
- verifytorrent : 测试种子(torrent)文件与硬盘上的文件内容一致。
- partialdownload : 拆包下载。
Expand Down Expand Up @@ -284,7 +284,7 @@ ptool show local 31a615d5984cb63c6f999f72bb3961dce49c194a
ptool show local --category rss --completed-before 5d --show-info-hash-only | ptool delete local --force -
```

#### 管理 BT 客户端里的的种子分类 / 标签 / Trackers 等(getcategories / createcategory / removecategories / setcategory / gettags / createtags / deletetags / addtags / removetags / renametag / edittracker / addtrackers / removetrackers / setsavepath)
#### 管理 BT 客户端里的的种子分类 / 标签 / Trackers 等(getcategories / createcategory / deletecategories / setcategory / gettags / createtags / deletetags / addtags / removetags / renametag / edittracker / addtrackers / removetrackers / setsavepath)

```
# 获取所有分类
Expand All @@ -294,7 +294,7 @@ ptool getcategories <client>
ptool createcategory <client> <category> --save-path "/root/downloads"
# 删除分类
ptool removecategories <client> <category>...
ptool deletecategories <client> <category>...
# 修改种子的所属分类
ptool setcategory <client> <category> <infoHashes>...
Expand Down Expand Up @@ -615,15 +615,30 @@ ptool search acg clannad

### 命令别名 (Alias) 功能

ptool.toml 里可以使用 `[[aliases]]` 区块自定义命令别名,例如:
ptool.toml 里可以使用 `[[aliases]]` 区块自定义命令别名(定义的别名无法覆盖内置命令),例如:

```
[[aliases]]
name = "st"
cmd = "status local -t"
```

然后可以直接运行 `ptool st`, 等效于运行 `ptool status local -t`。注:定义的别名无法覆盖内置命令。
然后可以直接运行 `ptool st`, 等效于运行 `ptool status local -t`

运行别名时也可以传入额外参数,并且支持指定额外参数中可选部分的默认值。例如:

```
[[aliases]]
name = "st"
cmd = "status -t"
minArgs = 0
defaultArgs = "local"
```

minArgs 是执行别名时必须传入的额外参数数量, defaultArgs 是额外参数可选部分的默认值。执行别名时,如果用户提供的额外参数数量 < minArgs ,程序会报错;如果用户提供的额外参数数量 == minArgs ,则 defaultArgs 会被追加到额外参数后面。定义以上别名后:

- 运行 `ptool st` 等效于运行 `ptool status -t local`
- 运行 `ptool st tr` 等效于运行 `ptool status -t tr`

### 模仿浏览器 (impersonate)

Expand Down
2 changes: 1 addition & 1 deletion client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ type Client interface {
DeleteTags(tags ...string) error
// create category if not existed, edit category if already exists
MakeCategory(category string, savePath string) error
RemoveCategories(categories []string) error
DeleteCategories(categories []string) error
GetCategories() ([]TorrentCategory, error)
SetTorrentsCatetory(infoHashes []string, category string) error
SetAllTorrentsCatetory(category string) error
Expand Down
2 changes: 1 addition & 1 deletion client/qbittorrent/qbittorrent.go
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ func (qbclient *Client) MakeCategory(category string, savePath string) error {
return err
}

func (qbclient *Client) RemoveCategories(categories []string) error {
func (qbclient *Client) DeleteCategories(categories []string) error {
err := qbclient.login()
if err != nil {
return fmt.Errorf("login error: %v", err)
Expand Down
2 changes: 1 addition & 1 deletion client/transmission/transmission.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ func (trclient *Client) MakeCategory(category string, savePath string) error {
return fmt.Errorf("unsupported")
}

func (trclient *Client) RemoveCategories(categories []string) error {
func (trclient *Client) DeleteCategories(categories []string) error {
return fmt.Errorf("unsupported")
}

Expand Down
12 changes: 0 additions & 12 deletions cmd/add/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,6 @@ func init() {
command.Flags().StringVarP(&defaultSite, "site", "", "", "Set default site of added torrents")
command.Flags().StringVarP(&addTags, "add-tags", "", "", "Add tags to added torrent (comma-separated)")
cmd.RootCmd.AddCommand(command)
command2.Flags().AddFlagSet(command.Flags())
cmd.RootCmd.AddCommand(command2)
}

func add(cmd *cobra.Command, args []string) error {
Expand Down Expand Up @@ -201,13 +199,3 @@ func add(cmd *cobra.Command, args []string) error {
}
return nil
}

var command2 = &cobra.Command{
Use: "add2 [args]",
Short: `Alias of "add --add-category-auto --sequential-download [args]"`,
RunE: func(cmd *cobra.Command, args []string) error {
addCategoryAuto = true
sequentialDownload = true
return command.RunE(cmd, args)
},
}
22 changes: 16 additions & 6 deletions cmd/alias/alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ var command = &cobra.Command{
Short: "Run alias.",
Long: `Run alias.`,
DisableFlagParsing: true,
Args: cobra.MatchAll(cobra.MinimumNArgs(1), cobra.OnlyValidArgs),
RunE: aliascmd,
}

Expand All @@ -36,9 +37,6 @@ func aliascmd(_ *cobra.Command, args []string) error {
defer func() {
inAlias = false
}()
if len(args) == 0 {
return fmt.Errorf("alias name must be provided as the first arg")
}
aliasName := args[0]
args = args[1:]

Expand All @@ -52,10 +50,22 @@ func aliascmd(_ *cobra.Command, args []string) error {
}
aliasArgs, err := shlex.Split(argsCmd)
if err != nil {
return fmt.Errorf("failed to parse cmd of alias '%s': %v", aliasName, err)
return fmt.Errorf("failed to parse alias %s cmdline '%s': %v", aliasName, argsCmd, err)
}
if len(args) < int(aliasConfig.MinArgs) {
return fmt.Errorf("alias '%s' requires at least %d arg(s), only received %d",
aliasName, aliasConfig.MinArgs, len(args))
}
aliasArgs = append([]string{os.Args[0]}, aliasArgs...)
os.Args = append(aliasArgs, args...)
fmt.Printf("Run alias '%s': %v\n", aliasName, os.Args[1:])
aliasArgs = append(aliasArgs, args...)
if len(args) == int(aliasConfig.MinArgs) && aliasConfig.DefaultArgs != "" {
if aliasDefaultArgs, err := shlex.Split(aliasConfig.DefaultArgs); err != nil {
return fmt.Errorf("failed to parse alias '%s' defaultArgs '%s': %v", aliasName, aliasConfig.DefaultArgs, err)
} else {
aliasArgs = append(aliasArgs, aliasDefaultArgs...)
}
}
os.Args = aliasArgs
fmt.Fprintf(os.Stderr, "Run alias '%s': %v\n", aliasName, os.Args[1:])
return cmd.RootCmd.Execute()
}
2 changes: 1 addition & 1 deletion cmd/all/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
_ "github.com/sagan/ptool/cmd/createcategory"
_ "github.com/sagan/ptool/cmd/createtags"
_ "github.com/sagan/ptool/cmd/delete"
_ "github.com/sagan/ptool/cmd/deletecategories"
_ "github.com/sagan/ptool/cmd/deletetags"
_ "github.com/sagan/ptool/cmd/dltorrent"
_ "github.com/sagan/ptool/cmd/edittracker"
Expand All @@ -25,7 +26,6 @@ import (
_ "github.com/sagan/ptool/cmd/pause"
_ "github.com/sagan/ptool/cmd/reannounce"
_ "github.com/sagan/ptool/cmd/recheck"
_ "github.com/sagan/ptool/cmd/removecategories"
_ "github.com/sagan/ptool/cmd/removetags"
_ "github.com/sagan/ptool/cmd/removetrackers"
_ "github.com/sagan/ptool/cmd/renametag"
Expand Down
15 changes: 0 additions & 15 deletions cmd/batchdl/batchdl.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,6 @@ func init() {
cmd.AddEnumFlagP(command, &sortFlag, "sort", "", common.SiteTorrentSortFlag)
cmd.AddEnumFlagP(command, &orderFlag, "order", "", common.OrderFlag)
cmd.RootCmd.AddCommand(command)
command2.Flags().AddFlagSet(command.Flags())
cmd.RootCmd.AddCommand(command2)
}

func batchdl(command *cobra.Command, args []string) error {
Expand Down Expand Up @@ -464,16 +462,3 @@ mainloop:
doneHandle()
return nil
}

var command2 = &cobra.Command{
Use: "batchdl2 {client} [args]",
Short: `Alias of "batchdl --action=add --add-client={client} --add-category-auto [args]"`,
Args: cobra.MatchAll(cobra.ExactArgs(2), cobra.OnlyValidArgs),
RunE: func(cmd *cobra.Command, args []string) error {
action = "add"
addClient = args[0]
addCategoryAuto = true
args = args[1:]
return command.RunE(cmd, args)
},
}
12 changes: 9 additions & 3 deletions cmd/configcmd/configcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func configcmd(cmd *cobra.Command, args []string) error {
sites := util.CopySlice(config.Get().Sites)
groups := util.CopySlice(config.Get().Groups)
aliases := util.CopySlice(config.Get().Aliases)
aliases = append(aliases, config.InternalAliases...)
cookieclouds := util.CopySlice(config.Get().Cookieclouds)
sort.Slice(clients, func(i, j int) bool {
return clients[i].Name < clients[j].Name
Expand Down Expand Up @@ -170,15 +171,20 @@ func configcmd(cmd *cobra.Command, args []string) error {
}
fmt.Printf("\n")

fmt.Printf("Aliases:\n")
fmt.Printf("%-15s %-s\n", "Name", "Cmd")
fmt.Printf("Aliases: (internal: *)\n")
fmt.Printf("%-15s %-5s %-7s %-20s %-s\n", "Name", "Flags", "MinArgs", "DefaultArgs", "Cmd")
emptyFlag = true
for _, aliasConfig := range aliases {
if filter != "" && !aliasConfig.MatchFilter(filter) {
continue
}
emptyFlag = false
fmt.Printf("%-15s %-s\n", aliasConfig.Name, aliasConfig.Cmd)
flags := []string{}
if aliasConfig.Internal {
flags = append(flags, "*")
}
fmt.Printf("%-15s %-5s %-7d %-20s %-s\n",
aliasConfig.Name, strings.Join(flags, ", "), aliasConfig.MinArgs, aliasConfig.DefaultArgs, aliasConfig.Cmd)
}
if emptyFlag {
fmt.Print(emptyListPlaceholder)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package removecategories
package deletecategories

import (
"fmt"
Expand All @@ -10,27 +10,28 @@ import (
)

var command = &cobra.Command{
Use: "removecategories {client} {category}...",
Annotations: map[string]string{"cobra-prompt-dynamic-suggestions": "removecategories"},
Short: "Remove categories from client.",
Long: `Remove categories from client.`,
Use: "deletecategories {client} {category}...",
Aliases: []string{"delcats"},
Annotations: map[string]string{"cobra-prompt-dynamic-suggestions": "deletecategories"},
Short: "Delete categories from client.",
Long: `Delete categories from client.`,
Args: cobra.MatchAll(cobra.MinimumNArgs(2), cobra.OnlyValidArgs),
RunE: removecategories,
RunE: deletecategories,
}

func init() {
cmd.RootCmd.AddCommand(command)
}

func removecategories(cmd *cobra.Command, args []string) error {
func deletecategories(cmd *cobra.Command, args []string) error {
clientName := args[0]
categories := args[1:]
clientInstance, err := client.CreateClient(clientName)
if err != nil {
return fmt.Errorf("failed to create client: %v", err)
}

err = clientInstance.RemoveCategories(categories)
err = clientInstance.DeleteCategories(categories)
if err != nil {
return err
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package removecategories
package deletecategories

import (
"github.com/c-bata/go-prompt"
Expand All @@ -8,7 +8,7 @@ import (
)

func init() {
cmd.AddShellCompletion("removecategories", func(document *prompt.Document) []prompt.Suggest {
cmd.AddShellCompletion("deletecategories", func(document *prompt.Document) []prompt.Suggest {
info := suggest.Parse(document)
if info.LastArgIndex < 1 {
return nil
Expand Down
1 change: 1 addition & 0 deletions cmd/deletetags/deletetags.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

var command = &cobra.Command{
Use: "deletetags {client} {tags}...",
Aliases: []string{"deltags"},
Annotations: map[string]string{"cobra-prompt-dynamic-suggestions": "deletetags"},
Short: "Delete tags from client.",
Long: `Delete tags from client.`,
Expand Down
11 changes: 0 additions & 11 deletions cmd/parsetorrent/parsetorrent.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ func init() {
command.Flags().BoolVarP(&forceLocal, "force-local", "", false, "Force treat all arg as local torrent filename")
command.Flags().StringVarP(&defaultSite, "site", "", "", "Set default site of torrent url")
cmd.RootCmd.AddCommand(command)
cmd.RootCmd.AddCommand(command2)
}

func parsetorrent(cmd *cobra.Command, args []string) error {
Expand Down Expand Up @@ -76,13 +75,3 @@ func parsetorrent(cmd *cobra.Command, args []string) error {
}
return nil
}

var command2 = &cobra.Command{
Use: "parsetorrent2",
Short: `Alias of "parsetorrent *.torrent"`,
Args: cobra.MatchAll(cobra.ExactArgs(0), cobra.OnlyValidArgs),
RunE: func(cmd *cobra.Command, args []string) error {
args = append(args, "*.torrent")
return command.RunE(cmd, args)
},
}
2 changes: 1 addition & 1 deletion cmd/run/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,6 @@ func run(_ *cobra.Command, args []string) error {
return fmt.Errorf("failed to parse cmdline '%s': %v", cmdline, err)
}
os.Args = append([]string{os.Args[0]}, cmdlineArgs...)
fmt.Printf("Run cmdline: %v\n", os.Args[1:])
fmt.Fprintf(os.Stderr, "Run cmdline: %v\n", os.Args[1:])
return cmd.RootCmd.Execute()
}
3 changes: 3 additions & 0 deletions cmd/xseedcheck/xseedcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,8 @@ func xseedcheck(cmd *cobra.Command, args []string) error {
fmt.Printf("Torrent file: %s\n", torrent)
tinfo.PrintFiles(true, true)
}
if compareResult < 0 {
return fmt.Errorf("not match")
}
return nil
}

0 comments on commit d67a630

Please sign in to comment.