96 lines
2.4 KiB
Go
96 lines
2.4 KiB
Go
/*
|
|
Copyright © 2021 Arsen Musayelyan
|
|
|
|
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 3 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 cmd
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
"regexp"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// retrieveCmd represents the retrieve command
|
|
var retrieveCmd = &cobra.Command{
|
|
Use: "retrieve",
|
|
Short: "A brief description of your command",
|
|
Aliases: []string{"retr", "recv", "get"},
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
if len(args) < 2 {
|
|
cmd.Usage()
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Get list of nodes from server
|
|
nodes := getNodeList()
|
|
|
|
// Compile regular expression for target argument
|
|
regex := regexp.MustCompile(`(.+)@(.+):(.+)`)
|
|
|
|
var sources []string
|
|
// For every argument
|
|
for index, arg := range args {
|
|
// Stop if last argument
|
|
if index == len(args)-1 {
|
|
break
|
|
}
|
|
|
|
// Find submatches in current argument
|
|
submatches := regex.FindStringSubmatch(arg)
|
|
// If no submatches found
|
|
if submatches == nil {
|
|
log.Fatal().Msg("Invalid target argument")
|
|
}
|
|
|
|
// Get variables from submatches
|
|
username, nodeName, path := submatches[1], submatches[2], submatches[3]
|
|
|
|
// Get node from list if it exists
|
|
node, ok := nodes[nodeName]
|
|
if !ok {
|
|
log.Fatal().Str("node", nodeName).Msg("Node does not exist on the server")
|
|
}
|
|
|
|
// Add new source to sources slice
|
|
sources = append(sources, username+"@"+node.IP+":"+path)
|
|
}
|
|
|
|
// Get last argument
|
|
file := args[len(args)-1]
|
|
|
|
// Create arguments for scp command
|
|
var scpArgs []string
|
|
scpArgs = append(scpArgs, sources...)
|
|
scpArgs = append(scpArgs, file)
|
|
|
|
// Create scp command
|
|
scp := exec.Command("scp", scpArgs...)
|
|
scp.Stdin = os.Stdin
|
|
scp.Stdout = os.Stdout
|
|
scp.Stderr = os.Stderr
|
|
// Run scp command
|
|
if err := scp.Run(); err != nil {
|
|
log.Fatal().Err(err).Msg("Error received from scp command")
|
|
}
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
fileCmd.AddCommand(retrieveCmd)
|
|
}
|