Skip to content

Commit ee4834f

Browse files
committed
fix watch log
1 parent 92266c3 commit ee4834f

File tree

3 files changed

+155
-79
lines changed

3 files changed

+155
-79
lines changed

Diff for: cmd/formatter/shortcut.go

+132-62
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"fmt"
66
"os"
7-
"os/exec"
87
"syscall"
98
"time"
109

@@ -30,40 +29,47 @@ type KeyboardWatch struct {
3029
Ctx context.Context
3130
Cancel context.CancelFunc
3231
}
32+
type KEYBOARD_LOG_LEVEL int
33+
34+
const (
35+
NONE KEYBOARD_LOG_LEVEL = 0
36+
INFO KEYBOARD_LOG_LEVEL = 1
37+
DEBUG KEYBOARD_LOG_LEVEL = 2
38+
)
39+
3340
type LogKeyboard struct {
34-
SignalChannel chan<- os.Signal
3541
ErrorHandle KeyboardError
3642
Watch KeyboardWatch
3743
started bool
3844
IsDockerDesktopActive bool
3945
IsWatchConfigured bool
40-
shouldPrintInfo bool
41-
printerStop func()
42-
printerStart func()
46+
logLevel KEYBOARD_LOG_LEVEL
47+
SignalChannel chan<- os.Signal
48+
// services []string
49+
// printerStop func()
50+
// printerStart func()
4351
}
4452

4553
var KeyboardManager *LogKeyboard
4654
var eg multierror.Group
4755
var errorColor = "\x1b[1;33m"
4856

