feat: migrate to golang

This commit is contained in:
2026-07-19 20:01:38 +08:00
parent 302d4e6bb5
commit a2630df9e0
69 changed files with 4750 additions and 3369 deletions

102
internal/cli/config.go Normal file
View File

@ -0,0 +1,102 @@
package cli
import "github.com/spf13/cobra"
func newConfigCmd() *cobra.Command {
var configFile, outputFile, subscriptionName string
cmd := &cobra.Command{
Use: "config",
Short: "Manage core configuration",
}
cmd.PersistentFlags().StringVar(&configFile, "config-file", "", "Path to the user config YAML file (default: core-config.yaml in config dir)")
cmd.PersistentFlags().StringVar(&outputFile, "output-file", "", "Path to the generated config file (default: generated_config.yaml in config dir)")
cmd.PersistentFlags().StringVar(&subscriptionName, "subscription", "", "Name of the subscription to use for config generation (default: active subscription)")
build := func() (*managers, error) {
return newManagers(configFile, outputFile, subscriptionName)
}
cmd.AddCommand(
&cobra.Command{
Use: "import <source>",
Short: "Import configuration from file",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.ImportConfig(args[0])
return nil
},
},
&cobra.Command{
Use: "export <destination>",
Short: "Export configuration to file",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.ExportConfig(args[0])
return nil
},
},
&cobra.Command{
Use: "edit",
Short: "Edit configuration with system editor",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.EditConfig()
return nil
},
},
&cobra.Command{
Use: "reset",
Short: "Reset configuration to default values",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.ResetConfig()
return nil
},
},
&cobra.Command{
Use: "show",
Short: "Show current configuration",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.ShowConfig()
return nil
},
},
&cobra.Command{
Use: "apply",
Short: "Apply active subscription to generate final config",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := build()
if err != nil {
return err
}
m.CoreConfig.Apply()
return nil
},
},
)
return cmd
}

33
internal/cli/core.go Normal file
View File

@ -0,0 +1,33 @@
package cli
import "github.com/spf13/cobra"
func newCoreCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "core",
Short: "Manage scientific-surfing core components",
}
cmd.AddCommand(newCoreUpdateCmd())
return cmd
}
func newCoreUpdateCmd() *cobra.Command {
var version string
var force bool
c := &cobra.Command{
Use: "update",
Short: "Update scientific-surfing core components",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Core.Update(version, force)
return nil
},
}
c.Flags().StringVar(&version, "version", "", "Specific version to download (e.g., v1.18.5). If not specified, downloads latest")
c.Flags().BoolVar(&force, "force", false, "Force update even if binary already exists")
return c
}

67
internal/cli/hook.go Normal file
View File

@ -0,0 +1,67 @@
package cli
import "github.com/spf13/cobra"
func newHookCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "hook",
Short: "Manage hook scripts",
}
cmd.AddCommand(
&cobra.Command{
Use: "init",
Short: "Initialize hooks directory with template scripts",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Hook.Init()
return nil
},
},
&cobra.Command{
Use: "list",
Short: "Show hooks directory location and list scripts",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Hook.ListHooks()
return nil
},
},
&cobra.Command{
Use: "edit <script>",
Short: "Edit a hook script",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Hook.Edit(args[0])
return nil
},
},
&cobra.Command{
Use: "rm <script>",
Short: "Remove a hook script",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Hook.Rm(args[0])
return nil
},
},
)
return cmd
}

85
internal/cli/root.go Normal file
View File

