Skip to content

Commit

Permalink
Improved CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
AlinaNova21 committed Nov 27, 2019
1 parent ad83f1f commit 5ad985d
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 75 deletions.
96 changes: 24 additions & 72 deletions cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,71 +1,32 @@
package cli

import (
"bufio"
"context"
"fmt"
"io"
"log"
"net"
"strings"
"time"
)

func copyWorker(dst io.Writer, src io.Reader, doneCh chan<- bool) {
io.Copy(dst, src)
doneCh <- true
}
"github.com/go-resty/resty/v2"
)

type ScreepsCLI struct {
conn net.Conn
buffer []string
host string
port int16
readCh chan string
stopReadCh chan bool
client *resty.Client
WelcomeText string
}

func NewScreepsCLI(host string, port int16) *ScreepsCLI {
return &ScreepsCLI{
host: host,
port: port,
client := resty.New()
client.SetHostURL(fmt.Sprintf("http://%s:%d", host, port))
s := &ScreepsCLI{
client: client,
}
resp, err := client.R().Get("/greeting")
if err == nil {
s.WelcomeText = resp.String()
}
return s
}

func (s *ScreepsCLI) Start() error {
conn, err := net.Dial("tcp4", fmt.Sprintf("%s:%d", s.host, s.port))
if err != nil {
log.Println("dial:", err)
return err
}
s.conn = conn
s.readCh = make(chan string)
s.stopReadCh = make(chan bool)

go func(outCh chan<- string) {
reader := bufio.NewReader(s.conn)
for {
line, err := reader.ReadString('\n')
if err != nil {
break
}
if len(line) > 0 {
line = strings.TrimPrefix(line, "< ")
outCh <- line
}
}
}(s.readCh)
buffer := ""
loop:
for {
select {
case line := <-s.readCh:
buffer = buffer + line
case <-time.After(200 * time.Millisecond):
break loop
}
}
s.WelcomeText = buffer
return nil
}

Expand All @@ -74,26 +35,17 @@ func (s *ScreepsCLI) Stop() {
}

func (s *ScreepsCLI) Command(cmd string) string {
if len(cmd) > 0 {
s.conn.Write([]byte(fmt.Sprintf("%s\n", cmd)))
if len(cmd) == 0 {
return ""
}
buffer := make([]string, 0)
log.Println("first sel")
select {
case line := <-s.readCh:
buffer = append(buffer, line)
case <-time.After(5 * time.Second):
buffer = append(buffer, "Timeout Waiting for response")
return strings.Join(buffer, "")
}
loop:
for {
select {
case line := <-s.readCh:
buffer = append(buffer, line)
case <-time.After(200 * time.Millisecond):
break loop
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
resp, err := s.client.R().
SetContext(ctx).
SetBody(cmd).
Post("/cli")
if err != nil {
return err.Error()
}
return strings.Join(buffer, "")
return resp.String()
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/c-bata/go-prompt v0.2.3
github.com/cavaliercoder/grab v2.0.0+incompatible
github.com/go-redis/redis/v7 v7.0.0-beta.4
github.com/go-resty/resty/v2 v2.1.0
github.com/go-stack/stack v1.8.0 // indirect
github.com/golang/snappy v0.0.1 // indirect
github.com/google/go-github v17.0.0+incompatible // indirect
Expand All @@ -24,6 +25,5 @@ require (
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c // indirect
github.com/xdg/stringprep v1.0.0 // indirect
go.mongodb.org/mongo-driver v1.1.3
golang.org/x/net v0.0.0-20190514140710-3ec191127204 // indirect
gopkg.in/yaml.v2 v2.2.2
)
5 changes: 5 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo
github.com/go-redis/redis v6.15.6+incompatible h1:H9evprGPLI8+ci7fxQx6WNZHJSb7be8FqJQRhdQZ5Sg=
github.com/go-redis/redis/v7 v7.0.0-beta.4 h1:p6z7Pde69EGRWvlC++y8aFcaWegyrKHzOBGo0zUACTQ=
github.com/go-redis/redis/v7 v7.0.0-beta.4/go.mod h1:xhhSbUMTsleRPur+Vgx9sUHtyN33bdjxY+9/0n9Ig8s=
github.com/go-resty/resty v1.12.0 h1:L1P5qymrXL5H/doXe2pKUr1wxovAI5ilm2LdVLbwThc=
github.com/go-resty/resty/v2 v2.1.0 h1:Z6IefCpUMfnvItVJaJXWv/pMiiD11So35QgwEELsldE=
github.com/go-resty/resty/v2 v2.1.0/go.mod h1:dZGr0i9PLlaaTD4H/hoZIDjQ+r6xq8mgbRzHZf7f2J8=
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
Expand Down Expand Up @@ -64,6 +67,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190514140710-3ec191127204 h1:4yG6GqBtw9C+UrLp6s2wtSniayy/Vd/3F7ffLE427XI=
golang.org/x/net v0.0.0-20190514140710-3ec191127204/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 h1:rTIdg5QFRR7XCaK4LCjBiPbx8j4DQRpdYMnGn/bJUEU=
golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
Expand Down
6 changes: 4 additions & 2 deletions launcher/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,16 @@ func runCli(config *Config) error {
if err := c.Start(); err != nil {
log.Fatalf("Error! %v", err)
}
fmt.Print(c.WelcomeText)
fmt.Println(c.WelcomeText)
p := prompt.New(
func(cmd string) {
if cmd == "exit" || cmd == "quit" {
os.Exit(0)
}
ret := c.Command(cmd)
fmt.Print(ret)
if len(ret) > 0 {
fmt.Println(ret)
}
},
completer,
prompt.OptionTitle("Screeps CLI"),
Expand Down
48 changes: 48 additions & 0 deletions launcher/climod.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package launcher

const cliMod = `
const http = require('http')
const express = require('express')
const bodyParser = require('body-parser')
const vm = require('vm')
const util = require('util')
module.exports = config => {
if (config.cli) {
const app = express()
const server = http.createServer(app)
config.cli.connectionListener = socket => {
server.emit('connection', socket)
}
app.get('/greeting', (req, res) => {
let build = ' '
try {
build = 'v'+require('screeps').version
}catch(err){}
let text = config.cli.greeting.replace('{build}', build)
res.write(text)
res.end()
})
app.post('/cli', bodyParser.text(), async (req, res) => {
const cb = (data, isResult) => {
res.write(data + "\n")
if (isResult) {
res.end()
}
}
const command = req.body
const ctx = vm.createContext(config.cli.createSandbox(cb))
try {
const result = await vm.runInContext(command, ctx)
if (typeof result != 'string') {
cb(''+util.inspect(result), true)
} else {
cb(''+result, true)
}
} catch(err) {
cb('Error: '+(err.stack || err), true)
}
})
}
}
`
1 change: 1 addition & 0 deletions launcher/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type ConfigEnv struct {
Storage map[string]string `yaml:"storage" json:"storage"`
}

// ConfigBackup Backup section of config
type ConfigBackup struct {
Dirs []string `yaml:"dirs" json:"dirs"`
Files []string `yaml:"files" json:"files"`
Expand Down
2 changes: 2 additions & 0 deletions launcher/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package launcher

import (
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
Expand Down Expand Up @@ -102,6 +103,7 @@ func (l *Launcher) Apply() error {
copy.Copy(filepath.Join("node_modules", "@screeps", "launcher", "init_dist"), ".")
os.RemoveAll(filepath.Join("node_modules", ".hooks"))
}
ioutil.WriteFile(filepath.Join(l.config.LocalMods, "screeps-launcher-cli.js"), []byte(cliMod), 0644)
log.Print("Writing mods.json")
err = writeMods(l.config)
if err != nil {
Expand Down

0 comments on commit 5ad985d

Please sign in to comment.