sh

package module
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 11, 2023 License: MIT Imports: 16 Imported by: 0

README

go-sh

go写的shell脚本处理包,为提高工作效率而开发

  • 支持执行多条命令,并等待所有后台任务结束
  • 自定义实时输出方式
  • 自定义执行ID生成方式,便于追踪执行记录
  • 可快捷指定shell类型和Set-Builtin
  • 支持获取执行完所在的工作目录,便于设置下一次执行的工作目录
  • 支持根据命令生成脚本文件去执行,可存储每次执行脚本
  • 可全局设置一些选项,减少每次生成去设置的工作量

Contents

Installation

go get -u github.com/zdz1715/go-sh@latest

Quick start

package main

import (
	"fmt"
	"os"

	"github.com/zdz1715/go-sh"
)

func main() {
	e, err := sh.NewExec()
	if err != nil {
		fmt.Printf("new exec fail:%s\n", err)
		return
	}

	dir, _ := os.Getwd()
	fmt.Printf("[%s] %s\n", dir, e.String())

	e.AddCommand("echo", "pwd: $PWD")
	e.AddCommand("cd", "/")
	// 后台执行
	e.AddCommand("sleep 5 &")

	// 添加多行脚本,配合存储可以生成脚本文件,不调用Run()就不会执行
	e.AddRawCommand([]byte(`
# hello world
hello() {
	echo hello world
}

hello
`))

	if err = e.Run("echo command-1 | cut -d '-' -f2", "echo command2"); err != nil {
		fmt.Printf("exec fail:%s\n", err)
	}

	fmt.Println("exec last work dir:", e.GetLastWorkDir())
}

/*
[go-sh] /bin/bash -ex -o pipefail
+ cd /
+ hello
+ echo hello world
hello world
+ sleep 5
+ echo command-1
+ cut -d - -f2
1
+ echo command2
command2
exec last work dir: /
*/

Examples

全局设置执行选项

如果没有单独的设置,全局设置则会覆盖,有则不会覆盖

package main

import (
	"fmt"

	"github.com/zdz1715/go-sh/shell"

	"github.com/zdz1715/go-sh"
)

func main() {
	// 设置全局执行的工作目录
	sh.SetGlobalExecWorkDir("/usr")
	// 设置全局执行的用户
	sh.SetGlobalExecUser("")
	// 设置全局执行的输出方法
	sh.SetGlobalExecOutput(func(num int, line []byte) {
		fmt.Println(string(line))
	})
	// 设置全局执行脚本存储方式
	sh.SetGlobalStorage(&sh.Storage{
		Dir: "/tmp",
		//NotAutoClean: true,
	})
	// 设置全局的id生成方式
	sh.SetGlobalIDCreator(func() string {
		return "jenkins-" + sh.XidCreator()
	})

	// 设置全局的shell 类型
	sh.SetGlobalShell(&shell.Shell{
		Type: shell.Sh,
	})

	e1, _ := sh.NewExec()
	e2, _ := sh.NewExec()
	e3, _ := sh.NewExec()
	e1.Run("echo e1: $(pwd)")
	e2.Run("echo e2: $(pwd)")
	e3.Run("echo e3: $(pwd)")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckStorage added in v0.1.3

func CheckStorage(s *Storage) (bool, error)

func IsDeadlineExceeded

func IsDeadlineExceeded(err error) bool

func SetGlobalExecOutput added in v0.1.2

func SetGlobalExecOutput(f func(num int, line []byte))

SetGlobalExecOutput Sets the output func for execution globally. If the output func has been set separately, it will not be overwritten.

func SetGlobalExecUser added in v0.1.2

func SetGlobalExecUser(user string)

SetGlobalExecUser Sets the user for execution globally. If the user has been set separately, it will not be overwritten.

func SetGlobalExecWorkDir added in v0.1.2

func SetGlobalExecWorkDir(dir string)

SetGlobalExecWorkDir Sets the working directory for execution globally. If the working directory has been set separately, it will not be overwritten.

func SetGlobalIDCreator added in v0.1.2

func SetGlobalIDCreator(creator IDCreator)

SetGlobalIDCreator Sets the ID Creator for execution globally. If the ID Creator has been set separately, it will not be overwritten.

func SetGlobalShell added in v0.1.2

func SetGlobalShell(shell *shell.Shell)

SetGlobalShell Sets the shell for execution globally. If the shell has been set separately, it will not be overwritten.

func SetGlobalStorage added in v0.1.2

func SetGlobalStorage(storage *Storage)

SetGlobalStorage Sets the storage for execution globally. If the storage has been set separately, it will not be overwritten.

Types

type Exec

type Exec struct {
	// contains filtered or unexported fields
}

func NewExec

func NewExec(execOpts ...*ExecOptions) (*Exec, error)

func NewExecContext added in v0.1.3

func NewExecContext(ctx context.Context, execOpts ...*ExecOptions) (*Exec, error)

func (*Exec) AddCommand

func (e *Exec) AddCommand(name string, args ...string) error

func (*Exec) AddRawCommand

func (e *Exec) AddRawCommand(raw []byte) error

func (*Exec) Cancel

func (e *Exec) Cancel() error

Cancel this execution

func (*Exec) Finished

func (e *Exec) Finished() bool

Finished returns the value of whether it is finished

func (*Exec) GetLastWorkDir added in v0.1.3

func (e *Exec) GetLastWorkDir() string

func (*Exec) ID

func (e *Exec) ID() string

func (*Exec) Run

func (e *Exec) Run(command ...string) error

func (*Exec) String

func (e *Exec) String() string

type ExecError

type ExecError struct {
	ID      string
	Context context.Context
	Err     error
}

func (*ExecError) Error

func (e *ExecError) Error() string

type ExecOptions

type ExecOptions struct {
	IDCreator IDCreator
	Shell     *shell.Shell
	Storage   *Storage
	User      string
	WorkDir   string
	Output    func(num int, line []byte)
}

func GlobalExecOptionsOverwrite added in v0.1.3

func GlobalExecOptionsOverwrite(opts ...*ExecOptions) *ExecOptions

func (*ExecOptions) Copy added in v0.1.3

func (e *ExecOptions) Copy() *ExecOptions

type IDCreator

type IDCreator func() string
var XidCreator IDCreator = func() string {
	return xid.New().String()
}

type Storage

type Storage struct {
	Dir          string
	NotAutoClean bool
}

func (*Storage) CreateFile added in v0.1.3

func (s *Storage) CreateFile(filename string) (*os.File, error)

func (*Storage) RemoveOrTruncate added in v0.1.3

func (s *Storage) RemoveOrTruncate(file *os.File, size int64) error

func (*Storage) Truncate added in v0.1.3

func (s *Storage) Truncate(file *os.File, size int64) error

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL