summaryrefslogtreecommitdiffstats
path: root/decor/on_abort.go
blob: 50a1dfbb5d70dc40c33784e629af653c3f8b60ef (plain)
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
package decor

var (
	_ Decorator = onAbortWrapper{}
	_ Wrapper   = onAbortWrapper{}
	_ Decorator = onAbortMetaWrapper{}
	_ Wrapper   = onAbortMetaWrapper{}
)

// OnAbort wrap decorator.
// Displays provided message on abort event.
// Has no effect if bar.Abort(true) is called.
//
//	`decorator` Decorator to wrap
//	`message` message to display
func OnAbort(decorator Decorator, message string) Decorator {
	if decorator == nil {
		return nil
	}
	return onAbortWrapper{decorator, message}
}

type onAbortWrapper struct {
	Decorator
	msg string
}

func (d onAbortWrapper) Decor(s Statistics) (string, int) {
	if s.Aborted {
		return d.Format(d.msg)
	}
	return d.Decorator.Decor(s)
}

func (d onAbortWrapper) Unwrap() Decorator {
	return d.Decorator
}

// OnAbortMeta wrap decorator.
// Provided fn is supposed to wrap output of given decorator
// with meta information like ANSI escape codes for example.
// Primary usage intention is to set SGR display attributes.
//
//	`decorator` Decorator to wrap
//	`fn` func to apply meta information
func OnAbortMeta(decorator Decorator, fn func(string) string) Decorator {
	if decorator == nil {
		return nil
	}
	return onAbortMetaWrapper{decorator, fn}
}

type onAbortMetaWrapper struct {
	Decorator
	fn func(string) string
}

func (d onAbortMetaWrapper) Decor(s Statistics) (string, int) {
	if s.Completed {
		str, width := d.Decorator.Decor(s)
		return d.fn(str), width
	}
	return d.Decorator.Decor(s)
}

func (d onAbortMetaWrapper) Unwrap() Decorator {
	return d.Decorator
}