/
repo.go
860 lines (745 loc) · 27 KB
/
repo.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
package modules
import (
"fmt"
"os"
"strings"
"github.com/c-bata/go-prompt"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/make-os/kit/crypto/ed25519"
modtypes "github.com/make-os/kit/modules/types"
"github.com/make-os/kit/node/services"
"github.com/make-os/kit/remote/repo"
rpctypes "github.com/make-os/kit/rpc/types"
"github.com/make-os/kit/types"
"github.com/make-os/kit/types/api"
"github.com/make-os/kit/types/constants"
"github.com/make-os/kit/types/core"
"github.com/make-os/kit/types/txns"
"github.com/make-os/kit/util"
"github.com/make-os/kit/util/crypto"
"github.com/make-os/kit/util/identifier"
"github.com/robertkrimen/otto"
"github.com/spf13/cast"
)
// RepoModule provides repository functionalities to JS environment
type RepoModule struct {
modtypes.ModuleCommon
logic core.Logic
service services.Service
repoSrv core.RemoteServer
}
// NewAttachableRepoModule creates an instance of RepoModule suitable in attach mode
func NewAttachableRepoModule(client rpctypes.Client) *RepoModule {
return &RepoModule{ModuleCommon: modtypes.ModuleCommon{Client: client}}
}
// NewRepoModule creates an instance of RepoModule
func NewRepoModule(service services.Service, repoSrv core.RemoteServer, logic core.Logic) *RepoModule {
return &RepoModule{service: service, logic: logic, repoSrv: repoSrv}
}
// methods are functions exposed in the special namespace of this module.
func (m *RepoModule) methods() []*modtypes.VMMember {
return []*modtypes.VMMember{
{Name: "create", Value: m.Create, Description: "Create a git repository on the network"},
{Name: "get", Value: m.Get, Description: "Get and return a repository"},
{Name: "update", Value: m.Update, Description: "Update a repository"},
{Name: "upsertOwner", Value: m.UpsertOwner, Description: "Create a proposal to add or update a repository owner"},
{Name: "vote", Value: m.Vote, Description: "Vote for or against a proposal"},
{Name: "depositPropFee", Value: m.DepositProposalFee, Description: "Deposit fees into a proposal"},
{Name: "addContributor", Value: m.AddContributor, Description: "Register one or more push keys as contributors"},
{Name: "track", Value: m.Track, Description: "Track one or more repositories"},
{Name: "untrack", Value: m.UnTrack, Description: "Untrack one or more repositories"},
{Name: "tracked", Value: m.GetTracked, Description: "Get a list of tracked repositories"},
{Name: "listByCreator", Value: m.GetReposCreatedByAddress, Description: "List repositories created by an address"},
// Repository query methods.
{Name: "ls", Value: m.ListPath, Description: "List files and directories of a repository"},
{Name: "readFileLines", Value: m.ReadFileLines, Description: "Get the lines of a file in a repository"},
{Name: "readFile", Value: m.ReadFile, Description: "Get the string content of a file in a repository"},
{Name: "getBranches", Value: m.GetBranches, Description: "Get a list of branches in a repository"},
{Name: "getLatestCommit", Value: m.GetLatestBranchCommit, Description: "Get the latest commit of a branch in a repository"},
{Name: "getCommits", Value: m.GetCommits, Description: "Get a list of commits in a branch of a repository"},
{Name: "getCommit", Value: m.GetCommit, Description: "Get a commit"},
{Name: "getAncestors", Value: m.GetCommitAncestors, Description: "Get ancestors of a commit in a repository"},
{Name: "countCommits", Value: m.CountCommits, Description: "Get a branch/reference commit count"},
{Name: "getDiffOfCommitAndParents", Value: m.GetParentsAndCommitDiff, Description: "Get the diff output of a commit and its parent(s)"},
}
}
// globals are functions exposed in the VM's global namespace
func (m *RepoModule) globals() []*modtypes.VMMember {
return []*modtypes.VMMember{}
}
// ConfigureVM configures the JS context and return
// any number of console prompt suggestions
func (m *RepoModule) ConfigureVM(vm *otto.Otto) prompt.Completer {
// Register the main namespace
obj := map[string]interface{}{}
util.VMSet(vm, constants.NamespaceRepo, obj)
for _, f := range m.methods() {
obj[f.Name] = f.Value
funcFullName := fmt.Sprintf("%s.%s", constants.NamespaceRepo, f.Name)
m.Suggestions = append(m.Suggestions, prompt.Suggest{Text: funcFullName, Description: f.Description})
}
// Register global functions
for _, f := range m.globals() {
vm.Set(f.Name, f.Value)
m.Suggestions = append(m.Suggestions, prompt.Suggest{Text: f.Name, Description: f.Description})
}
return m.Completer
}
// Create registers a git repository on the network
//
// params <map>
// - name <string>: The name of the namespace
// - value <string>: The amount to pay for initial resources
// - nonce <number|string>: The senders next account nonce
// - fee <number|string>: The transaction fee to pay
// - timestamp <number>: The unix timestamp
// - config <object>: The repo configuration
// - sig <String>: The transaction signature
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN object <map>
// - hash <string>: The transaction hash
// - address <string: The address of the repository
func (m *RepoModule) Create(params map[string]interface{}, options ...interface{}) util.Map {
var tx = txns.NewBareTxRepoCreate()
if err := tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
retPayload, signingKey := finalizeTx(tx, m.logic, m.Client, options...)
if retPayload {
return tx.ToMap()
}
if m.IsAttached() {
resp, err := m.Client.Repo().Create(&api.BodyCreateRepo{
Name: tx.Name,
Nonce: tx.Nonce,
Value: cast.ToFloat64(tx.Value.String()),
Fee: cast.ToFloat64(tx.Fee.String()),
Config: tx.Config.ToMap(),
SigningKey: ed25519.NewKeyFromPrivKey(signingKey),
})
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
"address": fmt.Sprintf("r/%s", tx.Name),
}
}
// UpsertOwner creates a proposal to add or update a repository owner
//
// params <map>
// - id <string>: A unique proposal id
// - addresses <string>: A comma separated list of addresses
// - veto <bool>: The senders next account nonce
// - fee <number|string>: The transaction fee to pay
// - timestamp <number>: The unix timestamp
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN <map>: When payloadOnly is false
// - hash <string>: The transaction hash
func (m *RepoModule) UpsertOwner(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareRepoProposalUpsertOwner()
if err = tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
if retPayload, _ := finalizeTx(tx, m.logic, nil, options...); retPayload {
return tx.ToMap()
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// Vote sends a TxTypeRepoCreate transaction to create a git repository
//
// params <map>
// - id <string>: The proposal ID to vote on
// - name <string>: The name of the repository
// - vote <uint>: The vote choice (1) yes (0) no (2) vote no with veto (3) abstain
// - nonce <number|string>: The senders next account nonce
// - fee <number|string>: The transaction fee to pay
// - timestamp <number>: The unix timestamp
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN object <map>
// - hash <string>: The transaction hash
func (m *RepoModule) Vote(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareRepoProposalVote()
if err = tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
retPayload, signingKey := finalizeTx(tx, m.logic, m.Client, options...)
if retPayload {
return tx.ToMap()
}
if m.IsAttached() {
resp, err := m.Client.Repo().VoteProposal(&api.BodyRepoVote{
RepoName: tx.RepoName,
ProposalID: tx.ProposalID,
Vote: tx.Vote,
Nonce: tx.Nonce,
Fee: cast.ToFloat64(tx.Fee.String()),
SigningKey: ed25519.NewKeyFromPrivKey(signingKey),
})
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// Get finds and returns a repository.
//
// name: The name of the repository
//
// opts <map>: fetch options
// - opts.height: Query a specific block
// - opts.select: Provide a list of dot-notated fields to be returned.
//
// RETURN <state.Repository>
func (m *RepoModule) Get(name string, opts ...modtypes.GetOptions) util.Map {
var blockHeight uint64
var selectors []string
var err error
if len(opts) > 0 {
opt := opts[0]
selectors = opt.Select
if opt.Height != nil {
blockHeight, err = cast.ToUint64E(opt.Height)
if err != nil {
panic(se(400, StatusCodeInvalidParam, "opts.height", "unexpected type"))
}
}
}
if m.IsAttached() {
resp, err := m.Client.Repo().Get(name, &api.GetRepoOpts{
Height: blockHeight,
})
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
if identifier.IsFullNamespaceURI(name) {
nsName := identifier.GetNamespace(name)
if nsName == identifier.NativeNamespaceRepoChar {
name = identifier.GetDomain(name)
} else {
ns := m.logic.NamespaceKeeper().Get(crypto.MakeNamespaceHash(nsName))
if ns.IsNil() {
panic(se(404, StatusCodeInvalidParam, "name", "namespace not found"))
}
name = ns.Domains.Get(identifier.GetDomain(name))
if name == "" {
panic(se(404, StatusCodeInvalidParam, "name", "namespace domain not found"))
}
if !strings.HasPrefix(name, identifier.NativeNamespaceRepo) {
panic(se(404, StatusCodeInvalidParam, "name", "namespace domain target is not a repository"))
}
name = identifier.GetDomain(name)
}
}
r := m.logic.RepoKeeper().Get(name, blockHeight)
if r.IsEmpty() {
panic(se(404, StatusCodeRepoNotFound, "name", types.ErrRepoNotFound.Error()))
}
if len(selectors) > 0 {
selected, err := Select(util.MustToJSON(r), selectors...)
if err != nil {
panic(se(400, StatusCodeInvalidParam, "select", err.Error()))
}
return selected
}
return util.ToMap(r)
}
// Update creates a proposal to update a repository
//
// params <map>
// - name <string>: The name of the repository
// - id <string>: A unique proposal ID
// - value <string|number>: The proposal fee
// - config <map[string]string>: The updated repository config
// - nonce <number|string>: The senders next account nonce
// - fee <number|string>: The transaction fee to pay
// - timestamp <number>: The unix timestamp
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN object <map>
// - hash <string>: The transaction hash
func (m *RepoModule) Update(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareRepoProposalUpdate()
if err = tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
if retPayload, _ := finalizeTx(tx, m.logic, nil, options...); retPayload {
return tx.ToMap()
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// DepositProposalFee creates a transaction to deposit a fee to a proposal
//
// params <map>
// - params.name <string>: The name of the repository
// - params.id <string>: A unique proposal ID
// - params.value <string|number>: The amount to add
// - params.nonce <number|string>: The senders next account nonce
// - params.fee <number|string>: The transaction fee to pay
// - params.timestamp <number>: The unix timestamp
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN object <map>
// - hash <string>: The transaction hash
func (m *RepoModule) DepositProposalFee(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareRepoProposalFeeSend()
if err = tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
if retPayload, _ := finalizeTx(tx, m.logic, nil, options...); retPayload {
return tx.ToMap()
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// AddContributor creates a proposal to register one or more push keys
//
// params <map>
// - name <string>: The name of the repository
// - id <string>: A unique proposal ID
// - ids <string|[]string>: A list or comma separated list of push key IDs to add
// - policies <[]map[string]interface{}>: A list of policies
// - sub <string>: The policy's subject
// - obj <string>: The policy's object
// - act <string>: The policy's action
// - value <string|number>: The proposal fee to pay
// - nonce <number|string>: The senders next account nonce
// - fee <number|string>: The transaction fee to pay
// - timestamp <number>: The unix timestamp
// - namespace <string>: A namespace to also register the key to
// - namespaceOnly <string>: Like namespace but key will not be registered to the repo.
//
// options <[]interface{}>
// - [0] key <string>: The signer's private key
// - [1] payloadOnly <bool>: When true, returns the payload only, without sending the tx.
//
// RETURN object <map>
// - hash <string>: The transaction hash
func (m *RepoModule) AddContributor(params map[string]interface{}, options ...interface{}) util.Map {
var err error
var tx = txns.NewBareRepoProposalRegisterPushKey()
if err = tx.FromMap(params); err != nil {
panic(se(400, StatusCodeInvalidParam, "params", err.Error()))
}
retPayload, signingKey := finalizeTx(tx, m.logic, m.Client, options...)
if retPayload {
return tx.ToMap()
}
if m.IsAttached() {
resp, err := m.Client.Repo().AddContributors(&api.BodyAddRepoContribs{
RepoName: tx.RepoName,
ProposalID: tx.ID,
PushKeys: tx.PushKeys,
FeeCap: cast.ToFloat64(tx.FeeCap.String()),
FeeMode: cast.ToInt(tx.FeeMode),
Nonce: tx.Nonce,
Namespace: tx.Namespace,
NamespaceOnly: tx.NamespaceOnly,
Policies: tx.Policies,
Value: cast.ToFloat64(tx.Value.String()),
Fee: cast.ToFloat64(tx.Fee.String()),
SigningKey: ed25519.NewKeyFromPrivKey(signingKey),
})
if err != nil {
panic(err)
}
return util.ToMap(resp)
}
hash, err := m.logic.GetMempoolReactor().AddTx(tx)
if err != nil {
panic(se(400, StatusCodeMempoolAddFail, "", err.Error()))
}
return map[string]interface{}{
"hash": hash,
}
}
// Track adds a repository to the track list.
// - names: A comma-separated list of repository or namespace names.
func (m *RepoModule) Track(names string, height ...uint64) {
if err := m.logic.RepoSyncInfoKeeper().Track(names, height...); err != nil {
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
}
// UnTrack removes a repository from the track list.
// - names: A comma-separated list of repository or namespace names.
func (m *RepoModule) UnTrack(names string) {
if err := m.logic.RepoSyncInfoKeeper().UnTrack(names); err != nil {
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
}
// GetTracked returns the tracked repositories
func (m *RepoModule) GetTracked() util.Map {
return util.ToJSONMap(m.logic.RepoSyncInfoKeeper().Tracked())
}
// GetReposCreatedByAddress returns names of repos created by an address
func (m *RepoModule) GetReposCreatedByAddress(address string) []string {
bz, err := ed25519.DecodeAddr(address)
if err != nil {
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
repos, err := m.logic.RepoKeeper().GetReposCreatedByAddress(bz[:])
if err != nil {
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return repos
}
// ListPath returns a list of entries in a repository's path
// - name: The name of the target repository.
// - path: The file or directory path to list
// - revision: The revision that will be queried (default: HEAD).
func (m *RepoModule) ListPath(name, path string, revision ...string) []util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
if strings.HasPrefix(path, "."+string(os.PathSeparator)) {
path = path[2:]
}
var rev = "HEAD"
if len(revision) > 0 {
rev = revision[0]
}
items, err := r.ListPath(rev, path)
if err != nil {
if err == plumbing.ErrReferenceNotFound {
return []util.Map{}
}
if err == repo.ErrPathNotFound {
panic(se(404, StatusCodePathNotFound, "path", err.Error()))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.StructSliceToMap(items)
}
// ReadFileLines returns the lines of a file in a repository.
// - name: The name of the target repository.
// - filePath: The file path.
// - revision: The revision that will be queried (default: HEAD).
func (m *RepoModule) ReadFileLines(name, filePath string, revision ...string) []string {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if filePath == "" {
panic(se(400, StatusCodeInvalidParam, "file", "file path is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
if strings.HasPrefix(filePath, "."+string(os.PathSeparator)) {
filePath = filePath[2:]
}
var rev = "HEAD"
if len(revision) > 0 {
rev = revision[0]
}
lines, err := r.GetFileLines(rev, filePath)
if err != nil {
if err == repo.ErrPathNotFound {
panic(se(404, StatusCodePathNotFound, "file", err.Error()))
}
if err == repo.ErrPathNotAFile {
panic(se(400, StatusCodePathNotAFile, "file", err.Error()))
}
panic(se(500, StatusCodeServerErr, "file", err.Error()))
}
return lines
}
// ReadFile returns the string content of a file in a repository.
// - name: The name of the target repository.
// - filePath: The file path.
// - revision: The revision that will be queried (default: HEAD).
func (m *RepoModule) ReadFile(name, filePath string, revision ...string) string {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if filePath == "" {
panic(se(400, StatusCodeInvalidParam, "file", "file path is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
if strings.HasPrefix(filePath, "."+string(os.PathSeparator)) {
filePath = filePath[2:]
}
var rev = "HEAD"
if len(revision) > 0 {
rev = revision[0]
}
str, err := r.GetFile(rev, filePath)
if err != nil {
if err == repo.ErrPathNotFound {
panic(se(404, StatusCodePathNotFound, "file", err.Error()))
}
if err == repo.ErrPathNotAFile {
panic(se(400, StatusCodePathNotAFile, "file", err.Error()))
}
panic(se(500, StatusCodeServerErr, "file", err.Error()))
}
return str
}
// GetBranches returns the list of branches
// - name: The name of the target repository.
func (m *RepoModule) GetBranches(name string) []string {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
branches, err := r.GetBranches()
if err != nil {
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
for i, branch := range branches {
branches[i] = "refs/heads/" + branch
}
return branches
}
// GetLatestBranchCommit returns the latest commit of a branch in a repository.
// - name: The name of the target repository.
// - branch: The name of the branch.
func (m *RepoModule) GetLatestBranchCommit(name, branch string) util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if branch == "" {
panic(se(400, StatusCodeInvalidParam, "branch", "branch name is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
c, err := r.GetLatestCommit(branch)
if err != nil {
if err == plumbing.ErrReferenceNotFound {
panic(se(404, StatusCodeBranchNotFound, "branch", "branch does not exist"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.ToMap(c)
}
// GetCommits returns commits in a branch.
// - name: The name of the repository.
// - branch: The target branch.
// - limit: The number of commit to return. 0 means all.
func (m *RepoModule) GetCommits(name, branch string, limit ...int) []util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if branch == "" {
panic(se(400, StatusCodeInvalidParam, "branch", "branch name is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
limit_ := 0
if len(limit) > 0 {
limit_ = limit[0]
}
commits, err := r.GetCommits(branch, limit_)
if err != nil {
if err == plumbing.ErrReferenceNotFound {
panic(se(404, StatusCodeBranchNotFound, "branch", "branch does not exist"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.StructSliceToMap(commits)
}
// GetCommit gets a commit.
// - name: The name of the repository
// - hash: The commit hash.
func (m *RepoModule) GetCommit(name, hash string) util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if hash == "" {
panic(se(400, StatusCodeInvalidParam, "hash", "commit hash is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
commit, err := r.GetCommit(hash)
if err != nil {
if err == plumbing.ErrObjectNotFound {
panic(se(404, StatusCodeCommitNotFound, "hash", "commit does not exist"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.ToMap(commit)
}
// CountCommits returns the number commits in a branch/reference.
// - name: The name of the target repository.
// - ref: The target branch or reference.
func (m *RepoModule) CountCommits(name, ref string) int {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if ref == "" {
panic(se(400, StatusCodeInvalidParam, "branch", "branch name is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
count, err := r.NumCommits(ref, false)
if err != nil {
if err == plumbing.ErrReferenceNotFound {
panic(se(404, StatusCodeBranchNotFound, "branch", "branch does not exist"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return count
}
// GetCommitAncestors returns ancestors of a commit with the given hash.
// - commitHash: The hash of the commit.
// - limit: The number of commit to return. 0 means all.
func (m *RepoModule) GetCommitAncestors(name, commitHash string, limit ...int) []util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if commitHash == "" {
panic(se(400, StatusCodeInvalidParam, "commitHash", "commit hash is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
limit_ := 0
if len(limit) > 0 {
limit_ = limit[0]
}
commits, err := r.GetCommitAncestors(commitHash, limit_)
if err != nil {
if err == plumbing.ErrObjectNotFound {
panic(se(404, StatusCodeCommitNotFound, "commitHash", "commit does not exist"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.StructSliceToMap(commits)
}
// GetParentsAndCommitDiff gets the diff output between a commit and its parent(s).
// - name: The name of the target repository.
// - commitHash: The hash of the commit.
func (m *RepoModule) GetParentsAndCommitDiff(name string, commitHash string) util.Map {
if name == "" {
panic(se(400, StatusCodeInvalidParam, "name", "repo name is required"))
}
if commitHash == "" {
panic(se(400, StatusCodeInvalidParam, "commitHash", "commit hash is required"))
}
repoPath := m.logic.Config().GetRepoPath(name)
r, err := repo.GetWithGitModule(m.logic.Config().Node.GitBinPath, repoPath)
if err != nil {
if err == git.ErrRepositoryNotExists {
panic(se(404, StatusCodeInvalidParam, "name", err.Error()))
}
panic(se(400, StatusCodeInvalidParam, "name", err.Error()))
}
res, err := r.GetParentAndChildCommitDiff(commitHash)
if err != nil {
if err == plumbing.ErrObjectNotFound {
panic(se(404, StatusCodeCommitNotFound, "commitHash", "commit not found"))
}
panic(se(500, StatusCodeServerErr, "", err.Error()))
}
return util.ToMap(res)
}