-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
414 lines (365 loc) · 9.18 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
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
package main
import (
"bufio"
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
"github.com/go-enry/go-enry/v2"
"github.com/go-enry/go-enry/v2/data"
)
var (
version = "not-set"
commit = "not-set"
)
func main() {
flag.Usage = usage
breakdownFlag := flag.Bool("breakdown", false, "")
jsonFlag := flag.Bool("json", false, "")
showVersion := flag.Bool("version", false, "Show the enry version information")
allLangs := flag.Bool("all", false, "Show all files, including those identifed as non-programming languages")
progLangs := flag.Bool("prog", false, "Show files identifed as programming languages only")
countMode := flag.String("mode", "byte", "the method used to count file size. Available options are: file, line and byte")
limitKB := flag.Int64("limit", 16*1024, "Analyse first N KB of the file (-1 means no limit)")
flag.Parse()
limit := (*limitKB) * 1024
if *showVersion {
fmt.Println(version)
return
}
root, err := filepath.Abs(flag.Arg(0))
if err != nil {
log.Fatal(err)
}
fileInfo, err := os.Stat(root)
if err != nil {
log.Fatal(err)
}
if fileInfo.Mode().IsRegular() {
err = printFileAnalysis(root, limit, *jsonFlag)
if err != nil {
fmt.Println(err)
}
return
}
out := make(map[string][]string, 0)
err = filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
if err != nil {
log.Println(err)
return filepath.SkipDir
}
if !f.Mode().IsDir() && !f.Mode().IsRegular() {
return nil
}
relativePath, err := filepath.Rel(root, path)
if err != nil {
log.Println(err)
return nil
}
if relativePath == "." {
return nil
}
if f.IsDir() {
relativePath = relativePath + "/"
}
if enry.IsVendor(relativePath) || enry.IsDotFile(relativePath) ||
enry.IsDocumentation(relativePath) || enry.IsConfiguration(relativePath) ||
enry.IsGenerated(relativePath, nil) {
if f.IsDir() {
return filepath.SkipDir
}
return nil
}
if f.IsDir() {
return nil
}
// TODO(bzz): provide API that mimics linguist CLI output for
// - running ByExtension & ByFilename
// - reading the file, if that did not work
// - GetLanguage([]Strategy)
content, err := readFile(path, limit)
if err != nil {
log.Println(err)
return nil
}
if enry.IsGenerated(relativePath, content) {
return nil
}
language := enry.GetLanguage(filepath.Base(path), content)
if language == enry.OtherLanguage {
return nil
}
if *progLangs && enry.GetLanguageType(language) != enry.Programming {
return nil
}
// If we are not asked to display all, do as
// https://github.com/github/linguist/blob/bf95666fc15e49d556f2def4d0a85338423c25f3/lib/linguist/blob_helper.rb#L382
if !*allLangs &&
enry.GetLanguageType(language) != enry.Programming &&
enry.GetLanguageType(language) != enry.Markup {
return nil
}
out[language] = append(out[language], relativePath)
return nil
})
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
switch {
case *jsonFlag && *breakdownFlag:
printBreakDown(out, &buf, true)
case *breakdownFlag:
printPercents(root, out, &buf, *countMode, false)
buf.WriteByte('\n')
printBreakDown(out, &buf, false)
default:
printPercents(root, out, &buf, *countMode, *jsonFlag)
}
fmt.Print(buf.String())
}
const usageFormat = `enry, a simple (and faster) implementation of github/linguist
usage: %[1]s [-mode=(file|line|byte)] [-all] [-prog] <path>
%[1]s [-mode=(file|line|byte)] [-all] [-prog] [-json] [-breakdown] <path>
%[1]s [-mode=(file|line|byte)] [-all] [-prog] [-json] [-breakdown]
%[1]s [-version]
build info: %[2]s, commit: %[3]s, based on linguist commit: %[4]s
`
func usage() {
fmt.Fprintf(
os.Stderr,
usageFormat,
os.Args[0], version, commit[:7], data.LinguistCommit[:7],
)
}
func printBreakDown(out map[string][]string, buff *bytes.Buffer, jsonFlag bool) {
if jsonFlag {
json.NewEncoder(buff).Encode(out)
} else {
for name, language := range out {
fmt.Fprintln(buff, name)
for _, file := range language {
fmt.Fprintln(buff, file)
}
fmt.Fprintln(buff)
}
}
}
// filelistError represents a failed operation that took place across multiple files.
type filelistError []string
func (e filelistError) Error() string {
return fmt.Sprintf("Could not process the following files:\n%s", strings.Join(e, "\n"))
}
func printPercents(root string, fSummary map[string][]string, buff *bytes.Buffer, mode string, isJSON bool) {
// Select the way we quantify 'amount' of code.
reducer := fileCountValues
switch mode {
case "file":
reducer = fileCountValues
case "line":
reducer = lineCountValues
case "byte":
reducer = byteCountValues
}
// Reduce the list of files to a quantity of file type.
var (
total float64
keys []string
unreadableFiles filelistError
fileValues = make(map[string]float64)
)
for fType, files := range fSummary {
val, err := reducer(root, files)
if err != nil {
unreadableFiles = append(unreadableFiles, err...)
}
fileValues[fType] = val
keys = append(keys, fType)
total += val
}
// Slice the keys by their quantity (file count, line count, byte size, etc.).
sort.Slice(keys, func(i, j int) bool {
return fileValues[keys[i]] > fileValues[keys[j]]
})
if isJSON {
results := []map[string]interface{}{} // This will hold our language percentages
for _, fType := range keys {
val := fileValues[fType]
percent := val / total * 100.0
results = append(results, map[string]interface{}{
"percentage": fmt.Sprintf("%.2f%%", percent),
"language": fType,
"color": enry.GetColor(fType),
"type": data.TypeForString(fType).String(),
})
}
if err := json.NewEncoder(buff).Encode(results); err != nil {
log.Println("Error encoding JSON:", err)
}
} else {
// The existing code for plain text format goes here
for _, fType := range keys {
val := fileValues[fType]
percent := val / total * 100.0
buff.WriteString(fmt.Sprintf("%.2f%%\t%s\n", percent, fType))
if unreadableFiles != nil {
buff.WriteString(fmt.Sprintf("\n%s", unreadableFiles.Error()))
}
}
}
}
func fileCountValues(_ string, files []string) (float64, filelistError) {
return float64(len(files)), nil
}
func lineCountValues(root string, files []string) (float64, filelistError) {
var (
filesErr filelistError
t float64
)
for _, fName := range files {
l, _ := getLines(filepath.Join(root, fName), nil)
t += float64(l)
}
return t, filesErr
}
func byteCountValues(root string, files []string) (float64, filelistError) {
var (
filesErr filelistError
t float64
)
for _, fName := range files {
f, err := os.Open(filepath.Join(root, fName))
if err != nil {
filesErr = append(filesErr, fName)
continue
}
fi, err := f.Stat()
f.Close()
if err != nil {
filesErr = append(filesErr, fName)
continue
}
t += float64(fi.Size())
}
return t, filesErr
}
func printFileAnalysis(file string, limit int64, isJSON bool) error {
data, err := readFile(file, limit)
if err != nil {
return err
}
isSample := limit > 0 && len(data) == int(limit)
full := data
if isSample {
// communicate to getLines that we don't have full contents
full = nil
}
totalLines, nonBlank := getLines(file, full)
// functions below can work on a sample
fileType := getFileType(file, data)
language := enry.GetLanguage(file, data)
mimeType := enry.GetMIMEType(file, language)
vendored := enry.IsVendor(file)
if isJSON {
return json.NewEncoder(os.Stdout).Encode(map[string]interface{}{
"filename": filepath.Base(file),
"lines": nonBlank,
"total_lines": totalLines,
"type": fileType,
"mime": mimeType,
"language": language,
"vendored": vendored,
})
}
fmt.Printf(
`%s: %d lines (%d sloc)
type: %s
mime_type: %s
language: %s
vendored: %t
`,
filepath.Base(file), totalLines, nonBlank, fileType, mimeType, language, vendored,
)
return nil
}
func readFile(path string, limit int64) ([]byte, error) {
if limit <= 0 {
return ioutil.ReadFile(path)
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
st, err := f.Stat()
if err != nil {
return nil, err
}
size := st.Size()
if limit > 0 && size > limit {
size = limit
}
buf := bytes.NewBuffer(nil)
buf.Grow(int(size))
_, err = io.Copy(buf, io.LimitReader(f, limit))
return buf.Bytes(), err
}
func getLines(file string, content []byte) (total, blank int) {
var r io.Reader
if content != nil {
r = bytes.NewReader(content)
} else {
// file not loaded to memory - stream it
f, err := os.Open(file)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
r = f
}
br := bufio.NewReader(r)
lastBlank := true
empty := true
for {
data, prefix, err := br.ReadLine()
if err == io.EOF {
break
} else if err != nil {
fmt.Println(err)
break
}
if prefix {
continue
}
empty = false
total++
lastBlank = len(data) == 0
if lastBlank {
blank++
}
}
if !empty && lastBlank {
total++
blank++
}
nonBlank := total - blank
return total, nonBlank
}
func getFileType(file string, content []byte) string {
switch {
case enry.IsImage(file):
return "Image"
case enry.IsBinary(content):
return "Binary"
default:
return "Text"
}
}