Skip to content

Commit

Permalink
feat: support to print the output in-time
Browse files Browse the repository at this point in the history
  • Loading branch information
LinuxSuRen committed Feb 16, 2023
1 parent 7e7dd8d commit 46fbfe6
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 83 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ name=linuxsuren
echo hello $name
```

### Run in long time
```shell
#!title: Run long time
for i in 1 2 3 4 5
do
echo $i
sleep 1
done
```

### Run Python Script
```python3
#!title: Python Hello World
Expand Down
16 changes: 1 addition & 15 deletions cli/golang_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cli
import (
"fmt"
"os"
"os/exec"
"strings"
)

Expand Down Expand Up @@ -39,20 +38,7 @@ func (s *GolangScript) Run() (err error) {
}()
}

var goExec string
if goExec, err = exec.LookPath("go"); err != nil {
return
}

cmd := exec.Command(goExec, "run", goSourceFile)
cmd.Env = os.Environ()

var output []byte
if output, err = cmd.CombinedOutput(); err != nil {
fmt.Println(string(output), err)
return
}
fmt.Print(string(output))
err = s.Execer.RunCommandInDir("go", s.Dir, "run", goSourceFile)
return
}

Expand Down
16 changes: 1 addition & 15 deletions cli/python_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package cli
import (
"fmt"
"os"
"os/exec"
)

// PythonScript represents the Python script
Expand All @@ -24,20 +23,7 @@ func (s *PythonScript) Run() (err error) {
}()
}

var pyExec string
if pyExec, err = exec.LookPath("python3"); err != nil {
return
}

cmd := exec.Command(pyExec, shellFile)
cmd.Env = os.Environ()

var output []byte
if output, err = cmd.CombinedOutput(); err != nil {
fmt.Println(string(output), err)
return
}
fmt.Print(string(output))
err = s.Execer.RunCommandInDir("python3", s.Dir, shellFile)
return
}

Expand Down
22 changes: 16 additions & 6 deletions cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,33 @@ package cli

import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"

"github.com/AlecAivazis/survey/v2"
"github.com/golang-commonmark/markdown"
"github.com/linuxsuren/http-downloader/pkg/exec"
"github.com/spf13/cobra"
)

// should be inject during the build process
var version string

