-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
275 lines (220 loc) · 6.43 KB
/
main.go
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strconv"
"sync"
"time"
)
const (
NOT_STARTED = "not_started"
IN_PROGRESS = "in_progress"
DONE = "done"
ESCAPTE_COLOR_START = "\033["
ESCAPE_COLOR_END = "\033[0m"
RED_BOLD = ESCAPTE_COLOR_START + "1;31m"
YELLOW_BOLD = ESCAPTE_COLOR_START + "1;33m"
GREEN_BOLD = ESCAPTE_COLOR_START + "1;32m"
VIOLET_BOLD = ESCAPTE_COLOR_START + "1;34m"
WHITE = ESCAPTE_COLOR_START + "0m"
)
type Task struct {
ID int `json:"id"`
Description string `json:"description"`
Duration int64 `json:"duration"`
Status string `json:"status"`
}
func (task Task) IsInProgress() bool {
return task.Status == IN_PROGRESS
}
func (task Task) IsNotStarted() bool {
return task.Status == NOT_STARTED
}
func (task Task) IsDone() bool {
return task.Status == DONE
}
func (task Task) IsNotYetDone() bool {
return task.Status != DONE
}
func (task *Task) UpdateStatusTo(newStatus string) {
task.Status = newStatus
}
func GetMatchingColor(status string) string {
switch status {
case NOT_STARTED:
return RED_BOLD
case IN_PROGRESS:
return YELLOW_BOLD
case DONE:
return GREEN_BOLD
default:
return WHITE
}
}
func PrintHeader() {
PrintLine("ID", "Description", "Duration", "Status")
fmt.Print("\n")
}
func PrintLine(ID, Description, Duration, Status string) {
fmt.Printf("%s \t\t %-24s \t\t %-8s \t\t %-12s \n", ID, Description, Duration, Status)
}
func ColorStatus(status string) string {
return fmt.Sprintf("%s %s %s", GetMatchingColor(status), status, ESCAPE_COLOR_END)
}
func PrintTasks(tasks []Task) {
PrintHeader()
for _, task := range tasks {
PrintLine(strconv.Itoa(task.ID), task.Description, strconv.FormatInt(task.Duration, 10), ColorStatus(task.Status))
time.Sleep(time.Nanosecond)
}
}
func GetTaskNotYetDone(tasks []Task) []Task {
tasksNotYetDone := []Task{}
for _, task := range tasks {
if task.IsNotYetDone() {
tasksNotYetDone = append(tasksNotYetDone, task)
}
}
return tasksNotYetDone
}
func NotifyTaskIsBeingProcessed(task Task, workerID int) string {
return fmt.Sprintf("Task (%s%d%s) is being processed by worker %d", YELLOW_BOLD, task.ID, ESCAPE_COLOR_END, workerID)
}
func NotifyTaskIsDone(task Task, workerID int) string {
return fmt.Sprintf("Task (%s%d%s) has been done in %d(s) by worker %d", GREEN_BOLD, task.ID, ESCAPE_COLOR_END, task.Duration, workerID)
}
func updateTaskStatusInList(task Task, taskList *[]Task, index int, notifications chan string, workerID int) {
if task.IsNotStarted() {
task.UpdateStatusTo(IN_PROGRESS)
notifications <- NotifyTaskIsBeingProcessed(task, workerID)
task.UpdateStatusTo(DONE)
notifications <- NotifyTaskIsDone(task, workerID)
}
if task.IsInProgress() {
time.Sleep(time.Duration(task.Duration) * time.Second)
task.UpdateStatusTo(DONE)
notifications <- NotifyTaskIsDone(task, workerID)
}
(*taskList)[index] = task
}
func processTask(taskID int, taskList *[]Task, notifications chan string, workerID int) {
for index, task := range *taskList {
if task.ID == taskID {
updateTaskStatusInList(task, taskList, index, notifications, workerID)
}
}
}
func filterTaskBasedOnStatus(tasks []Task, status string) []Task {
tasksFiltered := []Task{}
for _, task := range tasks {
if task.Status == status {
tasksFiltered = append(tasksFiltered, task)
}
}
return tasksFiltered
}
func parseArgumentsFromFlags() (*string, *bool, *bool, *int, *int, *int) {
arguments := map[string]string{
"file": "the file of the path",
"list": "print the list of all tasks",
"num": "use with -list to print a specific number of task",
"status": "use to print task with specifi status. values are 1(not started) , 2(in progress), 3(done). Ex: -status=1",
"process": "use to process task that are not yet done",
"workers": "use to process task that are not yet done. 5 by default",
}
filePath := flag.String("file", "./task.json", arguments["file"])
shouldList := flag.Bool("list", false, arguments["list"])
shouldProcessTasks := flag.Bool("process", false, arguments["process"])
numberOfLineToPrint := flag.Int("num", 0, arguments["num"])
status := flag.Int("status", 0, arguments["status"])
workers := flag.Int("workers", 5, arguments["workers"])
flag.Parse()
return filePath, shouldList, shouldProcessTasks, numberOfLineToPrint, status, workers
}
func getTasksFromFile(filePath *string) []Task {
var allTasks []Task
if *filePath == "" {
log.Fatalf("Please provide the file path")
}
file, err := os.Open(*filePath)
if err != nil {
log.Fatalf("Error while opening %s : %v", *filePath, err)
}
defer file.Close()
err = json.NewDecoder(file).Decode(&allTasks)
if err != nil {
log.Fatalf("Error while decoding %s : %v", *filePath, err)
}
return allTasks
}
func startProcessingTasks(allTasks *[]Task, workers *int) {
wg := sync.WaitGroup{}
notifications := make(chan string)
tasksNotYeDone := GetTaskNotYetDone(*allTasks)
if len(tasksNotYeDone) == 0 {
log.Fatal("No tasks to process")
}
taskDispatcher := make(chan int, len(tasksNotYeDone))
for _, task := range tasksNotYeDone {
taskDispatcher <- task.ID
}
close(taskDispatcher)
for i := 1; i <= *workers; i++ {
wg.Add(1)
go func(workerID int) {
defer wg.Done()
//ProcessTaskUntilNoneRemain
for taskID := range taskDispatcher {
processTask(taskID, allTasks, notifications, workerID)
}
}(i)
}
go func() {
wg.Wait()
close(notifications)
}()
for message := range notifications {
fmt.Println(message)
}
os.Exit(0)
}
func filterTasks(allTasks []Task, status *int) {
var finalStatus string
switch *status {
case 1:
finalStatus = NOT_STARTED
case 2:
finalStatus = IN_PROGRESS
case 3:
finalStatus = DONE
default:
log.Fatal("status must be 1, 2, or 3 : 1=>not_started, 2=>in_progress, 3=>done")
}
tasks := filterTaskBasedOnStatus(allTasks, finalStatus)
PrintTasks(tasks)
os.Exit(0)
}
func listTasks(allTasks []Task, numberOfLineToPrint *int) {
if *numberOfLineToPrint > 0 {
PrintTasks(allTasks[:*numberOfLineToPrint])
os.Exit(0)
}
PrintTasks(allTasks)
os.Exit(0)
}
func main() {
filePath, shouldList, shouldProcessTasks, numberOfLineToPrint, status, workers := parseArgumentsFromFlags()
allTasks := getTasksFromFile(filePath)
if *shouldList {
listTasks(allTasks, numberOfLineToPrint)
}
if *status != 0 {
filterTasks(allTasks, status)
}
if *shouldProcessTasks {
startProcessingTasks(&allTasks, workers)
}
}