forked from mborho/rem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathline.go
More file actions
93 lines (82 loc) · 2.15 KB
/
Copy pathline.go
File metadata and controls
93 lines (82 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// rem - A tool to remember things on the command line.
// Copyright (C) 2015 Martin Borho (martin@borho.net)
//
// 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 main
import (
"fmt"
"github.com/shirou/gopsutil/v3/process"
"golang.org/x/sys/unix"
"io"
"os"
"regexp"
)
type Line struct {
line string
cmd string
tag string
execFlag string
}
// Read incoming string into Line struct.
func (l *Line) read(line string) {
re := regexp.MustCompile("^#([^ ]+)?#")
l.line = line
if tagMatch := re.FindSubmatch([]byte(line)); tagMatch != nil {
l.tag = string(tagMatch[1])
l.cmd = line[len(l.tag)+2:]
} else {
// no tag found, simple command
l.cmd = line
}
}
func (l *Line) execute(printCmd bool) error {
// get the pid of the calling shell
p, err := process.NewProcess(int32(os.Getppid()))
if err != nil {
return err
}
// path of calling shell
callerPath, err := p.Exe()
if err != nil {
return err
}
// define 'execute' flag if not set
if l.execFlag == "" {
l.execFlag = "-c"
}
// print cmd before executing
if printCmd == true {
fmt.Println(l.cmd)
}
// /bin/bash -c "ls -la"
execParts := []string{callerPath, l.execFlag, l.cmd}
// replace the current process
err = unix.Exec(callerPath, execParts, os.Environ())
if err != nil {
return err
}
return nil
}
// Prints line to tabwriter.
func (l *Line) print(w io.Writer, index int, withTag bool) {
if withTag {
tag := ""
if tag = l.tag; tag == "" {
tag = " - "
}
fmt.Fprintf(w, " %d\t%s\t%s\n", index, tag, l.cmd)
} else {
fmt.Fprintf(w, " %d\t%s\n", index, l.cmd)
}
}