49-
func NewKeyboardManager(isDockerDesktopActive, isWatchConfigured, startWatch bool, watchFn func(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error, stop func(), start func(), sc chan<- os.Signal) {
57+
func NewKeyboardManager(isDockerDesktopActive, isWatchConfigured bool, sc chan<- os.Signal, watchFn func(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error) {
58+
// func NewKeyboardManager(isDockerDesktopActive, isWatchConfigured, startWatch bool, watchFn func(ctx context.Context, project *types.Project, services []string, options api.WatchOptions) error, stop func(), start func(), sc chan<- os.Signal) {
5059
km := LogKeyboard{}
5160
km.IsDockerDesktopActive = isDockerDesktopActive
5261
km.IsWatchConfigured = isWatchConfigured
53-
km.printerStart = start
54-
km.printerStop = stop
55-
km.shouldPrintInfo = true
62+
// km.printerStart = start
63+
// km.printerStop = stop
64+
km.logLevel = INFO
5665
// if up --watch and there is a watch config, we should start with watch running
57-
km.Watch.Watching = isWatchConfigured && startWatch
66+
km.Watch.Watching = false
5867
km.Watch.WatchFn = watchFn
5968
km.SignalChannel = sc
6069
KeyboardManager = &km
6170
}
6271

6372
func (lk *LogKeyboard) PrintKeyboardInfo(print func()) {
64-
if !lk.shouldPrintInfo {
65-
return
66-
}
6773
fmt.Print("\033[?25l") // hide cursor
6874
defer fmt.Printf("\033[?25h") // show cursor
6975

@@ -73,8 +79,14 @@ func (lk *LogKeyboard) PrintKeyboardInfo(print func()) {
7379
lk.started = true
7480
}
7581
print()
76-
lk.createBuffer()
77-
lk.printInfo()
82+
switch lk.logLevel {
83+
case INFO:
84+
lk.createBuffer(2)
85+
lk.printInfo()
86+
case DEBUG:
87+
lk.createBuffer(3)
88+
// lk.printDebugOptions()
89+
}
7890
}
7991

8092
func (lk *LogKeyboard) Error(prefix string, err error) {
@@ -83,10 +95,12 @@ func (lk *LogKeyboard) Error(prefix string, err error) {
8395
}
8496

8597
// This avoids incorrect printing at the end of the terminal
86-
func (lk *LogKeyboard) createBuffer() {
87-
fmt.Print("\012") // new line
88-
fmt.Print("\012")
89-
fmt.Print("\033[2A") // go back 3 lines
98+
func (lk *LogKeyboard) createBuffer(lines int) {
99+
for i := 0; i < lines; i++ {
100+
fmt.Print("\033[K") // clear
101+
fmt.Print("\012") // new line
102+
}
103+
fmt.Printf("\033[%dA", lines) // go back x lines
90104
}
91105

92106
func (lk *LogKeyboard) printError(height int) {
@@ -97,13 +111,15 @@ func (lk *LogKeyboard) printError(height int) {
97111
}
98112

99113
func (lk *LogKeyboard) printInfo() {
100-
height := goterm.Height()
101-
fmt.Print("\0337") // save cursor position
102-
lk.printError(height)
103-
fmt.Printf("\033[%d;0H", height) // Move to last line
104-
// clear line
105-
lk.infoMessage()
106-
fmt.Print("\0338") // restore cursor position
114+
if lk.logLevel == INFO {
115+
height := goterm.Height()
116+
fmt.Print("\0337") // save cursor position
117+
lk.printError(height)
118+
fmt.Printf("\033[%d;0H", height) // Move to last line
119+
// clear line
120+
lk.infoMessage()
121+
fmt.Print("\0338") // restore cursor position
122+
}
107123
}
108124

109125
func (lk *LogKeyboard) infoMessage() {
@@ -124,21 +140,23 @@ func (lk *LogKeyboard) infoMessage() {
124140
}
125141

126142
func (lk *LogKeyboard) clearInfo() {
127-
height := goterm.Height()
128-
fmt.Print("\0337") // save cursor position
129-
if lk.ErrorHandle.err != nil {
130-
fmt.Printf("\033[%d;0H", height-1)
131-
fmt.Print("\033[2K") // clear line
143+
if lk.logLevel == INFO {
144+
height := goterm.Height()
145+
fmt.Print("\0337") // save cursor position
146+
if lk.ErrorHandle.err != nil {
147+
fmt.Printf("\033[%d;0H", height-1)
148+
fmt.Print("\033[2K") // clear line
149+
}
150+
fmt.Printf("\033[%d;0H", height) // Move to last line
151+
fmt.Print("\033[2K") // clear line
152+
fmt.Print("\0338") // restore cursor position
153+
}
154+
if lk.logLevel == DEBUG {
155+
132156
}
133-
fmt.Printf("\033[%d;0H", height) // Move to last line
134-
fmt.Print("\033[2K") // clear line
135-
fmt.Print("\0338") // restore cursor position
136157
}
137158

138159
func (lk *LogKeyboard) PrintEnter() {
139-
if !lk.shouldPrintInfo {
140-
return
141-
}
142160
lk.clearInfo()
143161
lk.printInfo()
144162
}
@@ -176,6 +194,7 @@ func (lk *LogKeyboard) StartWatch(ctx context.Context, project *types.Project, o
176194
return
177195
}
178196
lk.switchWatching()
197+
fmt.Println("lk.isWatching()", lk.isWatching())
179198
if !lk.isWatching() && lk.Watch.Cancel != nil {
180199
lk.Watch.Cancel()
181200
} else {
@@ -193,48 +212,99 @@ func (lk *LogKeyboard) StartWatch(ctx context.Context, project *types.Project, o
193212
}
194213
}
195214

196-
func (lk *LogKeyboard) debug() {
197-
cmd := exec.Command("docker", "debug", "keep-not-latest-app-1")
198-
cmd.Stdout = os.Stdout
199-
cmd.Stdin = os.Stdin
200-
cmd.Stderr = os.Stderr
215+
// func (lk *LogKeyboard) printDebugOptions() {
216+
// if len(lk.services) == 0 {
217+
// lk.logLevel = INFO
218+
// return
219+
// }
220+
// height := goterm.Height()
221+
// //clear
222+
// fmt.Print("\0337") // save cursor position
223+
// fmt.Printf("\033[%d;0H\033[2K", height-2)
224+
// fmt.Printf("\033[%d;0H\033[2K", height-1)
225+
// fmt.Printf("\033[%d;0H\033[2K", height)
226+
// //clear
201227

202-
lk.printerStop()
203-
if err := cmd.Start(); err != nil {
204-
lk.printerStart()
205-
lk.Error("Debug", fmt.Errorf("Could not start debug process."))
206-
return
207-
}
208-
err := cmd.Wait()
209-
lk.printerStart()
210-
if err != nil {
211-
lk.Error("Debug", err)
212-
}
213-
}
228+
// fmt.Printf("\033[%d;0H", height-2) // Move to last line
229+
// fmt.Print("\033[2K[Debug] Select Service:")
230+
// fmt.Printf("\033[%d;0H", height-1) // Move to last line
231+
// serviceOpts := ""
232+
// for i := 0; i < len(lk.services); i++ {
233+
// serviceOpts = serviceOpts + fmt.Sprintf("(%d) %s ", i+1, lk.services[i])
234+
// }
235+
// fmt.Printf("\033[2K%s", serviceOpts)
236+
// fmt.Print("\0338") // restore cursor position
237+
// }
238+
239+
// func (lk *LogKeyboard) debug(project *types.Project) {
240+
// lk.services = project.ServiceNames()
241+
// // show list
242+
// lk.clearInfo()
243+
// lk.logLevel = DEBUG
244+
// // select
245+
// // clear line
246+
// choice := make(chan []byte)
247+
// eg.Go(func() error {
248+
// for {
249+
// data := make([]byte, 8)
250+
// n, err := os.Stdin.Read(data)
251+
252+
// // error handling : the basic thing to do is "on error, return"
253+
// if err != nil {
254+
// // if os.Stdin got closed, .Read() will return 'io.EOF'
255+
// if err == io.EOF {
256+
// log.Printf("stdin closed, exiting")
257+
// } else {
258+
// log.Printf("stdin: %s", err)
259+
// }
260+
// return err
261+
// }
262+
// // a habit to have : truncate your read buffers to 'n' after a .Read()
263+
// choice <- data[:n]
264+
// // return nil
265+
// }
266+
// })
267+
// out := <-choice
268+
// fmt.Println(out)
269+
//run
270+
// cmd := exec.Command("docker", "debug", "keep-not-latest-app-1")
271+
// cmd.Stdout = os.Stdout
272+
// cmd.Stdin = os.Stdin
273+
// cmd.Stderr = os.Stderr
274+
275+
// lk.printerStop()
276+
// if err := cmd.Start(); err != nil {
277+
// lk.printerStart()
278+
// lk.Error("Debug", fmt.Errorf("Could not start debug process."))
279+
// return
280+
// }
281+
// err := cmd.Wait()
282+
// lk.printerStart()
283+
// lk.logLevel = INFO
284+
// if err != nil {
285+
// lk.Error("Debug", err)
286+
// }
287+
// }
214288

215289
func (lk *LogKeyboard) HandleKeyEvents(event keyboard.KeyEvent, ctx context.Context, project *types.Project, options api.UpOptions) {
216290
switch kRune := event.Rune; kRune {
217291
case 'V':
218292
lk.openDockerDesktop(project)
219293
case 'W':
220294
lk.StartWatch(ctx, project, options)
221-
case 'D':
222-
lk.debug()
295+
// case 'D':
296+
// lk.debug(project)
223297
}
224298
switch key := event.Key; key {
225299
case keyboard.KeyCtrlC:
226300
keyboard.Close()
227301
lk.clearInfo()
228-
lk.shouldPrintInfo = false
302+
lk.logLevel = NONE
229303
if lk.Watch.Watching && lk.Watch.Cancel != nil {
230-
// fmt.Println("canceling")
231304
lk.Watch.Cancel()
232-
// fmt.Println("canceling watch?")
233-
err := eg.Wait().ErrorOrNil() // Need to print this ?
234-
fmt.Println("done@", err)
305+
_ = eg.Wait().ErrorOrNil() // Need to print this ?
235306
}
236307
// will notify main thread to kill and will handle gracefully
237-
fmt.Println("tear down")
238308
lk.SignalChannel <- syscall.SIGINT
239309
case keyboard.KeyEnter:
240310
lk.PrintEnter()

Diff for: pkg/compose/up.go

+17-15
Original file line numberDiff line numberDiff line change
@@ -95,21 +95,23 @@ func (s *composeService) Up(ctx context.Context, project *types.Project, options
9595
if err != nil {
9696
panic(err)
9797
}
98-
formatter.NewKeyboardManager(true, s.shouldWatch(project), options.Start.Watch, s.Watch, printer.Cancel, func() {
99-
eg.Go(func() error {
100-
_, err := printer.Run(options.Start.CascadeStop, options.Start.ExitCodeFrom, func() error {
101-
fmt.Fprintln(s.stdinfo(), "Aborting on container exit...")
102-
return progress.Run(ctx, func(ctx context.Context) error {
103-
return s.Stop(ctx, project.Name, api.StopOptions{
104-
Services: options.Create.Services,
105-
Project: project,
106-
})
107-
}, s.stdinfo())
108-
})
109-
return err
110-
})
111-
}, signalChan) // change after test
112-
if formatter.KeyboardManager.Watch.Watching {
98+
formatter.NewKeyboardManager(true, options.Start.Watch, signalChan, s.Watch)
99+
100+
// formatter.NewKeyboardManager(true, s.shouldWatch(project), options.Start.Watch, s.Watch, printer.Cancel, func() {
101+
// eg.Go(func() error {
102+
// _, err := printer.Run(options.Start.CascadeStop, options.Start.ExitCodeFrom, func() error {
103+
// fmt.Fprintln(s.stdinfo(), "Aborting on container exit...")
104+
// return progress.Run(ctx, func(ctx context.Context) error {
105+
// return s.Stop(ctx, project.Name, api.StopOptions{
106+
// Services: options.Create.Services,
107+
// Project: project,
108+
// })
109+
// }, s.stdinfo())
110+
// })
111+
// return err
112+
// })
113+
// }, signalChan) // change after test
114+
if options.Start.Watch {
113115
formatter.KeyboardManager.StartWatch(ctx, project, options)
114116
}
115117
// formatter.NewKeyboardManager(s.isDesktopIntegrationActive(), s.shouldWatch(project), options.Start.Watch, s.Watch)

Diff for: pkg/compose/watch.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ func (s *composeService) Watch(ctx context.Context, project *types.Project, serv
178178
// options.LogTo.Err(api.WatchLogger, "FAILED")
179179
return fmt.Errorf("none of the selected services is configured for watch, consider setting an 'develop' section")
180180
}
181-
options.LogTo.Log(api.WatchLogger, "watch enabled")
181+
options.LogTo.Log(api.WatchLogger, "Watch started")
182182

183183
return eg.Wait()
184184
}
@@ -198,10 +198,12 @@ func (s *composeService) watch(ctx context.Context, project *types.Project, name
198198

199199
events := make(chan fileEvent)
200200
batchEvents := batchDebounceEvents(ctx, s.clock, quietPeriod, events)
201+
quit := make(chan bool)
201202
go func() {
202203
for {
203204
select {
204205
case <-ctx.Done():
206+
quit <- true
205207
return
206208
case batch := <-batchEvents:
207209
start := time.Now()
@@ -217,9 +219,11 @@ func (s *composeService) watch(ctx context.Context, project *types.Project, name
217219

218220
for {
219221
select {
220-
case <-ctx.Done():
222+
case <-quit:
223+
options.LogTo.Log(api.WatchLogger, "Watch stoped")
221224
return nil
222225
case err := <-watcher.Errors():
226+
options.LogTo.Err(api.WatchLogger, "Watch stoped with errors")
223227
return err
224228
case event := <-watcher.Events():
225229
hostPath := event.Path()

0 commit comments

Comments
 (0)