-
Notifications
You must be signed in to change notification settings - Fork 0
/
source-index.go
462 lines (347 loc) · 10.5 KB
/
source-index.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
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
package main
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2022 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"fmt"
"io/ioutil"
"os"
"sort"
"strings"
"text/template"
"github.com/essentialkaos/ek/v12/env"
"github.com/essentialkaos/ek/v12/fmtc"
"github.com/essentialkaos/ek/v12/fsutil"
"github.com/essentialkaos/ek/v12/options"
"github.com/essentialkaos/ek/v12/sortutil"
"github.com/essentialkaos/ek/v12/timeutil"
"github.com/essentialkaos/ek/v12/usage"
"github.com/essentialkaos/ek/v12/usage/completion/bash"
"github.com/essentialkaos/ek/v12/usage/completion/fish"
"github.com/essentialkaos/ek/v12/usage/completion/zsh"
"github.com/essentialkaos/ek/v12/usage/update"
)
// ////////////////////////////////////////////////////////////////////////////////// //
const (
APP = "SourceIndex"
VER = "0.3.2"
DESC = "Utility for generating index for source archives"
)
const (
OPT_OUTPUT = "o:output"
OPT_TEMPLATE = "t:template"
OPT_NO_COLOR = "nc:no-color"
OPT_HELP = "h:help"
OPT_VER = "v:version"
OPT_COMPLETION = "completion"
)
// ////////////////////////////////////////////////////////////////////////////////// //
type Index struct {
Projects []*Project
}
type Project struct {
Name string
Releases []*Release
}
type Release struct {
Version string
Sources []*Source
Date string
Latest bool
}
type Source struct {
File string
Ext string
}
// ////////////////////////////////////////////////////////////////////////////////// //
type ReleaseSlice []*Release
func (s ReleaseSlice) Len() int { return len(s) }
func (s ReleaseSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s ReleaseSlice) Less(i, j int) bool {
return sortutil.VersionCompare(s[i].Version, s[j].Version)
}
type ProjectSlice []*Project
func (s ProjectSlice) Len() int { return len(s) }
func (s ProjectSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s ProjectSlice) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
type SourceSlice []*Source
func (s SourceSlice) Len() int { return len(s) }
func (s SourceSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SourceSlice) Less(i, j int) bool {
return s[i].Ext < s[j].Ext
}
// ////////////////////////////////////////////////////////////////////////////////// //
var optMap = options.Map{
OPT_OUTPUT: {Value: "index.html"},
OPT_TEMPLATE: {Value: "default.tpl"},
OPT_NO_COLOR: {Type: options.BOOL},
OPT_HELP: {Type: options.BOOL, Alias: "u:usage"},
OPT_VER: {Type: options.BOOL, Alias: "ver"},
OPT_COMPLETION: {},
}
// ////////////////////////////////////////////////////////////////////////////////// //
func main() {
args, errs := options.Parse(optMap)
if len(errs) != 0 {
for _, err := range errs {
printError(err.Error())
}
os.Exit(1)
}
if options.Has(OPT_COMPLETION) {
genCompletion()
}
if options.GetB(OPT_NO_COLOR) {
fmtc.DisableColors = true
}
if options.GetB(OPT_VER) {
showAbout()
return
}
if options.GetB(OPT_HELP) || len(args) == 0 {
showUsage()
return
}
process(args[0])
}
// process starts processing
func process(dir string) {
err := checkDir(dir)
if err != nil {
printErrorAndExit(err.Error())
}
index := buildIndex(dir)
err = export(index)
if err != nil {
printErrorAndExit(err.Error())
}
projects, releases := index.Stats()
fmtc.Printf(
"{g}Index for %d projects and %d releases successfully generated as {g*}%s{!}\n",
projects, releases, options.GetS(OPT_OUTPUT),
)
}
// checkDir checks directory
func checkDir(dir string) error {
if !fsutil.IsExist(dir) {
return fmt.Errorf("Directory %s doesn't exist", dir)
}
if !fsutil.IsReadable(dir) {
return fmt.Errorf("Directory %s is not readable", dir)
}
if !fsutil.IsExecutable(dir) {
return fmt.Errorf("Directory %s is not executable", dir)
}
if fsutil.IsEmptyDir(dir) {
return fmt.Errorf("Directory %s is empty", dir)
}
return nil
}
// buildIndex builds index with info about all projects in directory
func buildIndex(dir string) *Index {
var index = &Index{}
projects := fsutil.List(dir, true, fsutil.ListingFilter{Perms: "DRX"})
if len(projects) == 0 {
return index
}
for _, projectName := range projects {
project := &Project{
Name: projectName,
Releases: getReleases(projectName, dir+"/"+projectName),
}
if len(project.Releases) == 0 {
continue
}
index.Projects = append(index.Projects, project)
}
sort.Sort(ProjectSlice(index.Projects))
return index
}
// getReleases reads given directory and return slice with info about releases
func getReleases(project, dir string) []*Release {
var releases map[string]*Release
sources := fsutil.List(dir, true, fsutil.ListingFilter{Perms: "FR"})
if len(sources) == 0 {
return []*Release{}
}
releases = make(map[string]*Release)
for _, sourceName := range sources {
version, source := parseSourceName(project, sourceName)
if version == "current" || version == "" {
continue
}
release, ok := releases[version]
if !ok {
release = &Release{Version: version, Sources: []*Source{}}
releases[version] = release
}
if release.Date == "" {
cd, _ := fsutil.GetMTime(dir + "/" + sourceName)
release.Date = timeutil.Format(cd, "%Y/%m/%d")
}
release.Sources = append(release.Sources, source)
}
if len(releases) == 0 {
return []*Release{}
}
return releaseMapToSlice(releases)
}
// parseSourceName parses source name and return version and source info
func parseSourceName(project, name string) (string, *Source) {
verIndex := strings.LastIndex(name, "-")
if verIndex == -1 {
return "", nil
}
verAndExt := name[verIndex+1:]
var (
version string
ext string
)
switch {
case strings.HasSuffix(verAndExt, ".zip"):
version = strings.Replace(verAndExt, ".zip", "", -1)
ext = "ZIP"
case strings.HasSuffix(verAndExt, ".7z"):
version = strings.Replace(verAndExt, ".7z", "", -1)
ext = "7Z"
case strings.HasSuffix(verAndExt, ".tar.bz2"):
version = strings.Replace(verAndExt, ".tar.bz2", "", -1)
ext = "TAR.BZ2"
case strings.HasSuffix(verAndExt, ".tbz2"):
version = strings.Replace(verAndExt, ".tbz2", "", -1)
ext = "TAR.BZ2"
case strings.HasSuffix(verAndExt, ".tar.gz"):
version = strings.Replace(verAndExt, ".tar.gz", "", -1)
ext = "TAR.GZ"
case strings.HasSuffix(verAndExt, ".tgz"):
version = strings.Replace(verAndExt, ".tgz", "", -1)
ext = "TAR.GZ"
case strings.HasSuffix(verAndExt, ".tar.xz"):
version = strings.Replace(verAndExt, ".tar.xz", "", -1)
ext = "TAR.XZ"
case strings.HasSuffix(verAndExt, ".txz"):
version = strings.Replace(verAndExt, ".txz", "", -1)
ext = "TAR.XZ"
}
return version, &Source{File: project + "/" + name, Ext: ext}
}
// releaseMapToSlice converts map with releases to sorted slice
func releaseMapToSlice(releases map[string]*Release) []*Release {
var result []*Release
for _, release := range releases {
sort.Sort(SourceSlice(release.Sources))
result = append(result, release)
}
sort.Sort(sort.Reverse(ReleaseSlice(result)))
result[0].Latest = true
return result
}
// export renders template with inforamtion from index and save as file
func export(index *Index) error {
templateFile := getTemplateFile()
outputFile := options.GetS(OPT_OUTPUT)
if templateFile == "" {
return fmt.Errorf("Can't use given template")
}
if fsutil.IsExist(outputFile) {
err := os.Remove(outputFile)
if err != nil {
return err
}
}
fd, err := os.OpenFile(outputFile, os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer fd.Close()
tpl, err := ioutil.ReadFile(templateFile)
if err != nil {
return err
}
t := template.New("template")
t, err = t.Parse(string(tpl[:]))
return t.Execute(fd, index)
}
// getTemplateFile returns path to template file
func getTemplateFile() string {
template := options.GetS(OPT_TEMPLATE)
if fsutil.CheckPerms("FR", template) {
return template
}
gopath := env.Get().GetS("GOPATH")
template = gopath + "/src/github.com/essentialkaos/source-index/templates/" + template
if fsutil.CheckPerms("FR", template) {
return template
}
return ""
}
// printError prints error message to console
func printError(f string, a ...interface{}) {
fmtc.Fprintf(os.Stderr, "{r}"+f+"{!}\n", a...)
}
// printError prints warning message to console
func printWarn(f string, a ...interface{}) {
fmtc.Fprintf(os.Stderr, "{y}"+f+"{!}\n", a...)
}
// printErrorAndExit prints error mesage and exit with exit code 1
func printErrorAndExit(f string, a ...interface{}) {
printError(f, a...)
os.Exit(1)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// Stats returns number of projects and releases in index
func (i *Index) Stats() (int, int) {
var releases int
for _, project := range i.Projects {
releases += len(project.Releases)
}
return len(i.Projects), releases
}
// ////////////////////////////////////////////////////////////////////////////////// //
// showUsage prints usage info
func showUsage() {
genUsage().Render()
}
// genUsage
func genUsage() *usage.Info {
info := usage.NewInfo("", "dir")
info.AddOption(OPT_OUTPUT, "Output file {s-}(index.html by default){!}", "file")
info.AddOption(OPT_TEMPLATE, "Template {s-}(template.tpl by default){!}", "file")
info.AddOption(OPT_NO_COLOR, "Disable colors in output")
info.AddOption(OPT_HELP, "Show this help message")
info.AddOption(OPT_VER, "Show version")
return info
}
// genCompletion generates completion for different shells
func genCompletion() {
info := genUsage()
switch options.GetS(OPT_COMPLETION) {
case "bash":
fmt.Printf(bash.Generate(info, "source-index"))
case "fish":
fmt.Printf(fish.Generate(info, "source-index"))
case "zsh":
fmt.Printf(zsh.Generate(info, optMap, "source-index"))
default:
os.Exit(1)
}
os.Exit(0)
}
// showAbout prints basic info about app
func showAbout() {
about := &usage.About{
App: APP,
Version: VER,
Desc: DESC,
Year: 2006,
Owner: "ESSENTIAL KAOS",
License: "Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>",
UpdateChecker: usage.UpdateChecker{"essentialkaos/source-index", update.GitHubChecker},
}
about.Render()
}