github.com/mmatczuk/gohan@v0.0.0-20170206152520-30e45d9bdb69/extension/gohanscript/lib/command.go (about)

     1  // Copyright (C) 2016  Juniper Networks, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package lib
    17  
    18  import (
    19  	"github.com/cloudwan/gohan/extension/gohanscript"
    20  	"os"
    21  	"os/exec"
    22  	"path/filepath"
    23  	"strings"
    24  
    25  	"github.com/cloudwan/gohan/util"
    26  )
    27  
    28  func init() {
    29  	gohanscript.RegisterStmtParser("command", command)
    30  }
    31  
    32  func command(stmt *gohanscript.Stmt) (func(*gohanscript.Context) (interface{}, error), error) {
    33  	var err error
    34  	stmt.Args, err = gohanscript.MapToValue(util.MaybeMap(stmt.RawData["args"]))
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	stmt.Args["command"], err = gohanscript.NewValue(stmt.RawData["command"])
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	return func(context *gohanscript.Context) (interface{}, error) {
    43  		chdir := stmt.Arg("chdir", context)
    44  		if chdir != nil {
    45  			currentDir, _ := filepath.Abs(".")
    46  			os.Chdir(util.MaybeString(chdir))
    47  			defer os.Chdir(currentDir)
    48  		}
    49  		command := util.MaybeString(stmt.Arg("command", context))
    50  		parts := strings.Fields(command)
    51  		result, err := exec.Command(parts[0], parts[1:]...).CombinedOutput()
    52  		return string(result), err
    53  	}, nil
    54  }