refactor: improve ServiceManager initialization with cleaner API

- Split initializeServiceManager into two methods:
  * initializeServiceManager(): Simple method using default configuration
  * initializeServiceManagerWithServiceConfig(): Advanced method for custom config
- Simplify NewServiceCommand() to return *ServiceCommand without error
- Update all service command methods to use appropriate initialization:
  * Start: Uses initializeServiceManagerWithServiceConfig() for custom args
  * Stop/Restart/Reload/Status/Uninstall: Use simple initializeServiceManager()
- Remove direct access to sc.serviceManager.svc/prog in favor of lazy initialization
- Improve separation of concerns and reduce code duplication
This commit is contained in:
Cuong Manh Le
2025-07-30 15:52:56 +07:00
committed by Cuong Manh Le
parent 76e602afc3
commit 33dd720d80
7 changed files with 54 additions and 22 deletions
+20 -11
View File
@@ -25,16 +25,28 @@ type ServiceCommand struct {
serviceManager *ServiceManager
}
// NewServiceCommand creates a new service command handler
func NewServiceCommand() (*ServiceCommand, error) {
sm, err := NewServiceManager()
// initializeServiceManager creates a service manager with default configuration
func (sc *ServiceCommand) initializeServiceManager() (service.Service, *prog, error) {
svcConfig := sc.createServiceConfig()
return sc.initializeServiceManagerWithServiceConfig(svcConfig)
}
// initializeServiceManagerWithServiceConfig creates a service manager with the given configuration
func (sc *ServiceCommand) initializeServiceManagerWithServiceConfig(svcConfig *service.Config) (service.Service, *prog, error) {
p := &prog{}
s, err := newService(p, svcConfig)
if err != nil {
return nil, err
return nil, nil, fmt.Errorf("failed to create service: %w", err)
}
return &ServiceCommand{
serviceManager: sm,
}, nil
sc.serviceManager = &ServiceManager{prog: p, svc: s}
return s, p, nil
}
// NewServiceCommand creates a new service command handler
func NewServiceCommand() *ServiceCommand {
return &ServiceCommand{}
}
// createServiceConfig creates a properly initialized service configuration
@@ -50,10 +62,7 @@ func (sc *ServiceCommand) createServiceConfig() *service.Config {
// InitServiceCmd creates the service command with proper logic and aliases
func InitServiceCmd() *cobra.Command {
// Create service command handlers
sc, err := NewServiceCommand()
if err != nil {
panic(fmt.Sprintf("failed to create service command: %v", err))
}
sc := NewServiceCommand()
startCmd, startCmdAlias := createStartCommands(sc)
rootCmd.AddCommand(startCmdAlias)