// NewRootCommand returns the instance of cobra.Command
func NewRootCommand() (cmd *cobra.Command) {
opt := &option{}
func NewRootCommand(execer exec.Execer, out io.Writer) (cmd *cobra.Command) {
opt := &option{
execer: execer,
}
cmd = &cobra.Command{
Use: "mde",
Example: "mde README.md",
Args: cobra.MinimumNArgs(1),
RunE: opt.runE,
}
cmd.SetOut(out)
cmd.Version = version
flags := cmd.Flags()
flags.BoolVarP(&opt.loop, "loop", "", true, "Run the Markdown in loop mode.")
Expand Down Expand Up @@ -52,11 +57,13 @@ func (o *option) runE(cmd *cobra.Command, args []string) (err error) {
}
}

for {
err = o.executeScripts(scriptRunners)
if scriptRunners.Size() > 1 {
for {
err = o.executeScripts(scriptRunners)

if !o.loop {
break
if !o.loop {
break
}
}
}
return
Expand Down Expand Up @@ -109,6 +116,7 @@ func (o *option) parseMarkdownRunner(mdFilePath string) (scriptList ScriptRunner
Content: originalContent,
Dir: path.Dir(mdFilePath),
KeepScripts: o.keepScripts,
Execer: o.execer,
}

switch lang {
Expand All @@ -133,6 +141,8 @@ type option struct {
loop bool
keepFilter bool
keepScripts bool

execer exec.Execer
}

func (o *option) executeScripts(scriptRunners ScriptRunners) (err error) {
Expand Down
4 changes: 3 additions & 1 deletion cli/root_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package cli

import (
"bytes"
"testing"

"github.com/linuxsuren/http-downloader/pkg/exec"
"github.com/stretchr/testify/assert"
)

Expand All @@ -18,7 +20,7 @@ func TestNewRootCommand(t *testing.T) {
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := NewRootCommand()
cmd := NewRootCommand(exec.FakeExecer{}, &bytes.Buffer{})
assert.True(t, cmd.HasExample())

cmd.SetArgs(tt.args)
Expand Down
51 changes: 19 additions & 32 deletions cli/shell_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path"
"regexp"
"strings"

Expand All @@ -29,7 +27,7 @@ func (s *ShellScript) Run() (err error) {
lines := strings.Split(s.Content, "\n")[1:]

preDefinedEnv := os.Environ()
for _, cmdLine := range lines {
for i, cmdLine := range lines {
var pair []string
var ok bool
ok, pair, err = isInputRequest(cmdLine)
Expand All @@ -43,10 +41,8 @@ func (s *ShellScript) Run() (err error) {
}
os.Setenv(pair[0], pair[1])
continue
}

err = runCmdLine(cmdLine, s.Dir, s.KeepScripts)
if err != nil {
} else {
err = s.runCmdLine(strings.Join(lines[i:], "\n"), s.Dir, s.KeepScripts)
break
}
}
Expand All @@ -59,6 +55,22 @@ func (s *ShellScript) Run() (err error) {
return
}

func (s *ShellScript) runCmdLine(cmdLine, contextDir string, keepScripts bool) (err error) {
var shellFile string
if shellFile, err = writeAsShell(cmdLine, contextDir); err != nil {
fmt.Println(err)
return
}
if !keepScripts {
defer func() {
_ = os.RemoveAll(shellFile)
}()
}

err = s.Execer.RunCommandInDir("bash", contextDir, shellFile)
return
}

// GetTitle returns the title of this script
func (s *ShellScript) GetTitle() string {
return s.Title
Expand Down Expand Up @@ -91,31 +103,6 @@ func inputRequest(pair []string) (result []string, err error) {
return
}

func runCmdLine(cmdLine, contextDir string, keepScripts bool) (err error) {
var shellFile string
if shellFile, err = writeAsShell(cmdLine, contextDir); err != nil {
fmt.Println(err)
return
}
if !keepScripts {
defer func() {
_ = os.RemoveAll(shellFile)
}()
}

cmd := exec.Command("bash", path.Base(shellFile))
cmd.Dir = contextDir
cmd.Env = os.Environ()

var output []byte
if output, err = cmd.CombinedOutput(); err != nil {
fmt.Println(string(output), err)
return
}
fmt.Print(string(output))
return
}

func writeAsShell(content, dir string) (targetPath string, err error) {
var f *os.File
if f, err = os.CreateTemp(dir, "sh"); err == nil {
Expand Down
18 changes: 18 additions & 0 deletions cli/types.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
package cli

import "github.com/linuxsuren/http-downloader/pkg/exec"

// Script represents a script object
type Script struct {
Kind string
Title string
Content string
Dir string
KeepScripts bool
Execer exec.Execer
}

// ScriptRunner is the interface of a common runner
type ScriptRunner interface {
Run() error
GetTitle() string
}

// NewScriptRunners returns the instance of ScriptRunners
func NewScriptRunners() ScriptRunners {
return []ScriptRunner{&QuitRunner{}}
}

// ScriptRunners is an alias of the ScriptRunner slice
type ScriptRunners []ScriptRunner

// GetTitles returns all the titles
func (s ScriptRunners) GetTitles() (titles []string) {
titles = make([]string, len(s))
for i, r := range s {
titles[i] = r.GetTitle()
}
return
}

// GetRunner returns the runner by title
func (s ScriptRunners) GetRunner(title string) ScriptRunner {
for _, runner := range s {
if runner.GetTitle() == title {
Expand All @@ -36,11 +45,20 @@ func (s ScriptRunners) GetRunner(title string) ScriptRunner {
return nil
}

// Size returns the size of the script runners
func (s ScriptRunners) Size() int {
return len(s)
}

// QuitRunner represents a runner for quit
type QuitRunner struct{}

// Run does nothing
func (r *QuitRunner) Run() error {
return nil
}

// GetTitle returns the title
func (r *QuitRunner) GetTitle() string {
return "Quit"
}
15 changes: 9 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,25 @@ go 1.18

require (
github.com/golang-commonmark/markdown v0.0.0-20180910011815-a8f139058164
github.com/linuxsuren/http-downloader v0.0.82
github.com/spf13/cobra v1.6.1
github.com/stretchr/testify v1.6.1
github.com/stretchr/testify v1.8.1
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mattn/go-isatty v0.0.8 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/mattn/go-colorable v0.1.6 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150 // indirect
golang.org/x/term v0.0.0-20210503060354-a79de5458b56 // indirect
golang.org/x/text v0.3.3 // indirect
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
golang.org/x/text v0.3.8 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

Expand Down
Loading

0 comments on commit 46fbfe6

Please sign in to comment.