convert repo plugin to golang

This commit is contained in:
Michael Hobbs
2017-01-03 22:27:20 -08:00
parent 8d83803763
commit b6dffaabee
44 changed files with 2705 additions and 24 deletions

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,69 @@
## OLD README
First give you a full example, I will explain every command below.
session := sh.NewSession()
session.Env["PATH"] = "/usr/bin:/bin"
session.Stdout = os.Stdout
session.Stderr = os.Stderr
session.Alias("ll", "ls", "-l")
session.ShowCMD = true // enable for debug
var err error
err = session.Call("ll", "/")
if err != nil {
log.Fatal(err)
}
ret, err := session.Capture("pwd", sh.Dir("/home")) # wraper of session.Call
if err != nil {
log.Fatal(err)
}
# ret is "/home\n"
fmt.Println(ret)
create a new Session
session := sh.NewSession()
use alias like this
session.Alias("ll", "ls", "-l") # like alias ll='ls -l'
set current env like this
session.Env["BUILD_ID"] = "123" # like export BUILD_ID=123
set current directory
session.Set(sh.Dir("/")) # like cd /
pipe is also supported
session.Command("echo", "hello\tworld").Command("cut", "-f2")
// output should be "world"
session.Run()
test, the build in command support
session.Test("d", "dir") // test dir
session.Test("f", "file) // test regular file
with `Alias Env Set Call Capture Command` a shell scripts can be easily converted into golang program. below is a shell script.
#!/bin/bash -
#
export PATH=/usr/bin:/bin
alias ll='ls -l'
cd /usr
if test -d "local"
then
ll local | awk '{print $1, $NF}'
fi
convert to golang, will be
s := sh.NewSession()
s.Env["PATH"] = "/usr/bin:/bin"
s.Set(sh.Dir("/usr"))
s.Alias("ll", "ls", "-l")
if s.Test("d", "local") {
s.Command("ll", "local").Command("awk", "{print $1, $NF}").Run()
}

View File

@@ -0,0 +1,85 @@
## go-sh
[![wercker status](https://app.wercker.com/status/009acbd4f00ccc6de7e2554e12a50d84/s "wercker status")](https://app.wercker.com/project/bykey/009acbd4f00ccc6de7e2554e12a50d84)
[![Go Walker](http://gowalker.org/api/v1/badge)](http://gowalker.org/github.com/codeskyblue/go-sh)
*If you depend on the old api, see tag: v.0.1*
install: `go get github.com/codeskyblue/go-sh`
Pipe Example:
package main
import "github.com/codeskyblue/go-sh"
func main() {
sh.Command("echo", "hello\tworld").Command("cut", "-f2").Run()
}
Because I like os/exec, `go-sh` is very much modelled after it. However, `go-sh` provides a better experience.
These are some of its features:
* keep the variable environment (e.g. export)
* alias support (e.g. alias in shell)
* remember current dir
* pipe command
* shell build-in commands echo & test
* timeout support
Examples are important:
sh: echo hello
go: sh.Command("echo", "hello").Run()
sh: export BUILD_ID=123
go: s = sh.NewSession().SetEnv("BUILD_ID", "123")
sh: alias ll='ls -l'
go: s = sh.NewSession().Alias('ll', 'ls', '-l')
sh: (cd /; pwd)
go: sh.Command("pwd", sh.Dir("/")).Run()
sh: test -d data || mkdir data
go: if ! sh.Test("dir", "data") { sh.Command("mkdir", "data").Run() }
sh: cat first second | awk '{print $1}'
go: sh.Command("cat", "first", "second").Command("awk", "{print $1}").Run()
sh: count=$(echo "one two three" | wc -w)
go: count, err := sh.Echo("one two three").Command("wc", "-w").Output()
sh(in ubuntu): timeout 1s sleep 3
go: c := sh.Command("sleep", "3"); c.Start(); c.WaitTimeout(time.Second) # default SIGKILL
go: out, err := sh.Command("sleep", "3").SetTimeout(time.Second).Output() # set session timeout and get output)
sh: echo hello | cat
go: out, err := sh.Command("cat").SetInput("hello").Output()
sh: cat # read from stdin
go: out, err := sh.Command("cat").SetStdin(os.Stdin).Output()
If you need to keep env and dir, it is better to create a session
session := sh.NewSession()
session.SetEnv("BUILD_ID", "123")
session.SetDir("/")
# then call cmd
session.Command("echo", "hello").Run()
# set ShowCMD to true for easily debug
session.ShowCMD = true
for more information, it better to see docs.
[![Go Walker](http://gowalker.org/api/v1/badge)](http://gowalker.org/github.com/codeskyblue/go-sh)
### contribute
If you love this project, starring it will encourage the coder. Pull requests are welcome.
support the author: [alipay](https://me.alipay.com/goskyblue)
### thanks
this project is based on <http://github.com/codegangsta/inject>. thanks for the author.
# the reason to use Go shell
Sometimes we need to write shell scripts, but shell scripts are not good at working cross platform, Go, on the other hand, is good at that. Is there a good way to use Go to write shell like scripts? Using go-sh we can do this now.

View File

@@ -0,0 +1,41 @@
package main
import (
"fmt"
"log"
"github.com/codeskyblue/go-sh"
)
func main() {
sh.Command("echo", "hello").Run()
out, err := sh.Command("echo", "hello").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println("output is", string(out))
var a int
sh.Command("echo", "2").UnmarshalJSON(&a)
fmt.Println("a =", a)
s := sh.NewSession()
s.Alias("hi", "echo", "hi")
s.Command("hi", "boy").Run()
fmt.Print("pwd = ")
s.Command("pwd", sh.Dir("/")).Run()
if !sh.Test("dir", "data") {
sh.Command("echo", "mkdir", "data").Run()
}
sh.Command("echo", "hello", "world").
Command("awk", `{print "second arg is "$2}`).Run()
s.ShowCMD = true
s.Command("echo", "hello", "world").
Command("awk", `{print "second arg is "$2}`).Run()
s.SetEnv("BUILD_ID", "123").Command("bash", "-c", "echo $BUILD_ID").Run()
s.Command("bash", "-c", "echo current shell is $SHELL").Run()
}

View File

@@ -0,0 +1,7 @@
package main
import "github.com/codeskyblue/go-sh"
func main() {
sh.Command("less", "less.go").Run()
}

View File

@@ -0,0 +1,17 @@
package main
import (
"flag"
"fmt"
"github.com/codeskyblue/go-sh"
)
func main() {
flag.Parse()
if flag.NArg() != 1 {
fmt.Println("Usage: PROGRAM <file>")
return
}
sh.Command("tail", "-f", flag.Arg(0)).Run()
}

View File

@@ -0,0 +1,23 @@
package main
import (
"fmt"
"time"
sh "github.com/codeskyblue/go-sh"
)
func main() {
c := sh.Command("sleep", "3")
c.Start()
err := c.WaitTimeout(time.Second * 1)
if err != nil {
fmt.Printf("timeout should happend: %v\n", err)
}
// timeout should be a session
out, err := sh.Command("sleep", "2").SetTimeout(time.Second).Output()
fmt.Printf("output:(%s), err(%v)\n", string(out), err)
out, err = sh.Command("echo", "hello").SetTimeout(time.Second).Output()
fmt.Printf("output:(%s), err(%v)\n", string(out), err)
}

View File

@@ -0,0 +1,28 @@
package sh_test
import (
"fmt"
"github.com/codeskyblue/go-sh"
)
func ExampleCommand() {
out, err := sh.Command("echo", "hello").Output()
fmt.Println(string(out), err)
}
func ExampleCommandPipe() {
out, err := sh.Command("echo", "-n", "hi").Command("wc", "-c").Output()
fmt.Println(string(out), err)
}
func ExampleCommandSetDir() {
out, err := sh.Command("pwd", sh.Dir("/")).Output()
fmt.Println(string(out), err)
}
func ExampleTest() {
if sh.Test("dir", "mydir") {
fmt.Println("mydir exists")
}
}

View File

@@ -0,0 +1,148 @@
package sh
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"io"
"os"
"strings"
"syscall"
"time"
)
var ErrExecTimeout = errors.New("execute timeout")
// unmarshal shell output to decode json
func (s *Session) UnmarshalJSON(data interface{}) (err error) {
bufrw := bytes.NewBuffer(nil)
s.Stdout = bufrw
if err = s.Run(); err != nil {
return
}
return json.NewDecoder(bufrw).Decode(data)
}
// unmarshal command output into xml
func (s *Session) UnmarshalXML(data interface{}) (err error) {
bufrw := bytes.NewBuffer(nil)
s.Stdout = bufrw
if err = s.Run(); err != nil {
return
}
return xml.NewDecoder(bufrw).Decode(data)
}
// start command
func (s *Session) Start() (err error) {
s.started = true
var rd *io.PipeReader
var wr *io.PipeWriter
var length = len(s.cmds)
if s.ShowCMD {
var cmds = make([]string, 0, 4)
for _, cmd := range s.cmds {
cmds = append(cmds, strings.Join(cmd.Args, " "))
}
s.writePrompt(strings.Join(cmds, " | "))
}
for index, cmd := range s.cmds {
if index == 0 {
cmd.Stdin = s.Stdin
} else {
cmd.Stdin = rd
}
if index != length {
rd, wr = io.Pipe() // create pipe
cmd.Stdout = wr
cmd.Stderr = os.Stderr
}
if index == length-1 {
cmd.Stdout = s.Stdout
cmd.Stderr = s.Stderr
}
err = cmd.Start()
if err != nil {
return
}
}
return
}
// Should be call after Start()
// only catch the last command error
func (s *Session) Wait() (err error) {
for _, cmd := range s.cmds {
err = cmd.Wait()
wr, ok := cmd.Stdout.(*io.PipeWriter)
if ok {
wr.Close()
}
}
return err
}
func (s *Session) Kill(sig os.Signal) {
for _, cmd := range s.cmds {
if cmd.Process != nil {
cmd.Process.Signal(sig)
}
}
}
func (s *Session) WaitTimeout(timeout time.Duration) (err error) {
select {
case <-time.After(timeout):
s.Kill(syscall.SIGKILL)
return ErrExecTimeout
case err = <-Go(s.Wait):
return err
}
}
func Go(f func() error) chan error {
ch := make(chan error)
go func() {
ch <- f()
}()
return ch
}
func (s *Session) Run() (err error) {
if err = s.Start(); err != nil {
return
}
if s.timeout != time.Duration(0) {
return s.WaitTimeout(s.timeout)
}
return s.Wait()
}
func (s *Session) Output() (out []byte, err error) {
oldout := s.Stdout
defer func() {
s.Stdout = oldout
}()
stdout := bytes.NewBuffer(nil)
s.Stdout = stdout
err = s.Run()
out = stdout.Bytes()
return
}
func (s *Session) CombinedOutput() (out []byte, err error) {
oldout := s.Stdout
olderr := s.Stderr
defer func() {
s.Stdout = oldout
s.Stderr = olderr
}()
stdout := bytes.NewBuffer(nil)
s.Stdout = stdout
s.Stderr = stdout
err = s.Run()
out = stdout.Bytes()
return
}

View File

@@ -0,0 +1,126 @@
package sh
import (
"encoding/xml"
"io"
"os"
"os/exec"
"strings"
"testing"
"time"
)
func TestUnmarshalJSON(t *testing.T) {
var a int
s := NewSession()
s.ShowCMD = true
err := s.Command("echo", []string{"1"}).UnmarshalJSON(&a)
if err != nil {
t.Error(err)
}
if a != 1 {
t.Errorf("expect a tobe 1, but got %d", a)
}
}
func TestUnmarshalXML(t *testing.T) {
s := NewSession()
xmlSample := `<?xml version="1.0" encoding="utf-8"?>
<server version="1" />`
type server struct {
XMLName xml.Name `xml:"server"`
Version string `xml:"version,attr"`
}
data := &server{}
s.Command("echo", xmlSample).UnmarshalXML(data)
if data.Version != "1" {
t.Error(data)
}
}
func TestPipe(t *testing.T) {
s := NewSession()
s.ShowCMD = true
s.Call("echo", "hello")
err := s.Command("echo", "hi").Command("cat", "-n").Start()
if err != nil {
t.Error(err)
}
err = s.Wait()
if err != nil {
t.Error(err)
}
out, err := s.Command("echo", []string{"hello"}).Output()
if err != nil {
t.Error(err)
}
if string(out) != "hello\n" {
t.Error("capture wrong output:", out)
}
s.Command("echo", []string{"hello\tworld"}).Command("cut", []string{"-f2"}).Run()
}
func TestPipeCommand(t *testing.T) {
c1 := exec.Command("echo", "good")
rd, wr := io.Pipe()
c1.Stdout = wr
c2 := exec.Command("cat", "-n")
c2.Stdout = os.Stdout
c2.Stdin = rd
c1.Start()
c2.Start()
c1.Wait()
wc, ok := c1.Stdout.(io.WriteCloser)
if ok {
wc.Close()
}
c2.Wait()
}
func TestPipeInput(t *testing.T) {
s := NewSession()
s.ShowCMD = true
s.SetInput("first line\nsecond line\n")
out, err := s.Command("grep", "second").Output()
if err != nil {
t.Error(err)
}
if string(out) != "second line\n" {
t.Error("capture wrong output:", out)
}
}
func TestTimeout(t *testing.T) {
s := NewSession()
err := s.Command("sleep", "2").Start()
if err != nil {
t.Fatal(err)
}
err = s.WaitTimeout(time.Second)
if err != ErrExecTimeout {
t.Fatal(err)
}
}
func TestSetTimeout(t *testing.T) {
s := NewSession()
s.SetTimeout(time.Second)
defer s.SetTimeout(0)
err := s.Command("sleep", "2").Run()
if err != ErrExecTimeout {
t.Fatal(err)
}
}
func TestCombinedOutput(t *testing.T) {
s := NewSession()
bytes, err := s.Command("sh", "-c", "echo stderr >&2 ; echo stdout").CombinedOutput()
if err != nil {
t.Error(err)
}
stringOutput := string(bytes)
if !(strings.Contains(stringOutput, "stdout") && strings.Contains(stringOutput, "stderr")) {
t.Errorf("expect output from both output streams, got '%s'", strings.TrimSpace(stringOutput))
}
}

View File

@@ -0,0 +1,200 @@
/*
Package go-sh is intented to make shell call with golang more easily.
Some usage is more similar to os/exec, eg: Run(), Output(), Command(name, args...)
But with these similar function, pipe is added in and this package also got shell-session support.
Why I love golang so much, because the usage of golang is simple, but the power is unlimited. I want to make this pakcage got the sample style like golang.
// just like os/exec
sh.Command("echo", "hello").Run()
// support pipe
sh.Command("echo", "hello").Command("wc", "-c").Run()
// create a session to store dir and env
sh.NewSession().SetDir("/").Command("pwd")
// shell buildin command - "test"
sh.Test("dir", "mydir")
// like shell call: (cd /; pwd)
sh.Command("pwd", sh.Dir("/")) same with sh.Command(sh.Dir("/"), "pwd")
// output to json and xml easily
v := map[string] int {}
err = sh.Command("echo", `{"number": 1}`).UnmarshalJSON(&v)
*/
package sh
import (
"fmt"
"io"
"os"
"os/exec"
"reflect"
"strings"
"time"
"github.com/codegangsta/inject"
)
type Dir string
type Session struct {
inj inject.Injector
alias map[string][]string
cmds []*exec.Cmd
dir Dir
started bool
Env map[string]string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
ShowCMD bool // enable for debug
timeout time.Duration
}
func (s *Session) writePrompt(args ...interface{}) {
var ps1 = fmt.Sprintf("[golang-sh]$")
args = append([]interface{}{ps1}, args...)
fmt.Fprintln(s.Stderr, args...)
}
func NewSession() *Session {
env := make(map[string]string)
for _, key := range []string{"PATH"} {
env[key] = os.Getenv(key)
}
s := &Session{
inj: inject.New(),
alias: make(map[string][]string),
dir: Dir(""),
Stdin: strings.NewReader(""),
Stdout: os.Stdout,
Stderr: os.Stderr,
Env: env,
}
return s
}
func InteractiveSession() *Session {
s := NewSession()
s.SetStdin(os.Stdin)
return s
}
func Command(name string, a ...interface{}) *Session {
s := NewSession()
return s.Command(name, a...)
}
func Echo(in string) *Session {
s := NewSession()
return s.SetInput(in)
}
func (s *Session) Alias(alias, cmd string, args ...string) {
v := []string{cmd}
v = append(v, args...)
s.alias[alias] = v
}
func (s *Session) Command(name string, a ...interface{}) *Session {
var args = make([]string, 0)
var sType = reflect.TypeOf("")
// init cmd, args, dir, envs
// if not init, program may panic
s.inj.Map(name).Map(args).Map(s.dir).Map(map[string]string{})
for _, v := range a {
switch reflect.TypeOf(v) {
case sType:
args = append(args, v.(string))
default:
s.inj.Map(v)
}
}
if len(args) != 0 {
s.inj.Map(args)
}
s.inj.Invoke(s.appendCmd)
return s
}
// combine Command and Run
func (s *Session) Call(name string, a ...interface{}) error {
return s.Command(name, a...).Run()
}
/*
func (s *Session) Exec(cmd string, args ...string) error {
return s.Call(cmd, args)
}
*/
func (s *Session) SetEnv(key, value string) *Session {
s.Env[key] = value
return s
}
func (s *Session) SetDir(dir string) *Session {
s.dir = Dir(dir)
return s
}
func (s *Session) SetInput(in string) *Session {
s.Stdin = strings.NewReader(in)
return s
}
func (s *Session) SetStdin(r io.Reader) *Session {
s.Stdin = r
return s
}
func (s *Session) SetTimeout(d time.Duration) *Session {
s.timeout = d
return s
}
func newEnviron(env map[string]string, inherit bool) []string { //map[string]string {
environ := make([]string, 0, len(env))
if inherit {
for _, line := range os.Environ() {
for k, _ := range env {
if strings.HasPrefix(line, k+"=") {
goto CONTINUE
}
}
environ = append(environ, line)
CONTINUE:
}
}
for k, v := range env {
environ = append(environ, k+"="+v)
}
return environ
}
func (s *Session) appendCmd(cmd string, args []string, cwd Dir, env map[string]string) {
if s.started {
s.started = false
s.cmds = make([]*exec.Cmd, 0)
}
for k, v := range s.Env {
if _, ok := env[k]; !ok {
env[k] = v
}
}
environ := newEnviron(s.Env, true) // true: inherit sys-env
v, ok := s.alias[cmd]
if ok {
cmd = v[0]
args = append(v[1:], args...)
}
c := exec.Command(cmd, args...)
c.Env = environ
c.Dir = string(cwd)
s.cmds = append(s.cmds, c)
}

View File

@@ -0,0 +1,106 @@
package sh
import (
"fmt"
"log"
"runtime"
"strings"
"testing"
)
func TestAlias(t *testing.T) {
s := NewSession()
s.Alias("gr", "echo", "hi")
out, err := s.Command("gr", "sky").Output()
if err != nil {
t.Error(err)
}
if string(out) != "hi sky\n" {
t.Errorf("expect 'hi sky' but got:%s", string(out))
}
}
func ExampleSession_Command() {
s := NewSession()
out, err := s.Command("echo", "hello").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
// Output: hello
}
func ExampleSession_Command_pipe() {
s := NewSession()
out, err := s.Command("echo", "hello", "world").Command("awk", "{print $2}").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
// Output: world
}
func ExampleSession_Alias() {
s := NewSession()
s.Alias("alias_echo_hello", "echo", "hello")
out, err := s.Command("alias_echo_hello", "world").Output()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(out))
// Output: hello world
}
func TestEcho(t *testing.T) {
out, err := Echo("one two three").Command("wc", "-w").Output()
if err != nil {
t.Error(err)
}
if strings.TrimSpace(string(out)) != "3" {
t.Errorf("expect '3' but got:%s", string(out))
}
}
func TestSession(t *testing.T) {
if runtime.GOOS == "windows" {
t.Log("ignore test on windows")
return
}
session := NewSession()
session.ShowCMD = true
err := session.Call("pwd")
if err != nil {
t.Error(err)
}
out, err := session.SetDir("/").Command("pwd").Output()
if err != nil {
t.Error(err)
}
if string(out) != "/\n" {
t.Errorf("expect /, but got %s", string(out))
}
}
/*
#!/bin/bash -
#
export PATH=/usr/bin:/bin
alias ll='ls -l'
cd /usr
if test -d "local"
then
ll local | awk '{print $1, $NF}' | grep bin
fi
*/
func Example(t *testing.T) {
s := NewSession()
//s.ShowCMD = true
s.Env["PATH"] = "/usr/bin:/bin"
s.SetDir("/bin")
s.Alias("ll", "ls", "-l")
if s.Test("d", "local") {
//s.Command("ll", []string{"local"}).Command("awk", []string{"{print $1, $NF}"}).Command("grep", []string{"bin"}).Run()
s.Command("ll", "local").Command("awk", "{print $1, $NF}").Command("grep", "bin").Run()
}
}

View File

@@ -0,0 +1,64 @@
package sh
import (
"os"
"path/filepath"
)
func filetest(name string, modemask os.FileMode) (match bool, err error) {
fi, err := os.Stat(name)
if err != nil {
return
}
match = (fi.Mode() & modemask) == modemask
return
}
func (s *Session) pwd() string {
dir := string(s.dir)
if dir == "" {
dir, _ = os.Getwd()
}
return dir
}
func (s *Session) abspath(name string) string {
if filepath.IsAbs(name) {
return name
}
return filepath.Join(s.pwd(), name)
}
func init() {
//log.SetFlags(log.Lshortfile | log.LstdFlags)
}
// expression can be dir, file, link
func (s *Session) Test(expression string, argument string) bool {
var err error
var fi os.FileInfo
fi, err = os.Lstat(s.abspath(argument))
switch expression {
case "d", "dir":
return err == nil && fi.IsDir()
case "f", "file":
return err == nil && fi.Mode().IsRegular()
case "x", "executable":
/*
fmt.Println(expression, argument)
if err == nil {
fmt.Println(fi.Mode())
}
*/
return err == nil && fi.Mode()&os.FileMode(0100) != 0
case "L", "link":
return err == nil && fi.Mode()&os.ModeSymlink != 0
}
return false
}
// expression can be d,dir, f,file, link
func Test(exp string, arg string) bool {
s := NewSession()
return s.Test(exp, arg)
}

View File

@@ -0,0 +1,58 @@
package sh_test
import (
"testing"
"github.com/codeskyblue/go-sh"
)
var s = sh.NewSession()
type T struct{ *testing.T }
func NewT(t *testing.T) *T {
return &T{t}
}
func (t *T) checkTest(exp string, arg string, result bool) {
r := s.Test(exp, arg)
if r != result {
t.Errorf("test -%s %s, %v != %v", exp, arg, r, result)
}
}
func TestTest(i *testing.T) {
t := NewT(i)
t.checkTest("d", "../go-sh", true)
t.checkTest("d", "./yymm", false)
// file test
t.checkTest("f", "testdata/hello.txt", true)
t.checkTest("f", "testdata/xxxxx", false)
t.checkTest("f", "testdata/yymm", false)
// link test
t.checkTest("link", "testdata/linkfile", true)
t.checkTest("link", "testdata/xxxxxlinkfile", false)
t.checkTest("link", "testdata/hello.txt", false)
// executable test
t.checkTest("x", "testdata/executable", true)
t.checkTest("x", "testdata/xxxxx", false)
t.checkTest("x", "testdata/hello.txt", false)
}
func ExampleShellTest(t *testing.T) {
// test -L
sh.Test("link", "testdata/linkfile")
sh.Test("L", "testdata/linkfile")
// test -f
sh.Test("file", "testdata/file")
sh.Test("f", "testdata/file")
// test -x
sh.Test("executable", "testdata/binfile")
sh.Test("x", "testdata/binfile")
// test -d
sh.Test("dir", "testdata/dir")
sh.Test("d", "testdata/dir")
}

View File

View File

View File

@@ -0,0 +1 @@
hello.txt

View File

@@ -0,0 +1,28 @@
box: wercker/golang
# Build definition
build:
# The steps that will be executed on build
steps:
# Sets the go workspace and places you package
# at the right place in the workspace tree
- setup-go-workspace
# Gets the dependencies
- script:
name: go get
code: |
cd $WERCKER_SOURCE_DIR
go version
go get -t .
# Build the project
- script:
name: go build
code: |
go build .
# Test the project
- script:
name: go test
code: |
go test -v ./...