Add a way to extend the CLI with external binaries

This lets luet to be extended like git does (just by having luet-subcommand binaries under $PATH)
following the UNIX filosophy. It has the downside that we silence the errors from cobra and we handle
them by ourselves.

Also the Exec syscall is not portable, and it should have implementation for each platform (hence why in helpers)
This commit is contained in:
Ettore Di Giacinto 2020-02-18 23:08:14 +01:00
parent 4648dedb55
commit 647ea35983
No known key found for this signature in database
GPG Key ID: 1ADA699B145A2D1C
2 changed files with 47 additions and 2 deletions

View File

@ -16,6 +16,7 @@
package cmd
import (
"fmt"
"os"
"os/user"
"path/filepath"
@ -24,6 +25,7 @@ import (
"github.com/marcsauter/single"
config "github.com/mudler/luet/pkg/config"
helpers "github.com/mudler/luet/pkg/helpers"
. "github.com/mudler/luet/pkg/logger"
repo "github.com/mudler/luet/pkg/repository"
@ -51,12 +53,13 @@ var RootCmd = &cobra.Command{
Fatal("failed to load configuration:", err.Error())
}
},
SilenceErrors: true,
}
func LoadConfig(c *config.LuetConfig) error {
// If a config file is found, read it in.
if err := c.Viper.ReadInConfig(); err != nil {
Warning(err)
Debug(err)
}
err := c.Viper.Unmarshal(&config.LuetCfg)
@ -99,8 +102,18 @@ func Execute() {
}
defer s.TryUnlock()
}
if err := RootCmd.Execute(); err != nil {
Error(err)
if len(os.Args) > 0 {
for _, c := range RootCmd.Commands() {
if c.Name() == os.Args[1] {
os.Exit(-1) // Something failed
}
}
// Try to load a bin from path.
helpers.Exec("luet-"+os.Args[1], os.Args[1:], os.Environ())
}
fmt.Println(err)
os.Exit(-1)
}
}

32
pkg/helpers/sys.go Normal file
View File

@ -0,0 +1,32 @@
// Copyright © 2020 Ettore Di Giacinto <mudler@gentoo.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/>.
package helpers
import (
"os/exec"
"syscall"
"github.com/pkg/errors"
)
// This allows a multi-platform switch in the future
func Exec(cmd string, args []string, env []string) error {
path, err := exec.LookPath(cmd)
if err != nil {
return errors.Wrap(err, "Could not find binary in path: "+cmd)
}
return syscall.Exec(path, args, env)
}