forked from openware/gocryptotrader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocumentation.go
530 lines (466 loc) · 13 KB
/
documentation.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
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/file"
"github.com/thrasher-corp/gocryptotrader/core"
)
const (
// DefaultRepo is the main example repository
DefaultRepo = "https://api.github.com/repos/thrasher-corp/gocryptotrader"
// GithubAPIEndpoint allows the program to query your repository
// contributor list
GithubAPIEndpoint = "/contributors"
// LicenseFile defines a license file
LicenseFile = "LICENSE"
// ContributorFile defines contributor file
ContributorFile = "CONTRIBUTORS"
)
var (
// DefaultExcludedDirectories defines the basic directory exclusion list for GCT
DefaultExcludedDirectories = []string{".github",
".git",
"node_modules",
".vscode",
".idea",
"cmd_templates",
"common_templates",
"communications_templates",
"config_templates",
"currency_templates",
"events_templates",
"exchanges_templates",
"portfolio_templates",
"root_templates",
"sub_templates",
"testdata_templates",
"tools_templates",
"web_templates",
}
// global flag for verbosity
verbose bool
// current tool directory to specify working templates
toolDir string
// exposes root directory if outside of document tool directory
repoDir string
// is a broken down version of the documentation tool dir for cross platform
// checking
ref = []string{"gocryptotrader", "cmd", "documentation"}
)
// Contributor defines an account associated with this code base by doing
// contributions
type Contributor struct {
Login string `json:"login"`
URL string `json:"html_url"`
Contributions int `json:"contributions"`
}
// Config defines the running config to deploy documentation across a github
// repository including exclusion lists for files and directories
type Config struct {
GithubRepo string `json:"githubRepo"`
Exclusions Exclusions `json:"exclusionList"`
RootReadme bool `json:"rootReadmeActive"`
LicenseFile bool `json:"licenseFileActive"`
ContributorFile bool `json:"contributorFileActive"`
}
// Exclusions defines the exclusion list so documents are not generated
type Exclusions struct {
Files []string `json:"Files"`
Directories []string `json:"Directories"`
}
// DocumentationDetails defines parameters to update documentation
type DocumentationDetails struct {
Directories []string
Tmpl *template.Template
Contributors []Contributor
Config *Config
}
// Attributes defines specific documentation attributes when a template is
// executed
type Attributes struct {
Name string
Contributors []Contributor
NameURL string
Year int
CapitalName string
DonationAddress string
}
func main() {
flag.BoolVar(&verbose, "v", false, "Verbose output")
flag.StringVar(&toolDir, "tooldir", "", "Pass in the documentation tool directory if outside tool folder")
flag.Parse()
wd, err := os.Getwd()
if err != nil {
fmt.Println("Documentation tool error cannot get working dir:", err)
os.Exit(1)
}
if strings.Contains(wd, filepath.Join(ref...)) {
rootdir := filepath.Dir(filepath.Dir(wd))
repoDir = rootdir
toolDir = wd
} else {
if toolDir == "" {
fmt.Println("Please set documentation tool directory via the tooldir flag if working outside of tool directory")
os.Exit(1)
}
repoDir = wd
}
fmt.Println(core.Banner)
fmt.Println("This will update and regenerate documentation for the different packages in your repo.")
fmt.Println()
if verbose {
fmt.Println("Fetching configuration...")
}
config, err := GetConfiguration()
if err != nil {
log.Fatalf("Documentation Generation Tool - GetConfiguration error %s",
err)
}
if verbose {
fmt.Println("Fetching project directory tree...")
}
dirList, err := GetProjectDirectoryTree(&config)
if err != nil {
log.Fatalf("Documentation Generation Tool - GetProjectDirectoryTree error %s",
err)
}
var contributors []Contributor
if config.ContributorFile {
if verbose {
fmt.Println("Fetching repository contributor list...")
}
contributors, err = GetContributorList(config.GithubRepo)
if err != nil {
log.Fatalf("Documentation Generation Tool - GetContributorList error %s",
err)
}
// Github API missing contributors
contributors = append(contributors, []Contributor{
{
Login: "daniel-cohen",
URL: "https://github.com/daniel-cohen",
Contributions: 1,
},
{
Login: "DirectX",
URL: "https://github.com/DirectX",
Contributions: 1,
},
{
Login: "frankzougc",
URL: "https://github.com/frankzougc",
Contributions: 1,
},
// idoall's contributors were forked and merged, so his contributions
// aren't automatically retrievable
{
Login: "idoall",
URL: "https://github.com/idoall",
Contributions: 1,
},
{
Login: "mattkanwisher",
URL: "https://github.com/mattkanwisher",
Contributions: 1,
},
{
Login: "mKurrels",
URL: "https://github.com/mKurrels",
Contributions: 1,
},
{
Login: "m1kola",
URL: "https://github.com/m1kola",
Contributions: 1,
},
{
Login: "cavapoo2",
URL: "https://github.com/cavapoo2",
Contributions: 1,
},
{
Login: "zeldrinn",
URL: "https://github.com/zeldrinn",
Contributions: 1,
},
{
Login: "starit",
URL: "https://github.com/starit",
Contributions: 1,
},
{
Login: "Jimexist",
URL: "https://github.com/Jimexist",
Contributions: 1,
},
{
Login: "lookfirst",
URL: "https://github.com/lookfirst",
Contributions: 1,
},
{
Login: "merkeld",
URL: "https://github.com/merkeld",
Contributions: 1,
},
{
Login: "CodeLingoTeam",
URL: "https://github.com/CodeLingoTeam",
Contributions: 1,
},
{
Login: "Daanikus",
URL: "https://github.com/Daanikus",
Contributions: 1,
},
}...)
if verbose {
fmt.Println("Contributor List Fetched")
for i := range contributors {
fmt.Println(contributors[i].Login)
}
}
} else {
fmt.Println("Contributor list file disabled skipping fetching details")
}
if verbose {
fmt.Println("Fetching template files...")
}
tmpl, err := GetTemplateFiles()
if err != nil {
log.Fatalf("Documentation Generation Tool - GetTemplateFiles error %s",
err)
}
if verbose {
fmt.Println("All core systems fetched, updating documentation...")
}
err = UpdateDocumentation(DocumentationDetails{
dirList,
tmpl,
contributors,
&config})
if err != nil {
log.Fatalf("Documentation Generation Tool - UpdateDocumentation error %s",
err)
}
fmt.Println("\nDocumentation Generation Tool - Finished")
}
// GetConfiguration retrieves the documentation configuration
func GetConfiguration() (Config, error) {
var c Config
configFilePath := filepath.Join(toolDir, "config.json")
if file.Exists(configFilePath) {
config, err := ioutil.ReadFile(configFilePath)
if err != nil {
return c, err
}
err = json.Unmarshal(config, &c)
if err != nil {
return c, err
}
if c.GithubRepo == "" {
return c, errors.New("repository not set in config.json file, please change")
}
return c, nil
}
fmt.Println("Creating configuration file, please check to add a different github repository path and change preferences")
// Set default params for configuration
c.GithubRepo = DefaultRepo
c.ContributorFile = true
c.LicenseFile = true
c.RootReadme = true
c.Exclusions.Directories = DefaultExcludedDirectories
data, err := json.MarshalIndent(c, "", " ")
if err != nil {
return c, err
}
if err := ioutil.WriteFile(configFilePath, data, 0770); err != nil {
return c, err
}
return c, nil
}
// IsExcluded returns if the file path is included in the exclusion list
func IsExcluded(path string, exclusion []string) bool {
for i := range exclusion {
if path == exclusion[i] {
return true
}
}
return false
}
// GetProjectDirectoryTree uses filepath walk functions to get each individual
// directory name and path to match templates with
func GetProjectDirectoryTree(c *Config) ([]string, error) {
var directoryData []string
if c.RootReadme { // Projects root README.md
directoryData = append(directoryData, repoDir)
}
if c.LicenseFile { // Standard license file
directoryData = append(directoryData, filepath.Join(repoDir, LicenseFile))
}
if c.ContributorFile { // Standard contributor file
directoryData = append(directoryData, filepath.Join(repoDir, ContributorFile))
}
walkfn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// Bypass what is contained in config.json directory exclusion
if IsExcluded(info.Name(), c.Exclusions.Directories) {
if verbose {
fmt.Println("Excluding Directory:", info.Name())
}
return filepath.SkipDir
}
// Don't append parent directory
if strings.EqualFold(info.Name(), "..") {
return nil
}
directoryData = append(directoryData, path)
}
return nil
}
return directoryData, filepath.Walk(repoDir, walkfn)
}
// GetTemplateFiles parses and returns all template files in the documentation
// tree
func GetTemplateFiles() (*template.Template, error) {
tmpl := template.New("")
walkfn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if path == "." || path == ".." {
return nil
}
var parseError error
tmpl, parseError = tmpl.ParseGlob(filepath.Join(path, "*.tmpl"))
if parseError != nil {
if strings.Contains(parseError.Error(), "pattern matches no files") {
return nil
}
return parseError
}
return filepath.SkipDir
}
return nil
}
return tmpl, filepath.Walk(toolDir, walkfn)
}
// GetContributorList fetches a list of contributors from the github api
// endpoint
func GetContributorList(repo string) ([]Contributor, error) {
var resp []Contributor
return resp, common.SendHTTPGetRequest(repo+GithubAPIEndpoint, true, false, &resp)
}
// GetDocumentationAttributes returns specific attributes for a file template
func GetDocumentationAttributes(packageName string, contributors []Contributor) Attributes {
return Attributes{
Name: GetPackageName(packageName, false),
Contributors: contributors,
NameURL: GetGoDocURL(packageName),
Year: time.Now().Year(),
CapitalName: GetPackageName(packageName, true),
DonationAddress: core.BitcoinDonationAddress,
}
}
// GetPackageName returns the package name after cleaning path as a string
func GetPackageName(name string, capital bool) string {
newStrings := strings.Split(name, " ")
var i int
if len(newStrings) > 1 {
// retrieve the latest spacing to define the most childish package name
i = len(newStrings) - 1
}
if capital {
return strings.Title(newStrings[i])
}
return newStrings[i]
}
// GetGoDocURL returns a string for godoc package names
func GetGoDocURL(name string) string {
if strings.Contains(name, " ") {
return strings.Join(strings.Split(name, " "), "/")
}
if name == "testdata" ||
name == "tools" ||
name == ContributorFile ||
name == LicenseFile {
return ""
}
return name
}
// UpdateDocumentation generates or updates readme/documentation files across
// the codebase
func UpdateDocumentation(details DocumentationDetails) error {
for i := range details.Directories {
cutset := details.Directories[i][len(repoDir):]
if cutset != "" && cutset[0] == os.PathSeparator {
cutset = cutset[1:]
}
data := strings.Split(cutset, string(os.PathSeparator))
var temp []string
for x := range data {
if data[x] == ".." {
continue
}
if data[x] == "" {
break
}
temp = append(temp, data[x])
}
var name string
if len(temp) == 0 {
name = "root"
} else {
name = strings.Join(temp, " ")
}
if IsExcluded(name, details.Config.Exclusions.Files) {
if verbose {
fmt.Println("Excluding file:", name)
}
continue
}
if details.Tmpl.Lookup(name) == nil {
fmt.Printf("Template not found for path %s create new template with {{define \"%s\" -}} TEMPLATE HERE {{end}}\n",
details.Directories[i],
name)
continue
}
var mainPath string
if name == LicenseFile || name == ContributorFile {
mainPath = details.Directories[i]
} else {
mainPath = filepath.Join(details.Directories[i], "README.md")
}
err := os.Remove(mainPath)
if err != nil && !(strings.Contains(err.Error(), "no such file or directory") ||
strings.Contains(err.Error(), "The system cannot find the file specified.")) {
return err
}
file, err := os.Create(mainPath)
if err != nil {
return err
}
attr := GetDocumentationAttributes(name, details.Contributors)
err = details.Tmpl.ExecuteTemplate(file, name, attr)
if err != nil {
file.Close()
return err
}
file.Close()
}
return nil
}