@ -0,0 +1,85 @@
// Package cli wires up the ss command-line interface, mirroring cli.py's
// argparse-based command tree with cobra.
package cli
import (
"fmt"
"os"
"github.com/spf13/cobra"
"gitea.epss.net.cn/klesh/ss/internal/core"
"gitea.epss.net.cn/klesh/ss/internal/corecfg"
"gitea.epss.net.cn/klesh/ss/internal/hook"
"gitea.epss.net.cn/klesh/ss/internal/storage"
"gitea.epss.net.cn/klesh/ss/internal/subscription"
)
// managers bundles the manager instances every command needs, mirroring the
// set built unconditionally in cli.py's main().
type managers struct {
Storage *storage.Manager
Subscription *subscription.Manager
CoreConfig *corecfg.Manager
Core *core.Manager
Hook *hook.Manager
}
// newManagers builds the full manager stack. configFile/outputFile/
// subscriptionName are only ever non-empty when the "config" command tree
// supplies its persistent flags, matching cli.py's main() which populates
// CoreConfigManager from args.config_file/output_file/subscription
// regardless of which subcommand is running (those attributes simply don't
// exist on the namespace for other subcommands).
func newManagers(configFile, outputFile, subscriptionName string) (*managers, error) {
s, err := storage.New()
if err != nil {
return nil, fmt.Errorf("failed to initialize storage: %w", err)
}
subMgr, err := subscription.New(s)
if err != nil {
return nil, fmt.Errorf("failed to initialize subscription manager: %w", err)
}
coreCfgMgr, err := corecfg.New(subMgr, configFile, outputFile, subscriptionName)
if err != nil {
return nil, fmt.Errorf("failed to initialize core config manager: %w", err)
}
coreMgr := core.New(coreCfgMgr)
hookMgr := hook.New(s)
return &managers{
Storage: s,
Subscription: subMgr,
CoreConfig: coreCfgMgr,
Core: coreMgr,
Hook: hookMgr,
}, nil
}
// Execute runs the ss CLI. It is the Go equivalent of cli.py's main().
func Execute() {
root := &cobra.Command{
Use: "ss",
Short: "Scientific Surfing - CLI for managing clash RSS subscriptions",
SilenceUsage: true,
SilenceErrors: true,
}
root.AddCommand(
newSubscriptionCmd(),
newCoreCmd(),
newConfigCmd(),
newServiceCmd(),
newHookCmd(),
)
if err := root.Execute(); err != nil {
if _, silent := err.(*silentError); !silent {
fmt.Printf("❌ Error: %v\n", err)
}
os.Exit(1)
}
}

222
internal/cli/service.go Normal file
View File

@ -0,0 +1,222 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
svc "gitea.epss.net.cn/klesh/ss/internal/service"
)
func newServiceCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "service",
Short: "Manage mihomo as a system service",
}
cmd.AddCommand(
newServiceInstallCmd(),
newServiceUninstallCmd(),
newServiceStartCmd(),
newServiceStopCmd(),
newServiceRestartCmd(),
newServiceReloadCmd(),
newServiceStatusCmd(),
newServiceRunMacOSCmd(),
newServiceRunWindowsCmd(),
)
return cmd
}
func withNameFlag(c *cobra.Command, name *string) {
c.Flags().StringVar(name, "name", "mihomo", "Service name (default: mihomo)")
}
func newServiceInstallCmd() *cobra.Command {
var name, description string
c := &cobra.Command{
Use: "install",
Short: "Install mihomo as a system service",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.InstallService(name, description) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
c.Flags().StringVar(&description, "description", "Mihomo proxy service", "Service description")
return c
}
func newServiceUninstallCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "uninstall",
Short: "Uninstall mihomo system service",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.UninstallService(name) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
return c
}
func newServiceStartCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "start",
Short: "Start mihomo system service",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.StartService(name) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
return c
}
func newServiceStopCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "stop",
Short: "Stop mihomo system service",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.StopService(name) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
return c
}
func newServiceRestartCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "restart",
Short: "Restart mihomo system service",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.RestartService(name) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
return c
}
func newServiceReloadCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "reload",
Short: "Reload mihomo service configuration (via API)",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
if !m.Core.ReloadService(name) {
return errSilentFailure
}
return nil
},
}
withNameFlag(c, &name)
return c
}
func newServiceStatusCmd() *cobra.Command {
var name string
c := &cobra.Command{
Use: "status",
Short: "Check mihomo system service status",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
status := m.Core.GetServiceStatus(name)
fmt.Printf("Service '%s' status: %s\n", name, status)
return nil
},
}
withNameFlag(c, &name)
return c
}
// newServiceRunMacOSCmd is the hidden command the generated launchd plist
// invokes, replacing the standalone macos_service_wrapper.py script.
func newServiceRunMacOSCmd() *cobra.Command {
c := &cobra.Command{
Use: "run-macos <executable> <config-dir> [args...]",
Hidden: true,
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
return svc.RunMacOSWrapper(args[0], args[1], args[2:])
},
}
return c
}
// newServiceRunWindowsCmd is the hidden command sc.exe's binPath= invokes,
// replacing windows_service_wrapper.py + pywin32.
func newServiceRunWindowsCmd() *cobra.Command {
var name, bin, args string
c := &cobra.Command{
Use: "run-windows",
Hidden: true,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, cmdArgs []string) error {
return svc.RunWindowsService(name, bin, args)
},
}
c.Flags().StringVar(&name, "name", "mihomo", "Service name")
c.Flags().StringVar(&bin, "bin", "", "Path to the wrapped executable")
c.Flags().StringVar(&args, "args", "", "Command line arguments for the wrapped executable")
return c
}
// errSilentFailure signals a command failure whose message has already been
// printed by the underlying manager (matching cli.py's pattern of printing
// "❌ ..." then sys.exit(1) without an additional error message).
var errSilentFailure = &silentError{}
type silentError struct{}
func (e *silentError) Error() string { return "" }

