You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

options.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. package git
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "time"
  7. "github.com/go-git/go-git/v5/config"
  8. "github.com/go-git/go-git/v5/plumbing"
  9. "github.com/go-git/go-git/v5/plumbing/object"
  10. "github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
  11. "github.com/go-git/go-git/v5/plumbing/transport"
  12. "golang.org/x/crypto/openpgp"
  13. )
  14. // SubmoduleRescursivity defines how depth will affect any submodule recursive
  15. // operation.
  16. type SubmoduleRescursivity uint
  17. const (
  18. // DefaultRemoteName name of the default Remote, just like git command.
  19. DefaultRemoteName = "origin"
  20. // NoRecurseSubmodules disables the recursion for a submodule operation.
  21. NoRecurseSubmodules SubmoduleRescursivity = 0
  22. // DefaultSubmoduleRecursionDepth allow recursion in a submodule operation.
  23. DefaultSubmoduleRecursionDepth SubmoduleRescursivity = 10
  24. )
  25. var (
  26. ErrMissingURL = errors.New("URL field is required")
  27. )
  28. // CloneOptions describes how a clone should be performed.
  29. type CloneOptions struct {
  30. // The (possibly remote) repository URL to clone from.
  31. URL string
  32. // Auth credentials, if required, to use with the remote repository.
  33. Auth transport.AuthMethod
  34. // Name of the remote to be added, by default `origin`.
  35. RemoteName string
  36. // Remote branch to clone.
  37. ReferenceName plumbing.ReferenceName
  38. // Fetch only ReferenceName if true.
  39. SingleBranch bool
  40. // No checkout of HEAD after clone if true.
  41. NoCheckout bool
  42. // Limit fetching to the specified number of commits.
  43. Depth int
  44. // RecurseSubmodules after the clone is created, initialize all submodules
  45. // within, using their default settings. This option is ignored if the
  46. // cloned repository does not have a worktree.
  47. RecurseSubmodules SubmoduleRescursivity
  48. // Progress is where the human readable information sent by the server is
  49. // stored, if nil nothing is stored and the capability (if supported)
  50. // no-progress, is sent to the server to avoid send this information.
  51. Progress sideband.Progress
  52. // Tags describe how the tags will be fetched from the remote repository,
  53. // by default is AllTags.
  54. Tags TagMode
  55. }
  56. // Validate validates the fields and sets the default values.
  57. func (o *CloneOptions) Validate() error {
  58. if o.URL == "" {
  59. return ErrMissingURL
  60. }
  61. if o.RemoteName == "" {
  62. o.RemoteName = DefaultRemoteName
  63. }
  64. if o.ReferenceName == "" {
  65. o.ReferenceName = plumbing.HEAD
  66. }
  67. if o.Tags == InvalidTagMode {
  68. o.Tags = AllTags
  69. }
  70. return nil
  71. }
  72. // PullOptions describes how a pull should be performed.
  73. type PullOptions struct {
  74. // Name of the remote to be pulled. If empty, uses the default.
  75. RemoteName string
  76. // Remote branch to clone. If empty, uses HEAD.
  77. ReferenceName plumbing.ReferenceName
  78. // Fetch only ReferenceName if true.
  79. SingleBranch bool
  80. // Limit fetching to the specified number of commits.
  81. Depth int
  82. // Auth credentials, if required, to use with the remote repository.
  83. Auth transport.AuthMethod
  84. // RecurseSubmodules controls if new commits of all populated submodules
  85. // should be fetched too.
  86. RecurseSubmodules SubmoduleRescursivity
  87. // Progress is where the human readable information sent by the server is
  88. // stored, if nil nothing is stored and the capability (if supported)
  89. // no-progress, is sent to the server to avoid send this information.
  90. Progress sideband.Progress
  91. // Force allows the pull to update a local branch even when the remote
  92. // branch does not descend from it.
  93. Force bool
  94. }
  95. // Validate validates the fields and sets the default values.
  96. func (o *PullOptions) Validate() error {
  97. if o.RemoteName == "" {
  98. o.RemoteName = DefaultRemoteName
  99. }
  100. if o.ReferenceName == "" {
  101. o.ReferenceName = plumbing.HEAD
  102. }
  103. return nil
  104. }
  105. type TagMode int
  106. const (
  107. InvalidTagMode TagMode = iota
  108. // TagFollowing any tag that points into the histories being fetched is also
  109. // fetched. TagFollowing requires a server with `include-tag` capability
  110. // in order to fetch the annotated tags objects.
  111. TagFollowing
  112. // AllTags fetch all tags from the remote (i.e., fetch remote tags
  113. // refs/tags/* into local tags with the same name)
  114. AllTags
  115. //NoTags fetch no tags from the remote at all
  116. NoTags
  117. )
  118. // FetchOptions describes how a fetch should be performed
  119. type FetchOptions struct {
  120. // Name of the remote to fetch from. Defaults to origin.
  121. RemoteName string
  122. RefSpecs []config.RefSpec
  123. // Depth limit fetching to the specified number of commits from the tip of
  124. // each remote branch history.
  125. Depth int
  126. // Auth credentials, if required, to use with the remote repository.
  127. Auth transport.AuthMethod
  128. // Progress is where the human readable information sent by the server is
  129. // stored, if nil nothing is stored and the capability (if supported)
  130. // no-progress, is sent to the server to avoid send this information.
  131. Progress sideband.Progress
  132. // Tags describe how the tags will be fetched from the remote repository,
  133. // by default is TagFollowing.
  134. Tags TagMode
  135. // Force allows the fetch to update a local branch even when the remote
  136. // branch does not descend from it.
  137. Force bool
  138. }
  139. // Validate validates the fields and sets the default values.
  140. func (o *FetchOptions) Validate() error {
  141. if o.RemoteName == "" {
  142. o.RemoteName = DefaultRemoteName
  143. }
  144. if o.Tags == InvalidTagMode {
  145. o.Tags = TagFollowing
  146. }
  147. for _, r := range o.RefSpecs {
  148. if err := r.Validate(); err != nil {
  149. return err
  150. }
  151. }
  152. return nil
  153. }
  154. // PushOptions describes how a push should be performed.
  155. type PushOptions struct {
  156. // RemoteName is the name of the remote to be pushed to.
  157. RemoteName string
  158. // RefSpecs specify what destination ref to update with what source
  159. // object. A refspec with empty src can be used to delete a reference.
  160. RefSpecs []config.RefSpec
  161. // Auth credentials, if required, to use with the remote repository.
  162. Auth transport.AuthMethod
  163. // Progress is where the human readable information sent by the server is
  164. // stored, if nil nothing is stored.
  165. Progress sideband.Progress
  166. // Prune specify that remote refs that match given RefSpecs and that do
  167. // not exist locally will be removed.
  168. Prune bool
  169. // Force allows the push to update a remote branch even when the local
  170. // branch does not descend from it.
  171. Force bool
  172. }
  173. // Validate validates the fields and sets the default values.
  174. func (o *PushOptions) Validate() error {
  175. if o.RemoteName == "" {
  176. o.RemoteName = DefaultRemoteName
  177. }
  178. if len(o.RefSpecs) == 0 {
  179. o.RefSpecs = []config.RefSpec{
  180. config.RefSpec(config.DefaultPushRefSpec),
  181. }
  182. }
  183. for _, r := range o.RefSpecs {
  184. if err := r.Validate(); err != nil {
  185. return err
  186. }
  187. }
  188. return nil
  189. }
  190. // SubmoduleUpdateOptions describes how a submodule update should be performed.
  191. type SubmoduleUpdateOptions struct {
  192. // Init, if true initializes the submodules recorded in the index.
  193. Init bool
  194. // NoFetch tell to the update command to not fetch new objects from the
  195. // remote site.
  196. NoFetch bool
  197. // RecurseSubmodules the update is performed not only in the submodules of
  198. // the current repository but also in any nested submodules inside those
  199. // submodules (and so on). Until the SubmoduleRescursivity is reached.
  200. RecurseSubmodules SubmoduleRescursivity
  201. // Auth credentials, if required, to use with the remote repository.
  202. Auth transport.AuthMethod
  203. }
  204. var (
  205. ErrBranchHashExclusive = errors.New("Branch and Hash are mutually exclusive")
  206. ErrCreateRequiresBranch = errors.New("Branch is mandatory when Create is used")
  207. )
  208. // CheckoutOptions describes how a checkout operation should be performed.
  209. type CheckoutOptions struct {
  210. // Hash is the hash of the commit to be checked out. If used, HEAD will be
  211. // in detached mode. If Create is not used, Branch and Hash are mutually
  212. // exclusive.
  213. Hash plumbing.Hash
  214. // Branch to be checked out, if Branch and Hash are empty is set to `master`.
  215. Branch plumbing.ReferenceName
  216. // Create a new branch named Branch and start it at Hash.
  217. Create bool
  218. // Force, if true when switching branches, proceed even if the index or the
  219. // working tree differs from HEAD. This is used to throw away local changes
  220. Force bool
  221. // Keep, if true when switching branches, local changes (the index or the
  222. // working tree changes) will be kept so that they can be committed to the
  223. // target branch. Force and Keep are mutually exclusive, should not be both
  224. // set to true.
  225. Keep bool
  226. }
  227. // Validate validates the fields and sets the default values.
  228. func (o *CheckoutOptions) Validate() error {
  229. if !o.Create && !o.Hash.IsZero() && o.Branch != "" {
  230. return ErrBranchHashExclusive
  231. }
  232. if o.Create && o.Branch == "" {
  233. return ErrCreateRequiresBranch
  234. }
  235. if o.Branch == "" {
  236. o.Branch = plumbing.Master
  237. }
  238. return nil
  239. }
  240. // ResetMode defines the mode of a reset operation.
  241. type ResetMode int8
  242. const (
  243. // MixedReset resets the index but not the working tree (i.e., the changed
  244. // files are preserved but not marked for commit) and reports what has not
  245. // been updated. This is the default action.
  246. MixedReset ResetMode = iota
  247. // HardReset resets the index and working tree. Any changes to tracked files
  248. // in the working tree are discarded.
  249. HardReset
  250. // MergeReset resets the index and updates the files in the working tree
  251. // that are different between Commit and HEAD, but keeps those which are
  252. // different between the index and working tree (i.e. which have changes
  253. // which have not been added).
  254. //
  255. // If a file that is different between Commit and the index has unstaged
  256. // changes, reset is aborted.
  257. MergeReset
  258. // SoftReset does not touch the index file or the working tree at all (but
  259. // resets the head to <commit>, just like all modes do). This leaves all
  260. // your changed files "Changes to be committed", as git status would put it.
  261. SoftReset
  262. )
  263. // ResetOptions describes how a reset operation should be performed.
  264. type ResetOptions struct {
  265. // Commit, if commit is present set the current branch head (HEAD) to it.
  266. Commit plumbing.Hash
  267. // Mode, form resets the current branch head to Commit and possibly updates
  268. // the index (resetting it to the tree of Commit) and the working tree
  269. // depending on Mode. If empty MixedReset is used.
  270. Mode ResetMode
  271. }
  272. // Validate validates the fields and sets the default values.
  273. func (o *ResetOptions) Validate(r *Repository) error {
  274. if o.Commit == plumbing.ZeroHash {
  275. ref, err := r.Head()
  276. if err != nil {
  277. return err
  278. }
  279. o.Commit = ref.Hash()
  280. }
  281. return nil
  282. }
  283. type LogOrder int8
  284. const (
  285. LogOrderDefault LogOrder = iota
  286. LogOrderDFS
  287. LogOrderDFSPost
  288. LogOrderBSF
  289. LogOrderCommitterTime
  290. )
  291. // LogOptions describes how a log action should be performed.
  292. type LogOptions struct {
  293. // When the From option is set the log will only contain commits
  294. // reachable from it. If this option is not set, HEAD will be used as
  295. // the default From.
  296. From plumbing.Hash
  297. // The default traversal algorithm is Depth-first search
  298. // set Order=LogOrderCommitterTime for ordering by committer time (more compatible with `git log`)
  299. // set Order=LogOrderBSF for Breadth-first search
  300. Order LogOrder
  301. // Show only those commits in which the specified file was inserted/updated.
  302. // It is equivalent to running `git log -- <file-name>`.
  303. // this field is kept for compatility, it can be replaced with PathFilter
  304. FileName *string
  305. // Filter commits based on the path of files that are updated
  306. // takes file path as argument and should return true if the file is desired
  307. // It can be used to implement `git log -- <path>`
  308. // either <path> is a file path, or directory path, or a regexp of file/directory path
  309. PathFilter func(string) bool
  310. // Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>.
  311. // It is equivalent to running `git log --all`.
  312. // If set on true, the From option will be ignored.
  313. All bool
  314. // Show commits more recent than a specific date.
  315. // It is equivalent to running `git log --since <date>` or `git log --after <date>`.
  316. Since *time.Time
  317. // Show commits older than a specific date.
  318. // It is equivalent to running `git log --until <date>` or `git log --before <date>`.
  319. Until *time.Time
  320. }
  321. var (
  322. ErrMissingAuthor = errors.New("author field is required")
  323. )
  324. // CommitOptions describes how a commit operation should be performed.
  325. type CommitOptions struct {
  326. // All automatically stage files that have been modified and deleted, but
  327. // new files you have not told Git about are not affected.
  328. All bool
  329. // Author is the author's signature of the commit. If Author is empty the
  330. // Name and Email is read from the config, and time.Now it's used as When.
  331. Author *object.Signature
  332. // Committer is the committer's signature of the commit. If Committer is
  333. // nil the Author signature is used.
  334. Committer *object.Signature
  335. // Parents are the parents commits for the new commit, by default when
  336. // len(Parents) is zero, the hash of HEAD reference is used.
  337. Parents []plumbing.Hash
  338. // SignKey denotes a key to sign the commit with. A nil value here means the
  339. // commit will not be signed. The private key must be present and already
  340. // decrypted.
  341. SignKey *openpgp.Entity
  342. }
  343. // Validate validates the fields and sets the default values.
  344. func (o *CommitOptions) Validate(r *Repository) error {
  345. if o.Author == nil {
  346. if err := o.loadConfigAuthorAndCommitter(r); err != nil {
  347. return err
  348. }
  349. }
  350. if o.Committer == nil {
  351. o.Committer = o.Author
  352. }
  353. if len(o.Parents) == 0 {
  354. head, err := r.Head()
  355. if err != nil && err != plumbing.ErrReferenceNotFound {
  356. return err
  357. }
  358. if head != nil {
  359. o.Parents = []plumbing.Hash{head.Hash()}
  360. }
  361. }
  362. return nil
  363. }
  364. func (o *CommitOptions) loadConfigAuthorAndCommitter(r *Repository) error {
  365. cfg, err := r.ConfigScoped(config.SystemScope)
  366. if err != nil {
  367. return err
  368. }
  369. if o.Author == nil && cfg.Author.Email != "" && cfg.Author.Name != "" {
  370. o.Author = &object.Signature{
  371. Name: cfg.Author.Name,
  372. Email: cfg.Author.Email,
  373. When: time.Now(),
  374. }
  375. }
  376. if o.Committer == nil && cfg.Committer.Email != "" && cfg.Committer.Name != "" {
  377. o.Committer = &object.Signature{
  378. Name: cfg.Committer.Name,
  379. Email: cfg.Committer.Email,
  380. When: time.Now(),
  381. }
  382. }
  383. if o.Author == nil && cfg.User.Email != "" && cfg.User.Name != "" {
  384. o.Author = &object.Signature{
  385. Name: cfg.User.Name,
  386. Email: cfg.User.Email,
  387. When: time.Now(),
  388. }
  389. }
  390. if o.Author == nil {
  391. return ErrMissingAuthor
  392. }
  393. return nil
  394. }
  395. var (
  396. ErrMissingName = errors.New("name field is required")
  397. ErrMissingTagger = errors.New("tagger field is required")
  398. ErrMissingMessage = errors.New("message field is required")
  399. )
  400. // CreateTagOptions describes how a tag object should be created.
  401. type CreateTagOptions struct {
  402. // Tagger defines the signature of the tag creator.
  403. Tagger *object.Signature
  404. // Message defines the annotation of the tag. It is canonicalized during
  405. // validation into the format expected by git - no leading whitespace and
  406. // ending in a newline.
  407. Message string
  408. // SignKey denotes a key to sign the tag with. A nil value here means the tag
  409. // will not be signed. The private key must be present and already decrypted.
  410. SignKey *openpgp.Entity
  411. }
  412. // Validate validates the fields and sets the default values.
  413. func (o *CreateTagOptions) Validate(r *Repository, hash plumbing.Hash) error {
  414. if o.Tagger == nil {
  415. return ErrMissingTagger
  416. }
  417. if o.Message == "" {
  418. return ErrMissingMessage
  419. }
  420. // Canonicalize the message into the expected message format.
  421. o.Message = strings.TrimSpace(o.Message) + "\n"
  422. return nil
  423. }
  424. // ListOptions describes how a remote list should be performed.
  425. type ListOptions struct {
  426. // Auth credentials, if required, to use with the remote repository.
  427. Auth transport.AuthMethod
  428. }
  429. // CleanOptions describes how a clean should be performed.
  430. type CleanOptions struct {
  431. Dir bool
  432. }
  433. // GrepOptions describes how a grep should be performed.
  434. type GrepOptions struct {
  435. // Patterns are compiled Regexp objects to be matched.
  436. Patterns []*regexp.Regexp
  437. // InvertMatch selects non-matching lines.
  438. InvertMatch bool
  439. // CommitHash is the hash of the commit from which worktree should be derived.
  440. CommitHash plumbing.Hash
  441. // ReferenceName is the branch or tag name from which worktree should be derived.
  442. ReferenceName plumbing.ReferenceName
  443. // PathSpecs are compiled Regexp objects of pathspec to use in the matching.
  444. PathSpecs []*regexp.Regexp
  445. }
  446. var (
  447. ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed")
  448. )
  449. // Validate validates the fields and sets the default values.
  450. func (o *GrepOptions) Validate(w *Worktree) error {
  451. if !o.CommitHash.IsZero() && o.ReferenceName != "" {
  452. return ErrHashOrReference
  453. }
  454. // If none of CommitHash and ReferenceName are provided, set commit hash of
  455. // the repository's head.
  456. if o.CommitHash.IsZero() && o.ReferenceName == "" {
  457. ref, err := w.r.Head()
  458. if err != nil {
  459. return err
  460. }
  461. o.CommitHash = ref.Hash()
  462. }
  463. return nil
  464. }
  465. // PlainOpenOptions describes how opening a plain repository should be
  466. // performed.
  467. type PlainOpenOptions struct {
  468. // DetectDotGit defines whether parent directories should be
  469. // walked until a .git directory or file is found.
  470. DetectDotGit bool
  471. }
  472. // Validate validates the fields and sets the default values.
  473. func (o *PlainOpenOptions) Validate() error { return nil }