aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2022-08-01 23:00:11 +0700
committerShulhan <ms@kilabit.info>2022-08-01 23:00:11 +0700
commit70799d835b68a32db97843fe0c26ae0055adbacf (patch)
tree838541bb2c9d9a136a90a114aa1f22fb04d482eb
parent166e1cd18cf104d0b9a81feeafd7365a78d7499e (diff)
downloadawwan-70799d835b68a32db97843fe0c26ae0055adbacf.tar.xz
all: clean up codes
Replace ":=" with explicit variable declaration with types for clarity and minimizing duplicate variables.
-rw-r--r--awwan.go90
-rw-r--r--http_api.go93
-rw-r--r--script.go56
-rw-r--r--script_example_test.go20
-rw-r--r--script_test.go28
-rw-r--r--session.go102
-rw-r--r--statement.go19
-rw-r--r--template.go17
8 files changed, 289 insertions, 136 deletions
diff --git a/awwan.go b/awwan.go
index f343068..1bb8db4 100644
--- a/awwan.go
+++ b/awwan.go
@@ -74,7 +74,9 @@ type Awwan struct {
// Awwan workspace.
// If baseDir is empty, it will set to current working directory.
func New(baseDir string) (aww *Awwan, err error) {
- logp := "New"
+ var (
+ logp = "New"
+ )
aww = &Awwan{}
@@ -120,7 +122,13 @@ func (aww *Awwan) Build() (err error) {
}
func (aww *Awwan) Local(req *Request) (err error) {
- logp := "Local"
+ var (
+ logp = "Local"
+
+ ses *Session
+ sessionDir string
+ maxLines int
+ )
req.scriptPath = filepath.Clean(req.Script)
req.scriptPath, err = filepath.Abs(req.scriptPath)
@@ -128,9 +136,9 @@ func (aww *Awwan) Local(req *Request) (err error) {
return fmt.Errorf("%s: %w", logp, err)
}
- sessionDir := filepath.Dir(req.scriptPath)
+ sessionDir = filepath.Dir(req.scriptPath)
- ses, err := NewSession(aww.BaseDir, sessionDir)
+ ses, err = NewSession(aww.BaseDir, sessionDir)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
@@ -149,7 +157,7 @@ func (aww *Awwan) Local(req *Request) (err error) {
return fmt.Errorf("%s: %w", logp, err)
}
- maxLines := len(req.script.stmts)
+ maxLines = len(req.script.stmts)
if req.BeginAt >= maxLines {
return fmt.Errorf("%s: start index %d out of range %d", logp,
req.BeginAt, maxLines)
@@ -181,7 +189,16 @@ func (aww *Awwan) Local(req *Request) (err error) {
}
func (aww *Awwan) Play(req *Request) (err error) {
- logp := "Play"
+ var (
+ logp = "Play"
+
+ sessionDir string
+ ses *Session
+ sshSection *config.Section
+ mkdirStmt string
+ rmdirStmt string
+ maxLines int
+ )
req.scriptPath = filepath.Clean(req.Script)
req.scriptPath, err = filepath.Abs(req.scriptPath)
@@ -189,9 +206,9 @@ func (aww *Awwan) Play(req *Request) (err error) {
return fmt.Errorf("%s: %w", logp, err)
}
- sessionDir := filepath.Dir(req.scriptPath)
+ sessionDir = filepath.Dir(req.scriptPath)
- ses, err := NewSession(aww.BaseDir, sessionDir)
+ ses, err = NewSession(aww.BaseDir, sessionDir)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
@@ -208,7 +225,7 @@ func (aww *Awwan) Play(req *Request) (err error) {
}
}
- sshSection := aww.sshConfig.Get(ses.hostname)
+ sshSection = aww.sshConfig.Get(ses.hostname)
if sshSection == nil {
return fmt.Errorf("%s: can not find Host %q in SSH config", logp, ses.hostname)
}
@@ -227,7 +244,7 @@ func (aww *Awwan) Play(req *Request) (err error) {
return fmt.Errorf("%s: %w", logp, err)
}
- maxLines := len(req.script.stmts)
+ maxLines = len(req.script.stmts)
if req.BeginAt >= maxLines {
return fmt.Errorf("%s: start index %d out of range %d", logp, req.BeginAt, maxLines)
}
@@ -236,15 +253,15 @@ func (aww *Awwan) Play(req *Request) (err error) {
}
// Create temporary directory ...
- mkdirStmt := fmt.Sprintf("mkdir %s", ses.tmpDir)
+ mkdirStmt = fmt.Sprintf("mkdir %s", ses.tmpDir)
err = ses.sshClient.Execute(mkdirStmt)
if err != nil {
return fmt.Errorf("%s: %s: %w", logp, mkdirStmt, err)
}
defer func() {
- rmdirStmt := fmt.Sprintf("rm -rf %s", ses.tmpDir)
- err := ses.sshClient.Execute(rmdirStmt)
+ rmdirStmt = fmt.Sprintf("rm -rf %s", ses.tmpDir)
+ err = ses.sshClient.Execute(rmdirStmt)
if err != nil {
log.Printf("%s: %s", logp, err)
}
@@ -262,20 +279,22 @@ func (aww *Awwan) Play(req *Request) (err error) {
// Serve start the web-user interface that serve awwan actions through HTTP.
func (aww *Awwan) Serve() (err error) {
- logp := "Serve"
-
- envDev := os.Getenv(envDevelopment)
+ var (
+ logp = "Serve"
+ envDev = os.Getenv(envDevelopment)
+ memfsBaseOpts = &memfs.Options{
+ Root: aww.BaseDir,
+ Excludes: []string{
+ `.*/\.git`,
+ "node_modules",
+ "vendor",
+ `.*\.(bz|bz2|gz|iso|jar|tar|xz|zip)`,
+ },
+ TryDirect: true, // Only store the file structures in the memory.
+ }
- memfsBaseOpts := &memfs.Options{
- Root: aww.BaseDir,
- Excludes: []string{
- `.*/\.git`,
- "node_modules",
- "vendor",
- `.*\.(bz|bz2|gz|iso|jar|tar|xz|zip)`,
- },
- TryDirect: true, // Only store the file structures in the memory.
- }
+ serverOpts *http.ServerOptions
+ )
aww.memfsBase, err = memfs.New(memfsBaseOpts)
if err != nil {
@@ -286,7 +305,7 @@ func (aww *Awwan) Serve() (err error) {
go aww.workerBuild()
}
- serverOpts := &http.ServerOptions{
+ serverOpts = &http.ServerOptions{
Memfs: mfsWww,
Address: defListenAddress,
}
@@ -308,21 +327,28 @@ func (aww *Awwan) Serve() (err error) {
// loadSshConfig load all SSH config from user's home and the awwan base
// directoy.
func (aww *Awwan) loadSshConfig() (err error) {
- logp := "loadSshConfig"
+ var (
+ logp = "loadSshConfig"
- homeDir, err := os.UserHomeDir()
+ baseDirConfig *config.Config
+ homeDir string
+ configFile string
+ )
+
+ homeDir, err = os.UserHomeDir()
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
- configFile := filepath.Join(homeDir, defSshDir, defSshConfig)
+ configFile = filepath.Join(homeDir, defSshDir, defSshConfig)
aww.sshConfig, err = config.Load(configFile)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
configFile = filepath.Join(aww.BaseDir, defSshDir, defSshConfig)
- baseDirConfig, err := config.Load(configFile)
+
+ baseDirConfig, err = config.Load(configFile)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
@@ -457,7 +483,7 @@ func doBuildTypeScript(esBuildOptions *api.BuildOptions) (err error) {
}
func initMemfsWww() (err error) {
- mfsOpts := &memfs.Options{
+ var mfsOpts = &memfs.Options{
Root: "_www",
Includes: []string{
`.*\.(js|html|png|ico)$`,
diff --git a/http_api.go b/http_api.go
index bb3e5c8..a0b3163 100644
--- a/http_api.go
+++ b/http_api.go
@@ -15,6 +15,7 @@ import (
libbytes "github.com/shuLhan/share/lib/bytes"
libhttp "github.com/shuLhan/share/lib/http"
+ "github.com/shuLhan/share/lib/memfs"
)
const (
@@ -31,7 +32,9 @@ type fsRequest struct {
}
func (aww *Awwan) registerHttpApis() (err error) {
- logp := "registerHttpApis"
+ var (
+ logp = "registerHttpApis"
+ )
err = aww.httpd.RegisterEndpoint(&libhttp.Endpoint{
Method: libhttp.RequestMethodGet,
@@ -44,14 +47,13 @@ func (aww *Awwan) registerHttpApis() (err error) {
return fmt.Errorf("%s: %w", logp, err)
}
- apiFsDelete := &libhttp.Endpoint{
+ err = aww.httpd.RegisterEndpoint(&libhttp.Endpoint{
Method: libhttp.RequestMethodDelete,
Path: httpApiFs,
RequestType: libhttp.RequestTypeJSON,
ResponseType: libhttp.ResponseTypeJSON,
Call: aww.httpApiFsDelete,
- }
- err = aww.httpd.RegisterEndpoint(apiFsDelete)
+ })
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
@@ -94,17 +96,22 @@ func (aww *Awwan) registerHttpApis() (err error) {
// httpApiFs get the list of files or specific file using query parameter
// "path".
-func (aww *Awwan) httpApiFs(epr *libhttp.EndpointRequest) ([]byte, error) {
- res := &libhttp.EndpointResponse{}
+func (aww *Awwan) httpApiFs(epr *libhttp.EndpointRequest) (resb []byte, err error) {
+ var (
+ res = &libhttp.EndpointResponse{}
+
+ node *memfs.Node
+ path string
+ )
- path := epr.HttpRequest.Form.Get(paramNamePath)
+ path = epr.HttpRequest.Form.Get(paramNamePath)
if len(path) == 0 {
res.Code = http.StatusOK
res.Data = aww.memfsBase
return json.Marshal(res)
}
- node, err := aww.memfsBase.Get(path)
+ node, err = aww.memfsBase.Get(path)
if err != nil {
return nil, err
}
@@ -144,38 +151,44 @@ func (aww *Awwan) httpApiFs(epr *libhttp.EndpointRequest) ([]byte, error) {
// - 400: Bad request.
// - 401: Unauthorized.
// - 404: File not found.
-func (aww *Awwan) httpApiFsDelete(epr *libhttp.EndpointRequest) ([]byte, error) {
- logp := "httpApiFsDelete"
+func (aww *Awwan) httpApiFsDelete(epr *libhttp.EndpointRequest) (resb []byte, err error) {
+ var (
+ logp = "httpApiFsDelete"
+ res = &libhttp.EndpointResponse{}
+ req = &fsRequest{}
+
+ parentPath string
+ sysPath string
+ nodeParent *memfs.Node
+ )
- res := &libhttp.EndpointResponse{}
res.Code = http.StatusBadRequest
- req := &fsRequest{}
- err := json.Unmarshal(epr.RequestBody, req)
+ err = json.Unmarshal(epr.RequestBody, req)
if err != nil {
res.Message = err.Error()
return nil, res
}
- parentPath := path.Dir(req.Path)
- nodeParent := aww.memfsBase.PathNodes.Get(parentPath)
+ parentPath = path.Dir(req.Path)
+ nodeParent = aww.memfsBase.PathNodes.Get(parentPath)
if nodeParent == nil {
res.Message = fmt.Sprintf("%s: invalid path %s", logp, req.Path)
return nil, res
}
- path := filepath.Join(nodeParent.SysPath, path.Base(req.Path))
- path, err = filepath.Abs(path)
+ sysPath = filepath.Join(nodeParent.SysPath, path.Base(req.Path))
+ sysPath, err = filepath.Abs(sysPath)
if err != nil {
res.Message = fmt.Sprintf("%s: %s", logp, err)
return nil, res
}
- if !strings.HasPrefix(path, aww.memfsBase.Opts.Root) {
- res.Message = fmt.Sprintf("%s: invalid path %q", logp, path)
+ if !strings.HasPrefix(sysPath, aww.memfsBase.Opts.Root) {
+ res.Message = fmt.Sprintf("%s: invalid path %q", logp, sysPath)
return nil, res
}
- err = os.Remove(path)
+ err = os.Remove(sysPath)
if err != nil {
res.Code = http.StatusInternalServerError
res.Message = fmt.Sprintf("%s: %s", logp, err)
@@ -183,7 +196,7 @@ func (aww *Awwan) httpApiFsDelete(epr *libhttp.EndpointRequest) ([]byte, error)
}
res.Code = http.StatusOK
- res.Message = fmt.Sprintf("%s: %q has been removed", logp, path)
+ res.Message = fmt.Sprintf("%s: %q has been removed", logp, sysPath)
return json.Marshal(res)
}
@@ -206,6 +219,12 @@ func (aww *Awwan) httpApiFsPost(epr *libhttp.EndpointRequest) (rawBody []byte, e
logp = "httpApiFsPost"
res = &libhttp.EndpointResponse{}
req = &fsRequest{}
+
+ nodeParent *memfs.Node
+ node *memfs.Node
+ fi os.FileInfo
+ parentPath string
+ sysPath string
)
res.Code = http.StatusBadRequest
@@ -216,13 +235,13 @@ func (aww *Awwan) httpApiFsPost(epr *libhttp.EndpointRequest) (rawBody []byte, e
return nil, res
}
- parentPath := path.Dir(req.Path)
- nodeParent := aww.memfsBase.PathNodes.Get(parentPath)
+ parentPath = path.Dir(req.Path)
+ nodeParent = aww.memfsBase.PathNodes.Get(parentPath)
if nodeParent == nil {
res.Message = fmt.Sprintf("%s: invalid path %s", logp, req.Path)
return nil, res
}
- node := aww.memfsBase.PathNodes.Get(req.Path)
+ node = aww.memfsBase.PathNodes.Get(req.Path)
if node != nil {
res.Message = fmt.Sprintf("%s: file exist", logp)
return nil, res
@@ -230,27 +249,27 @@ func (aww *Awwan) httpApiFsPost(epr *libhttp.EndpointRequest) (rawBody []byte, e
res.Code = http.StatusInternalServerError
- path := filepath.Join(nodeParent.SysPath, path.Base(req.Path))
- path, err = filepath.Abs(path)
+ sysPath = filepath.Join(nodeParent.SysPath, path.Base(req.Path))
+ sysPath, err = filepath.Abs(sysPath)
if err != nil {
res.Message = fmt.Sprintf("%s: %s", logp, err)
return nil, res
}
- if !strings.HasPrefix(path, aww.memfsBase.Opts.Root) {
- res.Message = fmt.Sprintf("%s: invalid path %q", logp, path)
+ if !strings.HasPrefix(sysPath, aww.memfsBase.Opts.Root) {
+ res.Message = fmt.Sprintf("%s: invalid path %q", logp, sysPath)
return nil, res
}
if req.IsDir {
- err = os.Mkdir(path, 0700)
+ err = os.Mkdir(sysPath, 0700)
} else {
- err = os.WriteFile(path, nil, 0600)
+ err = os.WriteFile(sysPath, nil, 0600)
}
if err != nil {
res.Message = fmt.Sprintf("%s: %s", logp, err)
return nil, res
}
- fi, err := os.Stat(path)
+ fi, err = os.Stat(sysPath)
if err != nil {
res.Message = fmt.Sprintf("%s: %s", logp, err)
return nil, res
@@ -274,6 +293,8 @@ func (aww *Awwan) httpApiFsPut(epr *libhttp.EndpointRequest) (rawBody []byte, er
logp = "httpApiFsPut"
res = &libhttp.EndpointResponse{}
req = &fsRequest{}
+
+ node *memfs.Node
)
res.Code = http.StatusInternalServerError
@@ -284,7 +305,7 @@ func (aww *Awwan) httpApiFsPut(epr *libhttp.EndpointRequest) (rawBody []byte, er
return nil, res
}
- node := aww.memfsBase.PathNodes.Get(req.Path)
+ node = aww.memfsBase.PathNodes.Get(req.Path)
if node == nil {
res.Code = http.StatusNotFound
res.Message = fmt.Sprintf("%s: invalid or empty path %s", logp, req.Path)
@@ -303,16 +324,18 @@ func (aww *Awwan) httpApiFsPut(epr *libhttp.EndpointRequest) (rawBody []byte, er
return json.Marshal(res)
}
-func (aww *Awwan) httpApiExecute(epr *libhttp.EndpointRequest) ([]byte, error) {
+func (aww *Awwan) httpApiExecute(epr *libhttp.EndpointRequest) (resb []byte, err error) {
var (
logp = "httpApiExecute"
req = NewRequest()
res = &libhttp.EndpointResponse{}
+
+ data *HttpResponse
)
res.Code = http.StatusInternalServerError
- err := json.Unmarshal(epr.RequestBody, req)
+ err = json.Unmarshal(epr.RequestBody, req)
if err != nil {
res.Message = fmt.Sprintf("%s: %s", logp, err)
return nil, res
@@ -343,7 +366,7 @@ func (aww *Awwan) httpApiExecute(epr *libhttp.EndpointRequest) ([]byte, error) {
return nil, res
}
- data := &HttpResponse{
+ data = &HttpResponse{
Request: req,
Stdout: libbytes.Copy(aww.bufout.Bytes()),
Stderr: libbytes.Copy(aww.buferr.Bytes()),
diff --git a/script.go b/script.go
index 6ca0d27..3e2a380 100644
--- a/script.go
+++ b/script.go
@@ -74,9 +74,17 @@ func ParseScriptForRemote(ses *Session, content []byte) (s *Script, err error) {
func parseScript(ses *Session, content []byte, isLocal bool) (script *Script, err error) {
var (
logp = "parseScript"
- tmpl *template.Template
- buf bytes.Buffer
- raw []byte
+
+ tmpl *template.Template
+ buf bytes.Buffer
+ stmt *Statement
+ line []byte
+ raw []byte
+ splits [][]byte
+ rawLines [][]byte
+ stmts []*Statement
+ requires []*Statement
+ x int
)
// Apply the session variables.
@@ -100,20 +108,20 @@ func parseScript(ses *Session, content []byte, isLocal bool) (script *Script, er
}
raw = bytes.TrimRight(raw, " \t\r\n\v")
- splits := bytes.Split(raw, newLine)
+ splits = bytes.Split(raw, newLine)
// Add empty line at the beginning to make the start index start from
// 1, not 0.
- rawLines := [][]byte{newLine}
+ rawLines = [][]byte{newLine}
rawLines = append(rawLines, splits...)
rawLines = joinStatements(rawLines)
rawLines = joinRequireStatements(rawLines)
- stmts := make([]*Statement, len(rawLines))
- requires := make([]*Statement, len(rawLines))
+ stmts = make([]*Statement, len(rawLines))
+ requires = make([]*Statement, len(rawLines))
- for x, line := range rawLines {
- stmt, err := ParseStatement(line)
+ for x, line = range rawLines {
+ stmt, err = ParseStatement(line)
if err != nil {
return nil, fmt.Errorf("%s: line %d: %w", logp, x, err)
}
@@ -155,12 +163,17 @@ func parseScript(ses *Session, content []byte, isLocal bool) (script *Script, er
//
// will be leave as is.
func joinRequireStatements(in [][]byte) (out [][]byte) {
+ var (
+ stmt []byte
+ x int
+ )
+
out = make([][]byte, len(in))
if len(in) > 0 {
out[0] = in[0]
}
- for x := 1; x < len(in); x++ {
- stmt := in[x]
+ for x = 1; x < len(in); x++ {
+ stmt = in[x]
if !bytes.HasPrefix(stmt, cmdMagicRequire) {
out[x] = in[x]
continue
@@ -204,20 +217,29 @@ func joinRequireStatements(in [][]byte) (out [][]byte) {
// a b
// c
func joinStatements(in [][]byte) (out [][]byte) {
+ var (
+ stmt []byte
+ nextStmt []byte
+ x int
+ y int
+ endc int
+ lastc byte
+ )
+
out = make([][]byte, len(in))
if len(in) > 0 {
out[0] = nil
}
- for x := 1; x < len(in); x++ {
- stmt := bytes.TrimSpace(in[x])
+ for x = 1; x < len(in); x++ {
+ stmt = bytes.TrimSpace(in[x])
if len(stmt) == 0 {
in[x] = nil
out[x] = nil
continue
}
- endc := len(stmt) - 1
+ endc = len(stmt) - 1
if stmt[endc] != '\\' {
in[x] = nil
out[x] = stmt
@@ -227,9 +249,9 @@ func joinStatements(in [][]byte) (out [][]byte) {
stmt = bytes.TrimRight(stmt, "\\ \t")
stmt = append(stmt, ' ')
- y := x + 1
+ y = x + 1
for ; y < len(in); y++ {
- nextStmt := bytes.TrimSpace(in[y])
+ nextStmt = bytes.TrimSpace(in[y])
if len(nextStmt) == 0 {
in[y] = nil
out[y] = nil
@@ -237,7 +259,7 @@ func joinStatements(in [][]byte) (out [][]byte) {
}
endc = len(nextStmt) - 1
- lastc := nextStmt[endc]
+ lastc = nextStmt[endc]
if lastc == '\\' {
nextStmt = bytes.TrimRight(nextStmt, "\\ \t")
diff --git a/script_example_test.go b/script_example_test.go
index f6e4fc3..724dafd 100644
--- a/script_example_test.go
+++ b/script_example_test.go
@@ -9,28 +9,36 @@ import (
)
func ExampleParseScriptForLocal() {
- envContent := `
+ var (
+ envContent = `
[section]
key=value
`
- scriptContent := `
+ scriptContent = `
multiline\
command {{.Val "section::key"}};\
end;
`
- ses := &Session{}
- err := ses.loadEnvFromBytes([]byte(envContent))
+
+ ses = &Session{}
+
+ s *Script
+ err error
+ stmt []byte
+ )
+
+ err = ses.loadEnvFromBytes([]byte(envContent))
if err != nil {
log.Fatal(err)
}
- s, err := ParseScriptForLocal(ses, []byte(scriptContent))
+ s, err = ParseScriptForLocal(ses, []byte(scriptContent))
if err != nil {
log.Fatal(err)
}
- for _, stmt := range s.rawLines {
+ for _, stmt = range s.rawLines {
fmt.Printf("%s\n", stmt)
}
// Output:
diff --git a/script_test.go b/script_test.go
index 7591451..1253813 100644
--- a/script_test.go
+++ b/script_test.go
@@ -11,7 +11,13 @@ import (
)
func TestJoinRequireStatements(t *testing.T) {
- in := bytes.Split([]byte(`
+ var (
+ in [][]byte
+ exp [][]byte
+ got [][]byte
+ )
+
+ in = bytes.Split([]byte(`
#require:
a
b
@@ -20,7 +26,7 @@ b
#get:
#require:`), newLine)
- exp := [][]byte{
+ exp = [][]byte{
nil,
[]byte("#require: a"),
nil,
@@ -31,15 +37,17 @@ b
nil,
}
- got := joinRequireStatements(in)
+ got = joinRequireStatements(in)
test.Assert(t, "joinRequireStatements", exp, got)
}
func TestJoinStatements(t *testing.T) {
- cases := []struct {
+ type testCase struct {
in [][]byte
exp [][]byte
- }{{
+ }
+
+ var cases = []testCase{{
in: bytes.Split([]byte(`
a
b \
@@ -59,8 +67,14 @@ g`), newLine),
[]byte("g"),
},
}}
- for _, c := range cases {
- got := joinStatements(c.in)
+
+ var (
+ c testCase
+ got [][]byte
+ )
+
+ for _, c = range cases {
+ got = joinStatements(c.in)
test.Assert(t, "joinStatements", c.exp, got)
}
}
diff --git a/session.go b/session.go
index 4942a33..8e3b64b 100644
--- a/session.go
+++ b/session.go
@@ -43,7 +43,11 @@ type Session struct {
// NewSession create and initialize the new session based on Awwan base
// directory and the session directory.
func NewSession(baseDir, sessionDir string) (ses *Session, err error) {
- logp := "newSession"
+ var (
+ logp = "newSession"
+
+ randomString string
+ )
ses = &Session{
BaseDir: baseDir,
@@ -57,7 +61,7 @@ func NewSession(baseDir, sessionDir string) (ses *Session, err error) {
}
rand.Seed(time.Now().Unix())
- randomString := string(ascii.Random([]byte(ascii.LettersNumber), 16))
+ randomString = string(ascii.Random([]byte(ascii.LettersNumber), 16))
ses.tmpDir = filepath.Join(defTmpDir, randomString)
return ses, nil
@@ -85,7 +89,13 @@ func (ses *Session) Vals(keyPath string) []string {
// Copy file in local system.
func (ses *Session) Copy(stmt *Statement) (err error) {
- logp := "Copy"
+ var (
+ logp = "Copy"
+
+ src string
+ dest string
+ )
+
if len(stmt.cmd) == 0 {
return fmt.Errorf("%s: missing source argument", logp)
}
@@ -96,12 +106,12 @@ func (ses *Session) Copy(stmt *Statement) (err error) {
return fmt.Errorf("%s: two or more destination arguments is given", logp)
}
- src, err := parseTemplate(ses, stmt.cmd)
+ src, err = parseTemplate(ses, stmt.cmd)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
- dest := stmt.args[0]
+ dest = stmt.args[0]
err = libio.Copy(dest, src)
if err != nil {
@@ -112,7 +122,13 @@ func (ses *Session) Copy(stmt *Statement) (err error) {
// Get copy file from remote to local.
func (ses *Session) Get(stmt *Statement) (err error) {
- logp := "Get"
+ var (
+ logp = "Get"
+
+ remote string
+ local string
+ )
+
if len(stmt.cmd) == 0 {
return fmt.Errorf("%s: missing source argument", logp)
}
@@ -123,8 +139,8 @@ func (ses *Session) Get(stmt *Statement) (err error) {
return fmt.Errorf("%s: two or more destination arguments is given", logp)
}
- remote := stmt.cmd
- local := stmt.args[0]
+ remote = stmt.cmd
+ local = stmt.args[0]
if ses.sftpc == nil {
err = ses.sshClient.ScpGet(remote, local)
@@ -139,7 +155,13 @@ func (ses *Session) Get(stmt *Statement) (err error) {
// Put copy file from local to remote system.
func (ses *Session) Put(stmt *Statement) (err error) {
- logp := "Put"
+ var (
+ logp = "Put"
+
+ local string
+ remote string
+ )
+
if len(stmt.cmd) == 0 {
return fmt.Errorf("%s: missing source argument", logp)
}
@@ -150,12 +172,12 @@ func (ses *Session) Put(stmt *Statement) (err error) {
return fmt.Errorf("%s: two or more destination arguments is given", logp)
}
- local, err := parseTemplate(ses, stmt.cmd)
+ local, err = parseTemplate(ses, stmt.cmd)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
- remote := stmt.args[0]
+ remote = stmt.args[0]
if ses.sftpc == nil {
err = ses.sshClient.ScpPut(local, remote)
@@ -213,7 +235,17 @@ func (ses *Session) SudoCopy(req *Request, stmt *Statement, withParseInput bool)
// SudoGet copy file from remote that can be accessed by root on remote, to
// local.
func (ses *Session) SudoGet(stmt *Statement) (err error) {
- logp := "SudoGet"
+ var (
+ logp = "SudoGet"
+
+ remoteSrc string
+ remoteBase string
+ remoteTmp string
+ cpRemoteToTmp string
+ chmod string
+ local string
+ )
+
if len(stmt.cmd) == 0 {
return fmt.Errorf("%s: missing source argument", logp)
}
@@ -226,18 +258,18 @@ func (ses *Session) SudoGet(stmt *Statement) (err error) {
// Copy file in the remote to temporary directory first, so user can
// read them.
- remoteSrc := stmt.cmd
- remoteBase := filepath.Base(remoteSrc)
- remoteTmp := filepath.Join(ses.tmpDir, remoteBase)
+ remoteSrc = stmt.cmd
+ remoteBase = filepath.Base(remoteSrc)
+ remoteTmp = filepath.Join(ses.tmpDir, remoteBase)
- cpRemoteToTmp := fmt.Sprintf("sudo cp -f %s %s", remoteSrc, remoteTmp)
+ cpRemoteToTmp = fmt.Sprintf("sudo cp -f %s %s", remoteSrc, remoteTmp)
err = ses.sshClient.Execute(cpRemoteToTmp)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
- chmod := fmt.Sprintf("sudo chown %s %s", ses.SSHUser, remoteTmp)
+ chmod = fmt.Sprintf("sudo chown %s %s", ses.SSHUser, remoteTmp)
err = ses.sshClient.Execute(chmod)
if err != nil {
@@ -245,7 +277,7 @@ func (ses *Session) SudoGet(stmt *Statement) (err error) {
}
// Get temporary file in the remote to local.
- local := stmt.args[0]
+ local = stmt.args[0]
if ses.sftpc == nil {
err = ses.sshClient.ScpGet(remoteTmp, local)
} else {
@@ -259,7 +291,16 @@ func (ses *Session) SudoGet(stmt *Statement) (err error) {
// SudoPut copy file from local to remote using sudo.
func (ses *Session) SudoPut(stmt *Statement) (err error) {
- logp := "SudoPut"
+ var (
+ logp = "SudoPut"
+
+ local string
+ baseName string
+ tmp string
+ remote string
+ moveStmt string
+ )
+
if len(stmt.cmd) == 0 {
return fmt.Errorf("%s: missing source argument", logp)
}
@@ -272,16 +313,16 @@ func (ses *Session) SudoPut(stmt *Statement) (err error) {
// Apply the session variables into local file to be copied first, and
// save them into cache directory.
- local, err := parseTemplate(ses, stmt.cmd)
+ local, err = parseTemplate(ses, stmt.cmd)
if err != nil {
return fmt.Errorf("%s: %w", logp, err)
}
- baseName := filepath.Base(stmt.cmd)
+ baseName = filepath.Base(stmt.cmd)
// Copy file from local to temporary directory first in remote.
- tmp := filepath.Join(ses.tmpDir, baseName)
- remote := string(stmt.args[0])
+ tmp = filepath.Join(ses.tmpDir, baseName)
+ remote = string(stmt.args[0])
if ses.sftpc == nil {
err = ses.sshClient.ScpPut(local, tmp)
@@ -294,7 +335,7 @@ func (ses *Session) SudoPut(stmt *Statement) (err error) {
// Finally, move the file from the temporary directory to original
// destination.
- moveStmt := fmt.Sprintf("sudo mv -f %s %s", tmp, remote)
+ moveStmt = fmt.Sprintf("sudo mv -f %s %s", tmp, remote)
return ses.sshClient.Execute(moveStmt)
}
@@ -302,7 +343,9 @@ func (ses *Session) SudoPut(stmt *Statement) (err error) {
// ExecLocal execute the command with its arguments in local environment where
// the output and error send to os.Stdout and os.Stderr respectively.
func (ses *Session) ExecLocal(req *Request, stmt *Statement) (err error) {
- cmd := exec.Command("/bin/sh", "-c", string(stmt.raw))
+ var (
+ cmd = exec.Command("/bin/sh", "-c", string(stmt.raw))
+ )
cmd.Stdout = req.stdout
cmd.Stderr = req.stderr
return cmd.Run()
@@ -311,8 +354,13 @@ func (ses *Session) ExecLocal(req *Request, stmt *Statement) (err error) {
// executeRequires run the "#require:" statements from line 0 until
// the start argument in the local system.
func (ses *Session) executeRequires(req *Request) (err error) {
- for x := 0; x < req.BeginAt; x++ {
- stmt := req.script.requires[x]
+ var (
+ x int
+ stmt *Statement
+ )
+
+ for x = 0; x < req.BeginAt; x++ {
+ stmt = req.script.requires[x]
if stmt == nil {
continue
}
diff --git a/statement.go b/statement.go
index d4987f0..87b3a5b 100644
--- a/statement.go
+++ b/statement.go
@@ -32,7 +32,12 @@ type Statement struct {
// ParseStatement create and initialize new Statement from raw line.
// It will return nil if raw line is empty.
func ParseStatement(raw []byte) (stmt *Statement, err error) {
- logp := "ParseStatement"
+ var (
+ logp = "ParseStatement"
+
+ cmd string
+ args []string
+ )
raw = bytes.TrimSpace(raw)
if len(raw) == 0 {
@@ -41,7 +46,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
if bytes.HasPrefix(raw, cmdMagicGet) {
raw = raw[len(cmdMagicGet):]
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
if len(cmd) == 0 || len(args) == 0 {
return nil, fmt.Errorf("%s: %s missing argument", logp, cmdMagicGet)
}
@@ -55,7 +60,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
}
if bytes.HasPrefix(raw, cmdMagicPut) {
raw = raw[len(cmdMagicPut):]
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
if len(cmd) == 0 || len(args) == 0 {
return nil, fmt.Errorf("%s: %s missing argument", logp, cmdMagicPut)
}
@@ -69,7 +74,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
}
if bytes.HasPrefix(raw, cmdMagicSudoGet) {
raw = raw[len(cmdMagicSudoGet):]
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
if len(cmd) == 0 || len(args) == 0 {
return nil, fmt.Errorf("%s: %s missing argument", logp, cmdMagicSudoGet)
}
@@ -83,7 +88,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
}
if bytes.HasPrefix(raw, cmdMagicSudoPut) {
raw = raw[len(cmdMagicSudoPut):]
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
if len(cmd) == 0 || len(args) == 0 {
return nil, fmt.Errorf("%s: %s missing argument", logp, cmdMagicSudoPut)
}
@@ -97,7 +102,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
}
if bytes.HasPrefix(raw, cmdMagicRequire) {
raw = raw[len(cmdMagicRequire):]
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
stmt = &Statement{
kind: statementKindRequire,
cmd: cmd,
@@ -114,7 +119,7 @@ func ParseStatement(raw []byte) (stmt *Statement, err error) {
return stmt, nil
}
- cmd, args := libexec.ParseCommandArgs(string(raw))
+ cmd, args = libexec.ParseCommandArgs(string(raw))
stmt = &Statement{
cmd: cmd,
args: args,
diff --git a/template.go b/template.go
index d70ab8c..04c327e 100644
--- a/template.go
+++ b/template.go
@@ -15,14 +15,21 @@ import (
// parseTemplate read the file input "in" and apply the session variables,
// and write the result to ".cache" directory.
func parseTemplate(ses *Session, in string) (out string, err error) {
- logp := "parseTemplate"
+ var (
+ logp = "parseTemplate"
+
+ tmpl *template.Template
+ f *os.File
+ outDir string
+ base string
+ )
if libio.IsBinary(in) {
return in, nil
}
- outDir := filepath.Join(ses.BaseDir, defCacheDir, filepath.Dir(in))
- base := filepath.Base(in)
+ outDir = filepath.Join(ses.BaseDir, defCacheDir, filepath.Dir(in))
+ base = filepath.Base(in)
out = filepath.Join(outDir, base)
err = os.MkdirAll(outDir, 0700)
@@ -30,12 +37,12 @@ func parseTemplate(ses *Session, in string) (out string, err error) {
return "", fmt.Errorf("%s %s: %w", logp, in, err)
}
- tmpl, err := template.ParseFiles(in)
+ tmpl, err = template.ParseFiles(in)
if err != nil {
return "", fmt.Errorf("%s %s: %w", logp, in, err)
}
- f, err := os.Create(out)
+ f, err = os.Create(out)
if err != nil {
return "", fmt.Errorf("%s %s: %w", logp, in, err)
}