-
Notifications
You must be signed in to change notification settings - Fork 4
/
coverage.html
516 lines (431 loc) · 20 KB
/
coverage.html
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">tmp/helpers.go (7.1%)</option>
<option value="file1">tmp/urlChecker.go (0.0%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">package main
import (
//"flag"
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"mvdan.cc/xurls/v2"
)
type Post struct {
ID string
URL string
}
// extract all urls from the string and return them as a slice (array)
func extractURL(str string) []string <span class="cov8" title="1">{
rxStrict := xurls.Strict()
foundUrls := rxStrict.FindAllString(str, -1)
return foundUrls
}</span>
func parseFromTelescope() []string <span class="cov0" title="0">{
var allPostBody []byte
resp, err := http.Get("http://localhost:3000/posts")
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">var posts []Post
if err := json.Unmarshal(body, &posts); err != nil </span><span class="cov0" title="0">{
panic(err)</span>
}
<span class="cov0" title="0">for _, post := range posts </span><span class="cov0" title="0">{
resp, err := http.Get("http://localhost:3000" + post.URL)
if err != nil </span><span class="cov0" title="0">{
log.Fatal(err)
}</span>
<span class="cov0" title="0">defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
log.Fatal(err)
}</span>
<span class="cov0" title="0">allPostBody = append(allPostBody, body...)</span>
}
<span class="cov0" title="0">return extractURL(string(allPostBody))</span>
}
//Function to parse ignore URLs from provided ignore file path
func parseIgnoreURL(ignoreFilePath string) []string <span class="cov0" title="0">{
var ignoreURLs []string
//Read the content of file given by ignoreFilePath
content, err := ioutil.ReadFile(ignoreFilePath)
if err != nil </span><span class="cov0" title="0">{
log.Fatal(err)
}</span>
//Create a scanner for file content
<span class="cov0" title="0">scanner := bufio.NewScanner(strings.NewReader(string(content)))
re := regexp.MustCompile("^(#|https?://)")
//Scan the ignore URL file line by line
for scanner.Scan() </span><span class="cov0" title="0">{
line := scanner.Text()
//Check if the ignore link file is invalid
if !re.Match([]byte(line)) </span><span class="cov0" title="0">{
fmt.Println("Ignore Link File is invalid")
fmt.Println("Exit with status 1")
os.Exit(1)
}</span>
<span class="cov0" title="0">firstChar := string(line[0])
//Only look at lines that don't start with #
if firstChar != "#" </span><span class="cov0" title="0">{
URLsFoundFromLine := extractURL(line)
ignoreURLs = append(ignoreURLs, URLsFoundFromLine...)
}</span>
}
//If there is error during scan, log the error
<span class="cov0" title="0">if scanErr := scanner.Err(); scanErr != nil </span><span class="cov0" title="0">{
log.Fatal(scanErr)
}</span>
<span class="cov0" title="0">return ignoreURLs</span>
}
// remove duplicate strings from a slice of strings
func removeDuplicate(urls []string) []string <span class="cov0" title="0">{
result := make([]string, 0, len(urls))
temp := map[string]struct{}{}
for _, item := range urls </span><span class="cov0" title="0">{
if _, ok := temp[item]; !ok </span><span class="cov0" title="0">{
temp[item] = struct{}{}
result = append(result, item)
}</span>
}
<span class="cov0" title="0">return result</span>
}
func parseUniqueURLsFromFile(filepath string) []string <span class="cov0" title="0">{
//open file and read it
content, err := ioutil.ReadFile(filepath)
if err != nil </span><span class="cov0" title="0">{
log.Fatal(err)
}</span>
<span class="cov0" title="0">textContent := string(content)
//call functions to check the availability of each url
return removeDuplicate(extractURL(textContent))</span>
}
// get the status code from a link.
func getStatusCode(link string) (int, error) <span class="cov8" title="1">{
client := http.Client{
Timeout: 8 * time.Second,
}
resp, err := client.Head(link)
if err != nil </span><span class="cov0" title="0">{
return -1, err
}</span>
<span class="cov8" title="1">return resp.StatusCode, nil</span>
}
//check if urls passed reachable or not
func checkURL(urls []string) <span class="cov0" title="0">{
//use multi-threads to make the process execute faster
var wg sync.WaitGroup
wg.Add(len(urls))
//loop through the urls to check one by one
for _, v := range urls </span><span class="cov0" title="0">{
//annonymous function to make the wg.Done() work
go func(v string) </span><span class="cov0" title="0">{
defer wg.Done()
statusCode, err := getStatusCode(v)
//deal with errors
if err != nil </span><span class="cov0" title="0">{
fmt.Println(v + ": NO RESPONCE!")
}</span> else<span class="cov0" title="0"> {
//allow environment variables to determine the colors of the output
clicolor := os.Getenv("CLICOLOR")
if clicolor == "1" </span><span class="cov0" title="0">{
//set different colors and reponse according to different status code
var (
greenC = "\033[1;32m%s\033[0m"
redC = "\033[1;31m%s\033[0m"
grayC = "\033[1;30m%s\033[0m"
)
switch statusCode </span>{
case 200:<span class="cov0" title="0">
fmt.Printf(greenC, v+": GOOD!\n")</span>
case 400, 404:<span class="cov0" title="0">
fmt.Printf(redC, v+": BAD!\n")</span>
default:<span class="cov0" title="0">
fmt.Printf(grayC, v+": UNKNOWN!\n")</span>
}
} else<span class="cov0" title="0"> {
switch statusCode </span>{
case 200:<span class="cov0" title="0">
fmt.Println(v + ": GOOD!")</span>
case 400, 404:<span class="cov0" title="0">
fmt.Println(v + ": BAD!")</span>
default:<span class="cov0" title="0">
fmt.Println(v + ": UNKNOWN!")</span>
}
}
}
}(v)
}
<span class="cov0" title="0">wg.Wait()</span>
}
//json output structure
type UrlJson struct {
//[ { "url": 'https://www.google.com', "status": 200 }, { "url": 'https://bad-link.com', "status": 404 } ]
Url string
Status int
}
//if json output required, check urls and output json
func checkURLJson(urls []string) <span class="cov0" title="0">{
//use multi-threads to make the process execute faster
var wg sync.WaitGroup
wg.Add(len(urls))
urlsJ := make([]UrlJson, 0)
//loop through the urls to check one by one
for _, v := range urls </span><span class="cov0" title="0">{
go func(v string) </span><span class="cov0" title="0">{
defer wg.Done()
client := http.Client{
Timeout: 8 * time.Second,
}
//check if the url is reachable or not
resp, err := client.Head(v)
//deal with errors
if err != nil </span><span class="cov0" title="0">{
j := UrlJson{v, -1}
urlsJ = append(urlsJ, j)
}</span> else<span class="cov0" title="0"> {
u := UrlJson{v, resp.StatusCode}
urlsJ = append(urlsJ, u)
}</span>
}(v)
}
<span class="cov0" title="0">wg.Wait()
urlsInJson, err := json.Marshal(urlsJ)
if err != nil </span><span class="cov0" title="0">{
log.Fatalf("Something is going wrong with json Marshalling: %s", err)
}</span>
//fmt.Println(urlsInJson)
<span class="cov0" title="0">os.Stdout.WriteString(string(urlsInJson))</span>
}
</pre>
<pre class="file" id="file1" style="display: none">package main
import (
//"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"github.com/mb0/glob"
flag "github.com/spf13/pflag"
)
func main() <span class="cov0" title="0">{
globFlag := flag.Bool("g", false, "Glob pattern")
//add flags of -j, --jason to enable the program to output JSON
jflag := flag.BoolP("json", "j", false, "json output")
// checking version flag
vflag := flag.BoolP("version", "v", false, "version check")
// ignore url flag
ignoreFlag := flag.BoolP("ignore", "i", false, "ignore url patterns")
telescopeFlag := flag.BoolP("telescope", "t", false, "check from telescope")
flag.Parse()
//deal with non-file path, giving usage message
if len(os.Args) == 1 </span><span class="cov0" title="0">{
fmt.Println("help/usage message: To run this program, please pass an argument to it,i.e.: go run urlChecker.go urls.txt")
}</span> else<span class="cov0" title="0"> {
//feature of checking version
if *vflag </span><span class="cov0" title="0">{
fmt.Println(" ***** urlChecker Version 0.2 ***** ")
return
}</span>
<span class="cov0" title="0">if *globFlag </span><span class="cov0" title="0">{
//Assign the glob pattern provided to a local variable
pattern := flag.Args()[0]
//Read all files in the current directory
files, _ := ioutil.ReadDir(".")
//Create a globber object
globber, _ := glob.New(glob.Default())
//Loop through all files
for _, file := range files </span><span class="cov0" title="0">{
//Check if the file name match the glob pattern provided
matched, _ := globber.Match(pattern, file.Name())
//If matched then run the url check on that file
if matched </span><span class="cov0" title="0">{
//open file and read it
content, err := ioutil.ReadFile(file.Name())
if err != nil </span><span class="cov0" title="0">{
log.Fatal(err)
}</span>
<span class="cov0" title="0">textContent := string(content)
fmt.Println(">> ***** UrlChecker is working now...... ***** <<")
fmt.Println("--------------------------------------------------------------------------------------------------")
//call functions to check the availability of each url
checkURL(extractURL(textContent))</span>
}
}
<span class="cov0" title="0">return</span>
}
<span class="cov0" title="0">if *ignoreFlag </span><span class="cov0" title="0">{
combineStrIgnorePatterns := ""
ignoreFilePath := flag.Args()[0]
ignoreList := parseIgnoreURL(ignoreFilePath)
filepath := flag.Arg(1)
//If the user did not provide a second arg, exit with status code 1
if filepath == "" </span><span class="cov0" title="0">{
fmt.Println("A filepath as a second arg is required")
os.Exit(1)
}</span>
//Extract the URLs from filepath provided
<span class="cov0" title="0">URLList := parseUniqueURLsFromFile(filepath)
//If there are links to ignore, then filter them out from URLs list extracted above, else check regularly
if len(ignoreList) != 0 </span><span class="cov0" title="0">{
URLListWithoutIgnores := []string{}
for index, pattern := range ignoreList </span><span class="cov0" title="0">{
if index != len(ignoreList)-1 </span><span class="cov0" title="0">{
combineStrIgnorePatterns += pattern + "|"
}</span> else<span class="cov0" title="0"> {
combineStrIgnorePatterns += pattern
}</span>
}
//Create regex object to match any ignore links in list
<span class="cov0" title="0">re := regexp.MustCompile("^(" + combineStrIgnorePatterns + ")")
//Filter out the ignored links
for _, link := range URLList </span><span class="cov0" title="0">{
if !re.Match([]byte(link)) </span><span class="cov0" title="0">{
URLListWithoutIgnores = append(URLListWithoutIgnores, link)
}</span>
}
//Check with URL List that has no ignored links
<span class="cov0" title="0">checkURL(URLListWithoutIgnores)</span>
} else<span class="cov0" title="0"> {
//Check regularly if there is nothing to ignore
checkURL(URLList)
}</span>
<span class="cov0" title="0">return</span>
}
<span class="cov0" title="0">if *telescopeFlag </span><span class="cov0" title="0">{
var urls []string
urls = parseFromTelescope()
if *jflag </span><span class="cov0" title="0">{
checkURLJson(urls)
}</span> else<span class="cov0" title="0"> {
fmt.Println()
fmt.Println(">> ***** UrlChecker is working now...... ***** <<")
fmt.Println("--------------------------------------------------------------------------------------------------")
checkURL(urls)
}</span>
}
//use for loop to deal with multiple file paths
<span class="cov0" title="0">i := 1
for i+1 <= len(os.Args) </span><span class="cov0" title="0">{
var urls []string
if os.Args[i][0] != '-' </span><span class="cov0" title="0">{
//call functions to check the availability of each url
urls = parseUniqueURLsFromFile(os.Args[i])
//check if there are flags for JSON output or not
if *jflag </span><span class="cov0" title="0">{
checkURLJson(urls)
}</span> else<span class="cov0" title="0"> {
fmt.Println()
fmt.Println(">> ***** UrlChecker is working now...... ***** <<")
fmt.Println("--------------------------------------------------------------------------------------------------")
checkURL(urls)
}</span>
}
<span class="cov0" title="0">i++</span>
}
}
}
</pre>
</div>
</body>
<script>
(function() {
var files = document.getElementById('files');
var visible;
files.addEventListener('change', onChange, false);
function select(part) {
if (visible)
visible.style.display = 'none';
visible = document.getElementById(part);
if (!visible)
return;
files.value = part;
visible.style.display = 'block';
location.hash = part;
}
function onChange() {
select(files.value);
window.scrollTo(0, 0);
}
if (location.hash != "") {
select(location.hash.substr(1));
}
if (!visible) {
select("file0");
}
})();
</script>
</html>