View File

@ -0,0 +1,175 @@
package cli
import "github.com/spf13/cobra"
func newSubscriptionCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "subscription",
Short: "Manage subscriptions",
}
cmd.AddCommand(
newSubscriptionAddCmd(),
newSubscriptionRefreshCmd(),
newSubscriptionRmCmd(),
newSubscriptionRenameCmd(),
newSubscriptionSetURLCmd(),
newSubscriptionGetURLCmd(),
newSubscriptionActivateCmd(),
newSubscriptionListCmd(),
newSubscriptionStorageCmd(),
)
return cmd
}
func newSubscriptionAddCmd() *cobra.Command {
return &cobra.Command{
Use: "add <name> <url>",
Short: "Add a new subscription",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.AddSubscription(args[0], args[1])
return nil
},
}
}
func newSubscriptionRefreshCmd() *cobra.Command {
var backup bool
c := &cobra.Command{
Use: "refresh <name>",
Short: "Refresh a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.RefreshSubscription(args[0], backup)
m.Core.ReloadService("mihomo")
return nil
},
}
c.Flags().BoolVar(&backup, "backup", false, "Backup the existing file before refreshing")
return c
}
func newSubscriptionRmCmd() *cobra.Command {
return &cobra.Command{
Use: "rm <name>",
Short: "Delete a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.DeleteSubscription(args[0])
return nil
},
}
}
func newSubscriptionRenameCmd() *cobra.Command {
return &cobra.Command{
Use: "rename <name> <new_name>",
Short: "Rename a subscription",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.RenameSubscription(args[0], args[1])
return nil
},
}
}
func newSubscriptionSetURLCmd() *cobra.Command {
return &cobra.Command{
Use: "set-url <name> <url>",
Short: "Update the URL for a subscription",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.SetSubscriptionURL(args[0], args[1])
return nil
},
}
}
func newSubscriptionGetURLCmd() *cobra.Command {
return &cobra.Command{
Use: "get-url <name>",
Short: "Show the URL for a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.GetSubscriptionURL(args[0])
return nil
},
}
}
func newSubscriptionActivateCmd() *cobra.Command {
return &cobra.Command{
Use: "activate <name>",
Short: "Activate a subscription",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.ActivateSubscription(args[0])
if m.CoreConfig.Apply() {
m.Core.ReloadService("mihomo")
}
return nil
},
}
}
func newSubscriptionListCmd() *cobra.Command {
return &cobra.Command{
Use: "list",
Short: "List all subscriptions",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.ListSubscriptions()
return nil
},
}
}
func newSubscriptionStorageCmd() *cobra.Command {
return &cobra.Command{
Use: "storage",
Short: "Show storage information",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
m, err := newManagers("", "", "")
if err != nil {
return err
}
m.Subscription.ShowStorageInfo()
return nil
},
}
}