Debian Codegraph @

options.go

raw
1 package git
2
3 import (
4 "errors"
5 "fmt"
6 "regexp"
7 "strings"
8 "time"
9
10 "github.com/ProtonMail/go-crypto/openpgp"
11
12 "github.com/go-git/go-git/v5/config"
13 "github.com/go-git/go-git/v5/plumbing"
14 formatcfg "github.com/go-git/go-git/v5/plumbing/format/config"
15 "github.com/go-git/go-git/v5/plumbing/object"
16 "github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
17 "github.com/go-git/go-git/v5/plumbing/transport"
18 )
19
20 // SubmoduleRescursivity defines how depth will affect any submodule recursive
21 // operation.
22 type SubmoduleRescursivity uint
23
24 const (
25 // DefaultRemoteName name of the default Remote, just like git command.
26 DefaultRemoteName = "origin"
27
28 // NoRecurseSubmodules disables the recursion for a submodule operation.
29 NoRecurseSubmodules SubmoduleRescursivity = 0
30 // DefaultSubmoduleRecursionDepth allow recursion in a submodule operation.
31 DefaultSubmoduleRecursionDepth SubmoduleRescursivity = 10
32 )
33
34 var (
35 ErrMissingURL = errors.New("URL field is required")
36 )
37
38 // CloneOptions describes how a clone should be performed.
39 type CloneOptions struct {
40 // The (possibly remote) repository URL to clone from.
41 URL string
42 // Auth credentials, if required, to use with the remote repository.
43 Auth transport.AuthMethod
44 // Name of the remote to be added, by default `origin`.
45 RemoteName string
46 // Remote branch to clone.
47 ReferenceName plumbing.ReferenceName
48 // Fetch only ReferenceName if true.
49 SingleBranch bool
50 // Mirror clones the repository as a mirror.
51 //
52 // Compared to a bare clone, mirror not only maps local branches of the
53 // source to local branches of the target, it maps all refs (including
54 // remote-tracking branches, notes etc.) and sets up a refspec configuration
55 // such that all these refs are overwritten by a git remote update in the
56 // target repository.
57 Mirror bool
58 // No checkout of HEAD after clone if true.
59 NoCheckout bool
60 // Limit fetching to the specified number of commits.
61 Depth int
62 // RecurseSubmodules after the clone is created, initialize all submodules
63 // within, using their default settings. This option is ignored if the
64 // cloned repository does not have a worktree.
65 RecurseSubmodules SubmoduleRescursivity
66 // ShallowSubmodules limit cloning submodules to the 1 level of depth.
67 // It matches the git command --shallow-submodules.
68 ShallowSubmodules bool
69 // Progress is where the human readable information sent by the server is
70 // stored, if nil nothing is stored and the capability (if supported)
71 // no-progress, is sent to the server to avoid send this information.
72 Progress sideband.Progress
73 // Tags describe how the tags will be fetched from the remote repository,
74 // by default is AllTags.
75 Tags TagMode
76 // InsecureSkipTLS skips SSL verification if protocol is HTTPS.
77 InsecureSkipTLS bool
78 // ClientCert is the client certificate to use for mutual TLS authentication
79 // over the HTTPS protocol.
80 ClientCert []byte
81 // ClientKey is the client key to use for mutual TLS authentication over
82 // the HTTPS protocol.
83 ClientKey []byte
84 // CABundle specifies an additional CA bundle to use together with the
85 // system cert pool.
86 CABundle []byte
87 // ProxyOptions provides info required for connecting to a proxy.
88 ProxyOptions transport.ProxyOptions
89 // When the repository to clone is on the local machine, instead of
90 // using hard links, automatically setup .git/objects/info/alternates
91 // to share the objects with the source repository.
92 // The resulting repository starts out without any object of its own.
93 // NOTE: this is a possibly dangerous operation; do not use it unless
94 // you understand what it does.
95 //
96 // [Reference]: https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---shared
97 Shared bool
98 }
99
100 // MergeOptions describes how a merge should be performed.
101 type MergeOptions struct {
102 // Strategy defines the merge strategy to be used.
103 Strategy MergeStrategy
104 }
105
106 // MergeStrategy represents the different types of merge strategies.
107 type MergeStrategy int8
108
109 const (
110 // FastForwardMerge represents a Git merge strategy where the current
111 // branch can be simply updated to point to the HEAD of the branch being
112 // merged. This is only possible if the history of the branch being merged
113 // is a linear descendant of the current branch, with no conflicting commits.
114 //
115 // This is the default option.
116 FastForwardMerge MergeStrategy = iota
117 )
118
119 // Validate validates the fields and sets the default values.
120 func (o *CloneOptions) Validate() error {
121 if o.URL == "" {
122 return ErrMissingURL
123 }
124
125 if o.RemoteName == "" {
126 o.RemoteName = DefaultRemoteName
127 }
128
129 if o.ReferenceName == "" {
130 o.ReferenceName = plumbing.HEAD
131 }
132
133 if o.Tags == InvalidTagMode {
134 o.Tags = AllTags
135 }
136
137 return nil
138 }
139
140 // PullOptions describes how a pull should be performed.
141 type PullOptions struct {
142 // Name of the remote to be pulled. If empty, uses the default.
143 RemoteName string
144 // RemoteURL overrides the remote repo address with a custom URL
145 RemoteURL string
146 // Remote branch to clone. If empty, uses HEAD.
147 ReferenceName plumbing.ReferenceName
148 // Fetch only ReferenceName if true.
149 SingleBranch bool
150 // Limit fetching to the specified number of commits.
151 Depth int
152 // Auth credentials, if required, to use with the remote repository.
153 Auth transport.AuthMethod
154 // RecurseSubmodules controls if new commits of all populated submodules
155 // should be fetched too.
156 RecurseSubmodules SubmoduleRescursivity
157 // Progress is where the human readable information sent by the server is
158 // stored, if nil nothing is stored and the capability (if supported)
159 // no-progress, is sent to the server to avoid send this information.
160 Progress sideband.Progress
161 // Force allows the pull to update a local branch even when the remote
162 // branch does not descend from it.
163 Force bool
164 // InsecureSkipTLS skips SSL verification if protocol is HTTPS.
165 InsecureSkipTLS bool
166 // ClientCert is the client certificate to use for mutual TLS authentication
167 // over the HTTPS protocol.
168 ClientCert []byte
169 // ClientKey is the client key to use for mutual TLS authentication over
170 // the HTTPS protocol.
171 ClientKey []byte
172 // CABundle specifies an additional CA bundle to use together with the
173 // system cert pool.
174 CABundle []byte
175 // ProxyOptions provides info required for connecting to a proxy.
176 ProxyOptions transport.ProxyOptions
177 }
178
179 // Validate validates the fields and sets the default values.
180 func (o *PullOptions) Validate() error {
181 if o.RemoteName == "" {
182 o.RemoteName = DefaultRemoteName
183 }
184
185 if o.ReferenceName == "" {
186 o.ReferenceName = plumbing.HEAD
187 }
188
189 return nil
190 }
191
192 type TagMode int
193
194 const (
195 InvalidTagMode TagMode = iota
196 // TagFollowing any tag that points into the histories being fetched is also
197 // fetched. TagFollowing requires a server with `include-tag` capability
198 // in order to fetch the annotated tags objects.
199 TagFollowing
200 // AllTags fetch all tags from the remote (i.e., fetch remote tags
201 // refs/tags/* into local tags with the same name)
202 AllTags
203 // NoTags fetch no tags from the remote at all
204 NoTags
205 )
206
207 // FetchOptions describes how a fetch should be performed
208 type FetchOptions struct {
209 // Name of the remote to fetch from. Defaults to origin.
210 RemoteName string
211 // RemoteURL overrides the remote repo address with a custom URL
212 RemoteURL string
213 RefSpecs []config.RefSpec
214 // Depth limit fetching to the specified number of commits from the tip of
215 // each remote branch history.
216 Depth int
217 // Auth credentials, if required, to use with the remote repository.
218 Auth transport.AuthMethod
219 // Progress is where the human readable information sent by the server is
220 // stored, if nil nothing is stored and the capability (if supported)
221 // no-progress, is sent to the server to avoid send this information.
222 Progress sideband.Progress
223 // Tags describe how the tags will be fetched from the remote repository,
224 // by default is TagFollowing.
225 Tags TagMode
226 // Force allows the fetch to update a local branch even when the remote
227 // branch does not descend from it.
228 Force bool
229 // InsecureSkipTLS skips SSL verification if protocol is HTTPS.
230 InsecureSkipTLS bool
231 // ClientCert is the client certificate to use for mutual TLS authentication
232 // over the HTTPS protocol.
233 ClientCert []byte
234 // ClientKey is the client key to use for mutual TLS authentication over
235 // the HTTPS protocol.
236 ClientKey []byte
237 // CABundle specifies an additional CA bundle to use together with the
238 // system cert pool.
239 CABundle []byte
240 // ProxyOptions provides info required for connecting to a proxy.
241 ProxyOptions transport.ProxyOptions
242 // Prune specify that local refs that match given RefSpecs and that do
243 // not exist remotely will be removed.
244 Prune bool
245 }
246
247 // Validate validates the fields and sets the default values.
248 func (o *FetchOptions) Validate() error {
249 if o.RemoteName == "" {
250 o.RemoteName = DefaultRemoteName
251 }
252
253 if o.Tags == InvalidTagMode {
254 o.Tags = TagFollowing
255 }
256
257 for _, r := range o.RefSpecs {
258 if err := r.Validate(); err != nil {
259 return err
260 }
261 }
262
263 return nil
264 }
265
266 // PushOptions describes how a push should be performed.
267 type PushOptions struct {
268 // RemoteName is the name of the remote to be pushed to.
269 RemoteName string
270 // RemoteURL overrides the remote repo address with a custom URL
271 RemoteURL string
272 // RefSpecs specify what destination ref to update with what source object.
273 //
274 // The format of a <refspec> parameter is an optional plus +, followed by
275 // the source object <src>, followed by a colon :, followed by the destination ref <dst>.
276 // The <src> is often the name of the branch you would want to push, but it can be a SHA-1.
277 // The <dst> tells which ref on the remote side is updated with this push.
278 //
279 // A refspec with empty src can be used to delete a reference.
280 RefSpecs []config.RefSpec
281 // Auth credentials, if required, to use with the remote repository.
282 Auth transport.AuthMethod
283 // Progress is where the human readable information sent by the server is
284 // stored, if nil nothing is stored.
285 Progress sideband.Progress
286 // Prune specify that remote refs that match given RefSpecs and that do
287 // not exist locally will be removed.
288 Prune bool
289 // Force allows the push to update a remote branch even when the local
290 // branch does not descend from it.
291 Force bool
292 // InsecureSkipTLS skips SSL verification if protocol is HTTPS.
293 InsecureSkipTLS bool
294 // ClientCert is the client certificate to use for mutual TLS authentication
295 // over the HTTPS protocol.
296 ClientCert []byte
297 // ClientKey is the client key to use for mutual TLS authentication over
298 // the HTTPS protocol.
299 ClientKey []byte
300 // CABundle specifies an additional CA bundle to use together with the
301 // system cert pool.
302 CABundle []byte
303 // RequireRemoteRefs only allows a remote ref to be updated if its current
304 // value is the one specified here.
305 RequireRemoteRefs []config.RefSpec
306 // FollowTags will send any annotated tags with a commit target reachable from
307 // the refs already being pushed
308 FollowTags bool
309 // ForceWithLease allows a force push as long as the remote ref adheres to a "lease"
310 ForceWithLease *ForceWithLease
311 // PushOptions sets options to be transferred to the server during push.
312 Options map[string]string
313 // Atomic sets option to be an atomic push
314 Atomic bool
315 // ProxyOptions provides info required for connecting to a proxy.
316 ProxyOptions transport.ProxyOptions
317 }
318
319 // ForceWithLease sets fields on the lease
320 // If neither RefName nor Hash are set, ForceWithLease protects
321 // all refs in the refspec by ensuring the ref of the remote in the local repsitory
322 // matches the one in the ref advertisement.
323 type ForceWithLease struct {
324 // RefName, when set will protect the ref by ensuring it matches the
325 // hash in the ref advertisement.
326 RefName plumbing.ReferenceName
327 // Hash is the expected object id of RefName. The push will be rejected unless this
328 // matches the corresponding object id of RefName in the refs advertisement.
329 Hash plumbing.Hash
330 }
331
332 // Validate validates the fields and sets the default values.
333 func (o *PushOptions) Validate() error {
334 if o.RemoteName == "" {
335 o.RemoteName = DefaultRemoteName
336 }
337
338 if len(o.RefSpecs) == 0 {
339 o.RefSpecs = []config.RefSpec{
340 config.RefSpec(config.DefaultPushRefSpec),
341 }
342 }
343
344 for _, r := range o.RefSpecs {
345 if err := r.Validate(); err != nil {
346 return err
347 }
348 }
349
350 return nil
351 }
352
353 // SubmoduleUpdateOptions describes how a submodule update should be performed.
354 type SubmoduleUpdateOptions struct {
355 // Init, if true initializes the submodules recorded in the index.
356 Init bool
357 // NoFetch tell to the update command to not fetch new objects from the
358 // remote site.
359 NoFetch bool
360 // RecurseSubmodules the update is performed not only in the submodules of
361 // the current repository but also in any nested submodules inside those
362 // submodules (and so on). Until the SubmoduleRescursivity is reached.
363 RecurseSubmodules SubmoduleRescursivity
364 // Auth credentials, if required, to use with the remote repository.
365 Auth transport.AuthMethod
366 // Depth limit fetching to the specified number of commits from the tip of
367 // each remote branch history.
368 Depth int
369 }
370
371 var (
372 ErrBranchHashExclusive = errors.New("Branch and Hash are mutually exclusive")
373 ErrCreateRequiresBranch = errors.New("Branch is mandatory when Create is used")
374 )
375
376 // CheckoutOptions describes how a checkout operation should be performed.
377 type CheckoutOptions struct {
378 // Hash is the hash of a commit or tag to be checked out. If used, HEAD
379 // will be in detached mode. If Create is not used, Branch and Hash are
380 // mutually exclusive.
381 Hash plumbing.Hash
382 // Branch to be checked out, if Branch and Hash are empty is set to `master`.
383 Branch plumbing.ReferenceName
384 // Create a new branch named Branch and start it at Hash.
385 Create bool
386 // Force, if true when switching branches, proceed even if the index or the
387 // working tree differs from HEAD. This is used to throw away local changes
388 Force bool
389 // Keep, if true when switching branches, local changes (the index or the
390 // working tree changes) will be kept so that they can be committed to the
391 // target branch. Force and Keep are mutually exclusive, should not be both
392 // set to true.
393 Keep bool
394 // SparseCheckoutDirectories
395 SparseCheckoutDirectories []string
396 }
397
398 // Validate validates the fields and sets the default values.
399 func (o *CheckoutOptions) Validate() error {
400 if !o.Create && !o.Hash.IsZero() && o.Branch != "" {
401 return ErrBranchHashExclusive
402 }
403
404 if o.Create && o.Branch == "" {
405 return ErrCreateRequiresBranch
406 }
407
408 if o.Branch == "" {
409 o.Branch = plumbing.Master
410 }
411
412 return nil
413 }
414
415 // ResetMode defines the mode of a reset operation.
416 type ResetMode int8
417
418 const (
419 // MixedReset resets the index but not the working tree (i.e., the changed
420 // files are preserved but not marked for commit) and reports what has not
421 // been updated. This is the default action.
422 MixedReset ResetMode = iota
423 // HardReset resets the index and working tree. Any changes to tracked files
424 // in the working tree are discarded.
425 HardReset
426 // MergeReset resets the index and updates the files in the working tree
427 // that are different between Commit and HEAD, but keeps those which are
428 // different between the index and working tree (i.e. which have changes
429 // which have not been added).
430 //
431 // If a file that is different between Commit and the index has unstaged
432 // changes, reset is aborted.
433 MergeReset
434 // SoftReset does not touch the index file or the working tree at all (but
435 // resets the head to <commit>, just like all modes do). This leaves all
436 // your changed files "Changes to be committed", as git status would put it.
437 SoftReset
438 )
439
440 // ResetOptions describes how a reset operation should be performed.
441 type ResetOptions struct {
442 // Commit, if commit is present set the current branch head (HEAD) to it.
443 Commit plumbing.Hash
444 // Mode, form resets the current branch head to Commit and possibly updates
445 // the index (resetting it to the tree of Commit) and the working tree
446 // depending on Mode. If empty MixedReset is used.
447 Mode ResetMode
448 // Files, if not empty will constrain the reseting the index to only files
449 // specified in this list.
450 Files []string
451 }
452
453 // Validate validates the fields and sets the default values.
454 func (o *ResetOptions) Validate(r *Repository) error {
455 if o.Commit == plumbing.ZeroHash {
456 ref, err := r.Head()
457 if err != nil {
458 return err
459 }
460
461 o.Commit = ref.Hash()
462 } else {
463 _, err := r.CommitObject(o.Commit)
464 if err != nil {
465 return fmt.Errorf("invalid reset option: %w", err)
466 }
467 }
468
469 return nil
470 }
471
472 type LogOrder int8
473
474 const (
475 LogOrderDefault LogOrder = iota
476 LogOrderDFS
477 LogOrderDFSPost
478 LogOrderBSF
479 LogOrderCommitterTime
480 )
481
482 // LogOptions describes how a log action should be performed.
483 type LogOptions struct {
484 // When the From option is set the log will only contain commits
485 // reachable from it. If this option is not set, HEAD will be used as
486 // the default From.
487 From plumbing.Hash
488
489 // The default traversal algorithm is Depth-first search
490 // set Order=LogOrderCommitterTime for ordering by committer time (more compatible with `git log`)
491 // set Order=LogOrderBSF for Breadth-first search
492 Order LogOrder
493
494 // Show only those commits in which the specified file was inserted/updated.
495 // It is equivalent to running `git log -- <file-name>`.
496 // this field is kept for compatibility, it can be replaced with PathFilter
497 FileName *string
498
499 // Filter commits based on the path of files that are updated
500 // takes file path as argument and should return true if the file is desired
501 // It can be used to implement `git log -- <path>`
502 // either <path> is a file path, or directory path, or a regexp of file/directory path
503 PathFilter func(string) bool
504
505 // Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>.
506 // It is equivalent to running `git log --all`.
507 // If set on true, the From option will be ignored.
508 All bool
509
510 // Show commits more recent than a specific date.
511 // It is equivalent to running `git log --since <date>` or `git log --after <date>`.
512 Since *time.Time
513
514 // Show commits older than a specific date.
515 // It is equivalent to running `git log --until <date>` or `git log --before <date>`.
516 Until *time.Time
517 }
518
519 var (
520 ErrMissingAuthor = errors.New("author field is required")
521 )
522
523 // AddOptions describes how an `add` operation should be performed
524 type AddOptions struct {
525 // All equivalent to `git add -A`, update the index not only where the
526 // working tree has a file matching `Path` but also where the index already
527 // has an entry. This adds, modifies, and removes index entries to match the
528 // working tree. If no `Path` nor `Glob` is given when `All` option is
529 // used, all files in the entire working tree are updated.
530 All bool
531 // Path is the exact filepath to the file or directory to be added.
532 Path string
533 // Glob adds all paths, matching pattern, to the index. If pattern matches a
534 // directory path, all directory contents are added to the index recursively.
535 Glob string
536 // SkipStatus adds the path with no status check. This option is relevant only
537 // when the `Path` option is specified and does not apply when the `All` option is used.
538 // Notice that when passing an ignored path it will be added anyway.
539 // When true it can speed up adding files to the worktree in very large repositories.
540 SkipStatus bool
541 }
542
543 // Validate validates the fields and sets the default values.
544 func (o *AddOptions) Validate(r *Repository) error {
545 if o.Path != "" && o.Glob != "" {
546 return fmt.Errorf("fields Path and Glob are mutual exclusive")
547 }
548
549 return nil
550 }
551
552 // CommitOptions describes how a commit operation should be performed.
553 type CommitOptions struct {
554 // All automatically stage files that have been modified and deleted, but
555 // new files you have not told Git about are not affected.
556 All bool
557 // AllowEmptyCommits enable empty commits to be created. An empty commit
558 // is when no changes to the tree were made, but a new commit message is
559 // provided. The default behavior is false, which results in ErrEmptyCommit.
560 AllowEmptyCommits bool
561 // Author is the author's signature of the commit. If Author is empty the
562 // Name and Email is read from the config, and time.Now it's used as When.
563 Author *object.Signature
564 // Committer is the committer's signature of the commit. If Committer is
565 // nil the Author signature is used.
566 Committer *object.Signature
567 // Parents are the parents commits for the new commit, by default when
568 // len(Parents) is zero, the hash of HEAD reference is used.
569 Parents []plumbing.Hash
570 // SignKey denotes a key to sign the commit with. A nil value here means the
571 // commit will not be signed. The private key must be present and already
572 // decrypted.
573 SignKey *openpgp.Entity
574 // Signer denotes a cryptographic signer to sign the commit with.
575 // A nil value here means the commit will not be signed.
576 // Takes precedence over SignKey.
577 Signer Signer
578 // Amend will create a new commit object and replace the commit that HEAD currently
579 // points to. Cannot be used with All nor Parents.
580 Amend bool
581 }
582
583 // Validate validates the fields and sets the default values.
584 func (o *CommitOptions) Validate(r *Repository) error {
585 if o.All && o.Amend {
586 return errors.New("all and amend cannot be used together")
587 }
588
589 if o.Amend && len(o.Parents) > 0 {
590 return errors.New("parents cannot be used with amend")
591 }
592
593 if o.Author == nil {
594 if err := o.loadConfigAuthorAndCommitter(r); err != nil {
595 return err
596 }
597 }
598
599 if o.Committer == nil {
600 o.Committer = o.Author
601 }
602
603 if len(o.Parents) == 0 {
604 head, err := r.Head()
605 if err != nil && err != plumbing.ErrReferenceNotFound {
606 return err
607 }
608
609 if head != nil {
610 o.Parents = []plumbing.Hash{head.Hash()}
611 }
612 }
613
614 return nil
615 }
616
617 func (o *CommitOptions) loadConfigAuthorAndCommitter(r *Repository) error {
618 cfg, err := r.ConfigScoped(config.SystemScope)
619 if err != nil {
620 return err
621 }
622
623 if o.Author == nil && cfg.Author.Email != "" && cfg.Author.Name != "" {
624 o.Author = &object.Signature{
625 Name: cfg.Author.Name,
626 Email: cfg.Author.Email,
627 When: time.Now(),
628 }
629 }
630
631 if o.Committer == nil && cfg.Committer.Email != "" && cfg.Committer.Name != "" {
632 o.Committer = &object.Signature{
633 Name: cfg.Committer.Name,
634 Email: cfg.Committer.Email,
635 When: time.Now(),
636 }
637 }
638
639 if o.Author == nil && cfg.User.Email != "" && cfg.User.Name != "" {
640 o.Author = &object.Signature{
641 Name: cfg.User.Name,
642 Email: cfg.User.Email,
643 When: time.Now(),
644 }
645 }
646
647 if o.Author == nil {
648 return ErrMissingAuthor
649 }
650
651 return nil
652 }
653
654 var (
655 ErrMissingName = errors.New("name field is required")
656 ErrMissingTagger = errors.New("tagger field is required")
657 ErrMissingMessage = errors.New("message field is required")
658 )
659
660 // CreateTagOptions describes how a tag object should be created.
661 type CreateTagOptions struct {
662 // Tagger defines the signature of the tag creator. If Tagger is empty the
663 // Name and Email is read from the config, and time.Now it's used as When.
664 Tagger *object.Signature
665 // Message defines the annotation of the tag. It is canonicalized during
666 // validation into the format expected by git - no leading whitespace and
667 // ending in a newline.
668 Message string
669 // SignKey denotes a key to sign the tag with. A nil value here means the tag
670 // will not be signed. The private key must be present and already decrypted.
671 SignKey *openpgp.Entity
672 }
673
674 // Validate validates the fields and sets the default values.
675 func (o *CreateTagOptions) Validate(r *Repository, hash plumbing.Hash) error {
676 if o.Tagger == nil {
677 if err := o.loadConfigTagger(r); err != nil {
678 return err
679 }
680 }
681
682 if o.Message == "" {
683 return ErrMissingMessage
684 }
685
686 // Canonicalize the message into the expected message format.
687 o.Message = strings.TrimSpace(o.Message) + "\n"
688
689 return nil
690 }
691
692 func (o *CreateTagOptions) loadConfigTagger(r *Repository) error {
693 cfg, err := r.ConfigScoped(config.SystemScope)
694 if err != nil {
695 return err
696 }
697
698 if o.Tagger == nil && cfg.Author.Email != "" && cfg.Author.Name != "" {
699 o.Tagger = &object.Signature{
700 Name: cfg.Author.Name,
701 Email: cfg.Author.Email,
702 When: time.Now(),
703 }
704 }
705
706 if o.Tagger == nil && cfg.User.Email != "" && cfg.User.Name != "" {
707 o.Tagger = &object.Signature{
708 Name: cfg.User.Name,
709 Email: cfg.User.Email,
710 When: time.Now(),
711 }
712 }
713
714 if o.Tagger == nil {
715 return ErrMissingTagger
716 }
717
718 return nil
719 }
720
721 // ListOptions describes how a remote list should be performed.
722 type ListOptions struct {
723 // Auth credentials, if required, to use with the remote repository.
724 Auth transport.AuthMethod
725 // InsecureSkipTLS skips SSL verification if protocol is HTTPS.
726 InsecureSkipTLS bool
727 // ClientCert is the client certificate to use for mutual TLS authentication
728 // over the HTTPS protocol.
729 ClientCert []byte
730 // ClientKey is the client key to use for mutual TLS authentication over
731 // the HTTPS protocol.
732 ClientKey []byte
733 // CABundle specifies an additional CA bundle to use together with the
734 // system cert pool.
735 CABundle []byte
736 // PeelingOption defines how peeled objects are handled during a
737 // remote list.
738 PeelingOption PeelingOption
739 // ProxyOptions provides info required for connecting to a proxy.
740 ProxyOptions transport.ProxyOptions
741 // Timeout specifies the timeout in seconds for list operations
742 Timeout int
743 }
744
745 // PeelingOption represents the different ways to handle peeled references.
746 //
747 // Peeled references represent the underlying object of an annotated
748 // (or signed) tag. Refer to upstream documentation for more info:
749 // https://github.com/git/git/blob/master/Documentation/technical/reftable.txt
750 type PeelingOption uint8
751
752 const (
753 // IgnorePeeled ignores all peeled reference names. This is the default behavior.
754 IgnorePeeled PeelingOption = 0
755 // OnlyPeeled returns only peeled reference names.
756 OnlyPeeled PeelingOption = 1
757 // AppendPeeled appends peeled reference names to the reference list.
758 AppendPeeled PeelingOption = 2
759 )
760
761 // CleanOptions describes how a clean should be performed.
762 type CleanOptions struct {
763 Dir bool
764 }
765
766 // GrepOptions describes how a grep should be performed.
767 type GrepOptions struct {
768 // Patterns are compiled Regexp objects to be matched.
769 Patterns []*regexp.Regexp
770 // InvertMatch selects non-matching lines.
771 InvertMatch bool
772 // CommitHash is the hash of the commit from which worktree should be derived.
773 CommitHash plumbing.Hash
774 // ReferenceName is the branch or tag name from which worktree should be derived.
775 ReferenceName plumbing.ReferenceName
776 // PathSpecs are compiled Regexp objects of pathspec to use in the matching.
777 PathSpecs []*regexp.Regexp
778 }
779
780 var (
781 ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed")
782 )
783
784 // Validate validates the fields and sets the default values.
785 //
786 // TODO: deprecate in favor of Validate(r *Repository) in v6.
787 func (o *GrepOptions) Validate(w *Worktree) error {
788 return o.validate(w.r)
789 }
790
791 func (o *GrepOptions) validate(r *Repository) error {
792 if !o.CommitHash.IsZero() && o.ReferenceName != "" {
793 return ErrHashOrReference
794 }
795
796 // If none of CommitHash and ReferenceName are provided, set commit hash of
797 // the repository's head.
798 if o.CommitHash.IsZero() && o.ReferenceName == "" {
799 ref, err := r.Head()
800 if err != nil {
801 return err
802 }
803 o.CommitHash = ref.Hash()
804 }
805
806 return nil
807 }
808
809 // PlainOpenOptions describes how opening a plain repository should be
810 // performed.
811 type PlainOpenOptions struct {
812 // DetectDotGit defines whether parent directories should be
813 // walked until a .git directory or file is found.
814 DetectDotGit bool
815 // Enable .git/commondir support (see https://git-scm.com/docs/gitrepository-layout#Documentation/gitrepository-layout.txt).
816 // NOTE: This option will only work with the filesystem storage.
817 EnableDotGitCommonDir bool
818 }
819
820 // Validate validates the fields and sets the default values.
821 func (o *PlainOpenOptions) Validate() error { return nil }
822
823 type PlainInitOptions struct {
824 InitOptions
825 // Determines if the repository will have a worktree (non-bare) or not (bare).
826 Bare bool
827 ObjectFormat formatcfg.ObjectFormat
828 }
829
830 // Validate validates the fields and sets the default values.
831 func (o *PlainInitOptions) Validate() error { return nil }
832
833 var (
834 ErrNoRestorePaths = errors.New("you must specify path(s) to restore")
835 )
836
837 // RestoreOptions describes how a restore should be performed.
838 type RestoreOptions struct {
839 // Marks to restore the content in the index
840 Staged bool
841 // Marks to restore the content of the working tree
842 Worktree bool
843 // List of file paths that will be restored
844 Files []string
845 }
846
847 // Validate validates the fields and sets the default values.
848 func (o *RestoreOptions) Validate() error {
849 if len(o.Files) == 0 {
850 return ErrNoRestorePaths
851 }
852
853 return nil
854 }