-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
1149 lines (1066 loc) · 41.9 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
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"net/http"
"bufio"
"bytes"
"time"
"strings"
"encoding/json"
"fmt"
"flag"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"runtime"
"github.com/rickar/props"
"strongback.org/cli/files"
)
var (
Version string
Date string
Build string
ExecName string
)
type Environment struct {
userHome string
existingStrongback Component
existingWpiLib Component
httpClient http.Client
availableReleases []ReleaseInfo
dependencies []DependencyInfo
teamNumber string
}
type Component struct {
installed bool
version string
path string
properties *props.Properties
}
type DependencyInfo struct {
Name string
Version string
LibNames []string
Installed bool
SameVersion bool
}
type ReleaseInfo struct {
Name string
Url string
Html_url string
Id int
Tag_name string
Draft bool
Prerelease bool
Published_at string
Assets []AssetInfo
}
type AssetInfo struct {
Url string
Browser_download_url string
Id int
Name string
Label string
Content_type string
Size int
}
// NewProperties creates a new environment.
func NewEnvironment() *Environment {
e := new(Environment)
e.httpClient = http.Client{Timeout: 300 * time.Second}
e.userHome = files.UserHomeDir()
e.teamNumber = ""
e.DiscoverStrongback()
e.DiscoverWpiLib()
return e
}
func (env *Environment) DiscoverStrongback() {
dir := env.userHome + files.PathSeparator + "strongback"
strongback := new(Component)
strongback.path = dir
strongback.version = "<none>"
strongback.installed = false
if files.IsExistingDirectory(dir) {
// Load the properties file ...
propPath := dir + files.PathSeparator + "strongback.properties"
if files.IsExistingFile(propPath) {
props := *files.LoadPropertiesFile(propPath)
// Create the installed component ...
strongback.properties = &props
if &props != nil && props.Get("strongback.version") != "" {
strongback.version = props.Get("strongback.version")
strongback.installed = true
}
}
// Load the information about each dependency
env.dependencies = make([]DependencyInfo, 0, 2)
filesInDir, err := ioutil.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
for _, file := range filesInDir {
match, err := filepath.Match("*-lib-info.properties", file.Name())
if err != nil {
log.Fatal(err)
} else if match {
propPath := dir + files.PathSeparator + file.Name()
props := *files.LoadPropertiesFile(propPath)
info := &DependencyInfo{}
info.Name = props.Get("name")
info.Version = props.Get("version")
info.LibNames = strings.Split(props.Get("jarNames"), ",")
env.dependencies = append(env.dependencies, *info)
}
}
}
env.existingStrongback = *strongback
}
func (env *Environment) DiscoverWpiLib() {
dir := env.userHome + filepath.FromSlash("/wpilib")
wpilib := new(Component)
wpilib.path = dir
propPath := dir + filepath.FromSlash("/wpilib.properties")
if files.IsExistingDirectory(dir) && files.IsExistingFile(propPath) {
props := *files.LoadPropertiesFile(propPath)
// Create the installed component ...
wpilib.properties = &props
if &props != nil {
wpilib.version = props.Get("version")
wpilib.installed = true
teamNumberStr := props.Get("team-number")
if len(teamNumberStr) != 0 {
env.teamNumber = teamNumberStr
}
// See which Strongback dependencies are installed ...
for i, dependency := range env.dependencies {
exactMatch := true
installed := true
for _, libName := range dependency.LibNames {
strongbackFilePath := env.existingStrongback.path + filepath.FromSlash("/java/lib/" + libName)
wpiLibFilePath := dir + filepath.FromSlash("/user/java/lib/" + libName)
if !files.IsExistingFile(strongbackFilePath) || !files.IsExistingFile(wpiLibFilePath) {
installed = false
}
if exactMatch && !files.FilesHaveSameContent(strongbackFilePath, wpiLibFilePath) {
exactMatch = false
}
}
// Only considered installed if all the files match exactly ...
dependency.Installed = installed
dependency.SameVersion = exactMatch
env.dependencies[i] = dependency
}
}
} else {
wpilib.properties = props.NewProperties()
}
env.existingWpiLib = *wpilib
}
func (env *Environment) GetAvailableReleases() []ReleaseInfo {
if env.availableReleases == nil {
// Get the available releases ...
var releases []ReleaseInfo
env.getJson("https://api.github.com/repos/strongback/strongback-java/releases", &releases)
env.availableReleases = releases
}
return env.availableReleases
}
func (env *Environment) GetLatestRelease(includePreReleases bool) *ReleaseInfo {
releases := env.GetAvailableReleases()
for _, release := range releases {
if !includePreReleases && release.IsPreRelease() {
// Skip the pre-releases
continue
}
return &release
}
return nil
}
func (env *Environment) GetRelease(version string) *ReleaseInfo {
if len(version) == 0 {
return env.GetLatestRelease(false)
}
releases := env.GetAvailableReleases()
for _, release := range releases {
if release.Name == version {
return &release
}
}
return nil
}
func (env *Environment) GetDependencyInfoForJarFile(jarFileName string) *DependencyInfo {
for _, dependency := range env.dependencies {
for _, libName := range dependency.LibNames {
if libName == jarFileName {
return &dependency
}
}
}
return nil
}
func (release *ReleaseInfo) IsPreRelease() bool {
return strings.Contains(release.Name,"Alpha") || strings.Contains(release.Name,"Beta")|| strings.HasPrefix(release.Name,"v")
}
func (env *Environment) PrintReleases(includePreReleases bool) {
// Get the available releases ...
releases := env.GetAvailableReleases()
visibleReleases := 0
for _, release := range releases {
if !includePreReleases && release.IsPreRelease() {
// Skip the pre-releases
} else {
visibleReleases = visibleReleases+1
}
}
fmt.Printf("\nFound %d releases of the Strongback Java Library:\n", visibleReleases)
currentVersion := env.existingStrongback.version
for _, release := range releases {
if release.Name == currentVersion {
fmt.Printf(" %s (installed)\n",release.Name)
} else {
if !includePreReleases && release.IsPreRelease() {
// Skip the pre-releases
} else {
fmt.Printf(" %s\n",release.Name)
}
}
}
}
func (env *Environment) PrintVersion() {
if env.existingStrongback.installed {
fmt.Println("strongback library version " + env.existingStrongback.version)
} else {
fmt.Println("strongback library version <none>")
}
fmt.Println("strongback cli version " + Version)
}
func (env *Environment) PrintInfo() {
fmt.Println()
fmt.Println("Strongback Client")
fmt.Println(" version: " + Version)
fmt.Println(" build date: " + Date)
fmt.Println()
fmt.Println("Strongback Java Library")
if env.existingStrongback.installed {
fmt.Println(" location: " + env.existingStrongback.path)
fmt.Println(" current version: " + env.existingStrongback.version)
fmt.Println(" build date: " + env.existingStrongback.properties.Get("build.date"))
strongbackWpiLibVersion := env.existingStrongback.properties.Get("wpilib.version")
if len(strongbackWpiLibVersion) > 0 {
fmt.Println(" requires WPILib: " + strongbackWpiLibVersion + " (or later)")
}
} else {
fmt.Println(" not yet installed (use 'install' command)")
}
fmt.Println()
fmt.Println("WPILib Java Library")
if env.existingWpiLib.installed {
fmt.Println(" location: " + env.existingWpiLib.path)
if len(env.teamNumber) != 0 {
fmt.Println(" team number: " + env.teamNumber)
} else {
fmt.Println(" team number: <create robot project in Eclipse>")
}
} else {
fmt.Println(" not yet installed")
}
// Print the dependency libraries ...
for _, dependency := range env.dependencies {
fmt.Println()
fmt.Println(dependency.Name)
fmt.Println(" version: " + dependency.Version)
fmt.Println(" location: " + env.existingWpiLib.path + filepath.FromSlash("/user/java/lib/"))
fmt.Println(" JAR file(s): " + strings.Join(dependency.LibNames, ", "))
if dependency.SameVersion {
fmt.Println(" installed at: " + env.existingStrongback.path + filepath.FromSlash("/libs/"))
} else if dependency.Installed {
fmt.Println(" different version is installed; use 'strongback install-deps' to install this version")
} else {
fmt.Println(" not yet installed into WPILib; use 'strongback install-deps' to install this version")
}
}
fmt.Println()
}
func (env *Environment) getJson(url string, target interface{}) {
r, err := env.httpClient.Get(url)
if err != nil {
panic(err)
}
defer r.Body.Close()
decodeErr := json.NewDecoder(r.Body).Decode(target)
if decodeErr != nil {
fmt.Printf("%T\n%s\n%#v\n",decodeErr, decodeErr, decodeErr)
fmt.Print(decodeErr)
switch v := decodeErr.(type){
case *json.SyntaxError:
fmt.Print(v)
// fmt.Println(string(body[v.Offset-40:v.Offset]))
}
//panic(decodeErr)
}
}
func (env *Environment) GetUserConfirmation(maxAskTimes int) bool {
reader := bufio.NewReader(os.Stdin)
// Confirm removal ...
for times := 1; times<=maxAskTimes; times++ {
fmt.Printf("Are you sure? [y/n] ")
response, err := reader.ReadString('\n')
if err != nil {
return false
}
response = strings.ToLower(strings.TrimSpace(response))
if response == "y" || response == "yes" {
return true
} else if response == "n" || response == "no" {
return false
}
}
return false
}
func (env *Environment) UninstallRelease(skipPrompt bool, skipArchive bool, verbose bool, removeArchive bool) bool {
fmt.Println()
if env.existingStrongback.installed {
fmt.Printf("Removing Java Library version %s\n", env.existingStrongback.version)
if skipPrompt || env.GetUserConfirmation(3) {
env.RemoveInstalledRelease(skipArchive, verbose)
if removeArchive {
fmt.Println()
fmt.Println("Removing all archives of previous installations. This cannot be undone!")
fmt.Println()
if skipPrompt || env.GetUserConfirmation(3) {
archiveDirPath := env.existingStrongback.path + "-archives"
os.RemoveAll(archiveDirPath)
fmt.Println("Archives of previous installations removed.")
}
}
} else {
fmt.Println()
fmt.Println("Existing without uninstalling.")
os.Exit(1)
}
return true
}
fmt.Println("No Strongback Java Library version is installed.")
return false;
}
func (env *Environment) RemoveInstalledRelease(skipArchive bool, verbose bool) bool {
if env.existingStrongback.installed {
if !skipArchive {
// There is an existing release, so archive it
historyArchiveName := "strongback-" + env.existingStrongback.version + ".tar.gz"
// First, make sure the archive directory exists
archiveDirPath := env.existingStrongback.path + "-archives"
files.MkDir(archiveDirPath)
// Create a tar.gz file with the existing installation, overwriting any existing archive
historyArchivePath := archiveDirPath + files.PathSeparator + historyArchiveName
fmt.Println(" archiving current " + env.existingStrongback.version + " installation to " + historyArchivePath)
err := files.CreateTar(historyArchivePath, env.userHome, "strongback", false)
if err != nil {
panic(err)
}
}
os.RemoveAll(env.existingStrongback.path)
return true
}
return false
}
func (env *Environment) InstallRelease(desiredVersion string, skipArchive bool, forceReplaceLibs bool, verbose bool) bool {
fmt.Println()
var release *ReleaseInfo
latestAvailable := ""
if len(desiredVersion) == 0 {
release = env.GetLatestRelease(false)
latestAvailable = "latest available"
desiredVersion = release.Name
if len(desiredVersion) == 0 {
fmt.Println("Unable to find the latest Strongback Java Library version")
return false
}
}
// At this point, we have a valid desiredVersion
// See what is already installed
existingVersion := env.existingStrongback.version
if desiredVersion == existingVersion {
fmt.Printf("Strongback %s is already installed\n", desiredVersion)
// Add the Strongback JARs to the WPILib's `user/java/lib` directory if it exists
env.InstallLibsAsWpiUserLibs(forceReplaceLibs, verbose)
return true
}
if release == nil {
// The desiredVersion was specified and didn't match what we already have installed, so get the release info
release = env.GetRelease(desiredVersion)
if release == nil {
fmt.Println("Unable to find and install Strongback Java Library version " + desiredVersion)
return false
}
}
// Find the asset we want to download
var desiredAsset *AssetInfo
for _, asset := range release.Assets {
if asset.Content_type == "application/x-gzip" {
desiredAsset = &asset
break
}
}
if desiredAsset == nil {
fmt.Println("Unable to find a TAR archive for version " + desiredVersion)
return false
}
fmt.Println("Installing " + latestAvailable + " Strongback Java Library " + release.Name)
fmt.Println()
archiveName := desiredAsset.Name
// See if the asset exists in our archive
archiveDirPath := env.existingStrongback.path + "-archives";
archiveAssetPath := archiveDirPath + files.PathSeparator + archiveName
if files.IsExistingFile(archiveAssetPath) {
fmt.Println(" found previously installed archive at " + archiveAssetPath)
} else {
// Make sure the archive directory exists
files.MkDir(archiveDirPath)
// Download the desired release to a local file in the archive
fmt.Print(" downloading " + archiveName + " to " + archiveAssetPath)
resp, err := env.httpClient.Get(desiredAsset.Browser_download_url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
// Create the file in the archive
file, err := os.Create(archiveAssetPath)
if err != nil {
fmt.Println(err)
panic(err)
}
defer file.Close()
// Copy the downloaded content into the file
size, err := io.Copy(file, resp.Body)
if err != nil {
panic(err)
}
fmt.Printf(" (%v bytes)\n", size)
}
if env.existingStrongback.installed {
if env.RemoveInstalledRelease(skipArchive, verbose) {
fmt.Println(" replacing existing " + env.existingStrongback.version + " installation with " + desiredVersion + " at " + env.existingStrongback.path)
}
} else {
fmt.Println(" installing at " + env.userHome + files.PathSeparator + "strongback")
}
// Install this release
err := files.ExtractTar(archiveAssetPath, env.userHome, verbose)
if err != nil {
panic(err)
}
// Add the Strongback JARs to the WPILib's `user/java/lib` directory if it exists
env.InstallLibsAsWpiUserLibs(forceReplaceLibs, verbose)
// Update the one we know about
env.DiscoverStrongback()
env.DiscoverWpiLib()
// If there is no Eclipse directory in the Strongback installation, then make it ...
if !files.IsExistingDirectory(env.existingStrongback.path + filepath.FromSlash("/java/eclipse")) {
projectName := "initialeclipseproject"
projectDirPath := env.existingStrongback.path + files.PathSeparator + projectName
os.RemoveAll(projectDirPath)
env.NewProject(projectName, env.existingStrongback.path, "", true, true, true)
os.RemoveAll(projectDirPath)
}
return true
}
func (env *Environment) InstallLibsAsWpiUserLibs(forceReplaceLibs bool, verbose bool) bool {
wpiUserLibPath := env.existingWpiLib.path + filepath.FromSlash("/user/java/lib/")
if !env.existingWpiLib.installed || !files.IsExistingDirectory(env.existingWpiLib.path) {
// There is no WPILib directory, so make the user lib directory
fmt.Println(" making WPILib user library directory at " + wpiUserLibPath)
files.MkDir(wpiUserLibPath)
}
// Add the Strongback JARs to the WPILib's `user/java/lib` directory if it exists
if !files.IsExistingDirectory(env.existingWpiLib.path + filepath.FromSlash("/user/java/lib")) {
// This version of the WPILib does not have a user lib directory
return false
}
// Always copy the Strongback JAR
if forceReplaceLibs {
fmt.Println(" overwriting as WPILib user libraries at " + wpiUserLibPath)
} else {
fmt.Println(" adding WPILib user libraries at " + wpiUserLibPath)
}
strongbackLibPath := env.existingStrongback.path + filepath.FromSlash("/java/lib/")
err := files.CopyFile(strongbackLibPath + "strongback.jar", wpiUserLibPath + "strongback.jar")
if err != nil {
panic(err)
return false
}
if verbose {
fmt.Println(" strongback.jar")
}
// Copy the non-Strongback JARs if they don't exist or if forced to
skipped := 0
entries, _ := ioutil.ReadDir(strongbackLibPath)
for _, f := range entries {
if f.Mode().IsRegular() && !strings.HasPrefix(f.Name(), "strongback") {
// This is a file and not the Strongback JAR, so try to copy this ...
pathToUserLib := wpiUserLibPath + f.Name()
dependency := env.GetDependencyInfoForJarFile(f.Name())
if forceReplaceLibs || !files.IsExistingFile(pathToUserLib) {
libVersion := "<unknown>"
if dependency != nil {
libVersion = dependency.Version
}
if verbose {
fmt.Println(" " + f.Name() + " version " + libVersion)
}
err = files.CopyFile(strongbackLibPath + f.Name(), pathToUserLib)
if err != nil {
panic(err)
return false
}
} else {
// Determine if this dependency is exactly the same as what Strongback requires
if dependency != nil && dependency.SameVersion {
// It's an exact match, so report this
if verbose {
fmt.Println(" " + f.Name() + " already matches version required by Strongback")
}
} else {
// It's not an exact match, so
skipped = skipped + 1
if verbose {
fmt.Println(" " + f.Name() + " exists and left unmodified")
}
}
}
}
}
if skipped != 0 {
fmt.Println()
fmt.Printf("Found and left untouched %d existing WPILib user library files.\n", skipped)
fmt.Printf("Use '--overwrite' option to force replacement with Strongback's version.\n")
}
fmt.Println()
return true
}
func (env *Environment) InstallDeps(forceReplaceLibs bool, verbose bool) bool {
if !env.existingStrongback.installed {
return env.InstallRelease("",false, forceReplaceLibs, verbose)
}
fmt.Println("")
fmt.Println("Installing Strongback " + env.existingStrongback.version + " dependencies.")
// Add the Strongback JARs to the WPILib's `user/java/lib` directory if it exists
env.InstallLibsAsWpiUserLibs(forceReplaceLibs, verbose)
// Update the one we know about
env.DiscoverStrongback()
env.DiscoverWpiLib()
// If there is no Eclipse directory in the Strongback installation, then make it ...
if !files.IsExistingDirectory(env.existingStrongback.path + filepath.FromSlash("/java/eclipse")) {
projectName := "initialeclipseproject"
projectDirPath := env.existingStrongback.path + files.PathSeparator + projectName
os.RemoveAll(projectDirPath)
env.NewProject(projectName, env.existingStrongback.path, "", true, true, true)
os.RemoveAll(projectDirPath)
}
return true
}
func (env *Environment) CheckInstalled() {
if !env.existingStrongback.installed {
fmt.Println("You must first install the Strongback Java Library using:")
fmt.Println()
PrintInstallUsage()
os.Exit(2)
}
}
func (env *Environment) DecodeFile(inputFile string, outputFile string, verbose bool) {
suffix := ".sh"
if runtime.GOOS == "windows" {
suffix = ".bat"
}
var args []string
args = append(args, "log-decoder")
args = append(args, "-f")
args = append(args, inputFile)
if len(outputFile) != 0 {
args = append(args, "-o")
args = append(args, outputFile)
}
commandPath := env.existingStrongback.path + filepath.FromSlash("/java/bin/strongback") + suffix;
out, err := exec.Command(commandPath, args...).Output()
if err != nil {
log.Fatal("Error running " + commandPath + " " + strings.Join(args, " "))
panic(err)
}
fmt.Println(string(out))
}
func (env *Environment) NewProject(name string, directory string, packageName string, eclipse bool, overwrite bool, silent bool) bool {
suffix := ".sh"
if runtime.GOOS == "windows" {
suffix = ".bat"
}
if len(packageName) == 0 {
if len(env.teamNumber) != 0 {
packageName = "org.frc" + env.teamNumber + ".robot"
} else {
if !silent {
fmt.Println()
fmt.Println("No package name was specified, and WPILib has not been initialized with a team number.")
fmt.Println("Aborting.")
}
return false
}
}
var args []string
args = append(args, "new-project")
args = append(args, "-n")
args = append(args, name)
args = append(args, "-d")
args = append(args, directory)
args = append(args, "-p")
args = append(args, packageName)
if eclipse {
args = append(args, "-e")
}
if overwrite {
args = append(args, "-o")
}
commandPath := env.existingStrongback.path + filepath.FromSlash("/java/bin/strongback") + suffix;
cmd := exec.Command(commandPath, args...)
var stdout bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
outMsg := stdout.String()
errMsg := stderr.String()
// Look for specific errors output by this command
if len(errMsg) != 0 {
if !silent {
errMsg := strings.Replace(errMsg,"run this application", "run this command", 1)
errMsg = strings.Replace(errMsg,"-o option", "--overwrite flag", 1)
if strings.Contains(errMsg, "file already exists") {
// Get the name of the file that already exists ...
slash := strings.LastIndexAny(errMsg, "/\\")
if slash > -1 {
existingFileName := strings.TrimSpace(errMsg[slash:len(errMsg)])
fmt.Println()
fmt.Println("Error: the file '" + existingFileName + "'' already exists. Run this command with the --overwrite flag to replace any existing files.")
return false
}
}
// Not sure what error this is, so just print it
fmt.Println()
fmt.Println("Error: " + errMsg)
}
return false
}
if err != nil {
log.Fatal("Error running " + commandPath + " " + strings.Join(args, " "))
panic(err)
}
if !silent {
fmt.Println(outMsg)
}
return true
}
func PrintUsage() {
fmt.Println(" " + ExecName + " <command> [<args>]")
fmt.Println()
fmt.Println("Available commands include:")
fmt.Println(" decode Converts a binary data/event log file to a readable CSV file")
fmt.Println(" help Displays information about using this utility")
fmt.Println(" info Displays the information about this utility and what's installed")
fmt.Println(" install Install or upgrade the Strongback Java Library")
fmt.Println(" install-deps Install the's 3rd party libraries in the current Strongback Java Library")
fmt.Println(" as WPILib user libraries")
fmt.Println(" new-project Creates a new project configured to use Strongback (only 1.x)")
fmt.Println(" releases Display the available versions of the Strongback Java Library")
fmt.Println(" version Display the currently installed version")
fmt.Println(" uninstall Remove an existing Strongback Java Library installation")
fmt.Println()
fmt.Println("Additional help is available for each command with:")
fmt.Println()
fmt.Println(" " + ExecName + " help <command>")
fmt.Println()
}
func PrintInstallUsage() {
fmt.Println(" " + ExecName + " install [--skip-archive] [--overwrite] [--verbose] [version] ")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Install or upgrade the Strongback Java Library.")
fmt.Println()
fmt.Println("Options:")
fmt.Println()
fmt.Println(" --skip-archive")
fmt.Println(" Do not archive the current installation before installing the new version.")
fmt.Println(" This flag does nothing if there is no current installation.")
fmt.Println()
fmt.Println(" --overwrite")
fmt.Println(" Always install Strongback's 3rd party libraries as WPILib user libraries,")
fmt.Println(" replacing any user library files that already exist in the WPILib installation.")
fmt.Println()
fmt.Println(" --verbose")
fmt.Println(" Print additional detailed information during the operation.")
fmt.Println()
fmt.Println("Arguments:")
fmt.Println()
fmt.Println(" version")
fmt.Println(" The version of the Strongback Java Library that should be installed.")
fmt.Println(" The latest version is used if an explicit version is not provided.")
fmt.Println()
}
func PrintInstallDepsUsage() {
fmt.Println(" " + ExecName + " install-deps [--overwrite] [--verbose]")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Install the's 3rd party libraries in the current Strongback Java Library")
fmt.Println(" as WPILib user libraries")
fmt.Println()
fmt.Println("Options:")
fmt.Println()
fmt.Println(" --overwrite")
fmt.Println(" Always install Strongback's 3rd party libraries as WPILib user libraries,")
fmt.Println(" replacing any user library files that already exist in the WPILib installation.")
fmt.Println()
fmt.Println(" --verbose")
fmt.Println(" Print additional detailed information during the operation.")
fmt.Println()
}
func PrintUninstallUsage() {
fmt.Println(" " + ExecName + " uninstall [--skip-archive] [--remove-archives] [--verbose] [--yes]")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Remove any Strongback Java Library that is already installed.")
fmt.Println()
fmt.Println("Options:")
fmt.Println()
fmt.Println(" --skip-archive")
fmt.Println(" Do not archive the current installation before removing it.")
fmt.Println(" This flag does nothing if there is no current installation.")
fmt.Println()
fmt.Println(" --remove-archives")
fmt.Println(" Remove all archives of previous Strongback Java Library installations.")
fmt.Println(" Doing this is permanent and will prevent recoverying previous installations.")
fmt.Println()
fmt.Println(" --verbose")
fmt.Println(" Print additional detailed information during the operation.")
fmt.Println()
fmt.Println(" --yes")
fmt.Println(" Do not prompt about removing existing installation or archives.")
fmt.Println()
}
func PrintReleasesUsage() {
fmt.Println(" " + ExecName + " releases [--all]")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" List the releases Strongback Java Library that are available as listed on the")
fmt.Println(" " + ExecName + " GitHub organization. The installed version is highlighted.")
fmt.Println()
fmt.Println("Options:")
fmt.Println(" --all")
fmt.Println(" Show all the releases, including alpha, beta, and other early")
fmt.Println(" releases that are only for testing purposes. Unless this is")
fmt.Println(" provided, only releases that are ready for use on robots are listed.")
fmt.Println()
}
func PrintNewProjectUsage() {
fmt.Println(" " + ExecName + " new-project [--directory <path>] [--package <packageName>]")
fmt.Println(" [--no-eclipse] [--overwrite]")
fmt.Println(" name")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Create a new FRC robot project using the Strongback Java Library.")
fmt.Println(" No files will be overwritten unless --overwrite is specified.")
fmt.Println()
fmt.Println("Arguments:")
fmt.Println()
fmt.Println(" name")
fmt.Println(" The name of the new project.")
fmt.Println()
fmt.Println("Options:")
fmt.Println(" --directory <parent_directory>")
fmt.Println(" The directory where this utility should place the new project.")
fmt.Println(" Defaults to the current directory.")
fmt.Println()
fmt.Println(" --package")
fmt.Println(" Specifies a custom initial package for Robot.java. Defaults to 'org.frc<teamNumber>.robot'")
fmt.Println(" where the team number is obtained from the WPILib installation or is '0' if WPILib is not")
fmt.Println(" installed and initialized through Eclipse.")
fmt.Println()
fmt.Println(" --no-eclipse")
fmt.Println(" Use this if you are not using Eclipse to avoid creating Eclipse project metadata files.")
fmt.Println()
fmt.Println(" --overwrite")
fmt.Println(" Forces overwriting of existing files. This is required if the directory or files exist.")
fmt.Println()
}
func PrintDecodeUsage() {
fmt.Println(" " + ExecName + " decode [--verbose] input [output]")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Converts binary log files to readable CSV files")
fmt.Println()
fmt.Println("Arguments:")
fmt.Println()
fmt.Println(" input")
fmt.Println(" The path to the binary log recorded on the robot by the Strongback Java Library.")
fmt.Println()
fmt.Println(" output")
fmt.Println(" The path to the file to be written by this utility and that will contain the")
fmt.Println(" comma separated values (CSV). If not provided, the output will be saved in the")
fmt.Println(" current directory in a file with the same filename as the input but with a .csv extension.")
fmt.Println()
fmt.Println("Options:")
fmt.Println()
fmt.Println(" --verbose")
fmt.Println(" Print additional detailed information during the operation.")
fmt.Println()
}
func PrintVersionUsage() {
fmt.Println(" " + ExecName + " version")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Output the shortened version information for the Strongback utility and Java Library")
fmt.Println()
}
func PrintInfoUsage() {
fmt.Println(" " + ExecName + " info")
fmt.Println()
fmt.Println("Description:")
fmt.Println(" Output the detailed version information for the Strongback utility and Java Library")
fmt.Println()
}
func PrintUsageError(err error) {
fmt.Println()
fmt.Println("Error: " + err.Error())
}
func PrintUsageLead() {
fmt.Println()
fmt.Println("Usage:")
fmt.Println()
}
func HasFlagsAfterArguments(command *flag.FlagSet) bool {
for i := 0; i!=command.NArg(); i++ {
arg := command.Arg(i)
if strings.HasPrefix(arg, "--") {
fmt.Println()
fmt.Println("Error: unexpected flag " + arg + " appearing after arguments. Put all flags before arguments.")
return true
}
}
return false
}
func main() {
// Subcommands without flags
versionCommand := flag.NewFlagSet("version", flag.ContinueOnError)
helpCommand := flag.NewFlagSet("help", flag.ContinueOnError)
// Subcommands with flags
releasesCommand := flag.NewFlagSet("releases", flag.ContinueOnError)
allReleases := releasesCommand.Bool("all", false, "List all releases.")
installCommand := flag.NewFlagSet("install", flag.ContinueOnError)
installSkipArchive := installCommand.Bool("skip-archive", false, "Do not create an archive before upgrading.")
installVerbose := installCommand.Bool("verbose", false, "Print additional detail.")
installUserlibs := installCommand.Bool("overwrite", false, "Install Strongback and 3rd party JARs as WPILib user libraries.")
installDepsCommand := flag.NewFlagSet("install-deps", flag.ContinueOnError)
installDepsVerbose := installDepsCommand.Bool("verbose", false, "Print additional detail.")
installDepsUserlibs := installDepsCommand.Bool("overwrite", false, "Install Strongback and 3rd party JARs as WPILib user libraries.")
uninstallCommand := flag.NewFlagSet("uninstall", flag.ContinueOnError)
uninstallSkipArchive := uninstallCommand.Bool("skip-archive", false, "Do not create an archive before removing.")
uninstallVerbose := uninstallCommand.Bool("verbose", false, "Print additional detail.")
uninstallYes := uninstallCommand.Bool("yes", false, "Do not prompt to remove.")
uninstallRemoveArchives := uninstallCommand.Bool("remove-archives", false, "Also remove all archives.")
decodeCommand := flag.NewFlagSet("decode", flag.ContinueOnError)
decodeVerbose := decodeCommand.Bool("verbose", false, "Print additional detail.")
newProjectCommand := flag.NewFlagSet("new-project", flag.ContinueOnError)
newProjectNoEclipse := newProjectCommand.Bool("no-eclipse", false, "Avoid generating Eclipse metadata for project.")
newProjectOverwrite := newProjectCommand.Bool("overwrite", false, "Overwrite existing files.")
newProjectDirectory := newProjectCommand.String("directory", "", "Directory.")
newProjectPackage := newProjectCommand.String("package", "", "Directory.")
// Verify that a subcommand has been provided
// os.Arg[0] is the main command
// os.Arg[1] will be the subcommand
if len(os.Args) < 2 {
PrintUsage()
os.Exit(1)
}
// Switch on the subcommand
// Parse the flags for appropriate FlagSet
// FlagSet.Parse() requires a set of arguments to parse as input
// os.Args[2:] will be all arguments starting after the subcommand at os.Args[1]
switch os.Args[1] {
case "install":
installCommand.SetOutput(bytes.NewBuffer([]byte{}))
if err := installCommand.Parse(os.Args[2:]); err != nil {
PrintUsageError(err)
PrintUsageLead()
PrintInstallUsage()
os.Exit(1)
}
if HasFlagsAfterArguments(installCommand) {
PrintUsageLead()
PrintInstallUsage()
os.Exit(1)
}
var desiredVersion string
if installCommand.NArg() > 0 {
desiredVersion = installCommand.Arg(0)
}
env := NewEnvironment()
env.InstallRelease(desiredVersion, *installSkipArchive, *installUserlibs, *installVerbose)
os.Exit(0)
case "install-deps":
installDepsCommand.SetOutput(bytes.NewBuffer([]byte{}))
if err := installDepsCommand.Parse(os.Args[2:]); err != nil {
PrintUsageError(err)
PrintUsageLead()
PrintInstallDepsUsage()
os.Exit(1)
}
if HasFlagsAfterArguments(installCommand) {
PrintUsageLead()
PrintInstallDepsUsage()
os.Exit(1)