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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package git
  2. import (
  3. "errors"
  4. "regexp"
  5. "strings"
  6. "time"
  7. "golang.org/x/crypto/openpgp"
  8. "github.com/go-git/go-git/v5/config"
  9. "github.com/go-git/go-git/v5/plumbing"
  10. "github.com/go-git/go-git/v5/plumbing/object"
  11. "github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband"
  12. "github.com/go-git/go-git/v5/plumbing/transport"
  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. }
  170. // Validate validates the fields and sets the default values.
  171. func (o *PushOptions) Validate() error {
  172. if o.RemoteName == "" {
  173. o.RemoteName = DefaultRemoteName
  174. }
  175. if len(o.RefSpecs) == 0 {
  176. o.RefSpecs = []config.RefSpec{
  177. config.RefSpec(config.DefaultPushRefSpec),
  178. }
  179. }
  180. for _, r := range o.RefSpecs {
  181. if err := r.Validate(); err != nil {
  182. return err
  183. }
  184. }
  185. return nil
  186. }
  187. // SubmoduleUpdateOptions describes how a submodule update should be performed.
  188. type SubmoduleUpdateOptions struct {
  189. // Init, if true initializes the submodules recorded in the index.
  190. Init bool
  191. // NoFetch tell to the update command to not fetch new objects from the
  192. // remote site.
  193. NoFetch bool
  194. // RecurseSubmodules the update is performed not only in the submodules of
  195. // the current repository but also in any nested submodules inside those
  196. // submodules (and so on). Until the SubmoduleRescursivity is reached.
  197. RecurseSubmodules SubmoduleRescursivity
  198. // Auth credentials, if required, to use with the remote repository.
  199. Auth transport.AuthMethod
  200. }
  201. var (
  202. ErrBranchHashExclusive = errors.New("Branch and Hash are mutually exclusive")
  203. ErrCreateRequiresBranch = errors.New("Branch is mandatory when Create is used")
  204. )
  205. // CheckoutOptions describes how a checkout operation should be performed.
  206. type CheckoutOptions struct {
  207. // Hash is the hash of the commit to be checked out. If used, HEAD will be
  208. // in detached mode. If Create is not used, Branch and Hash are mutually
  209. // exclusive.
  210. Hash plumbing.Hash
  211. // Branch to be checked out, if Branch and Hash are empty is set to `master`.
  212. Branch plumbing.ReferenceName
  213. // Create a new branch named Branch and start it at Hash.
  214. Create bool
  215. // Force, if true when switching branches, proceed even if the index or the
  216. // working tree differs from HEAD. This is used to throw away local changes
  217. Force bool
  218. // Keep, if true when switching branches, local changes (the index or the
  219. // working tree changes) will be kept so that they can be committed to the
  220. // target branch. Force and Keep are mutually exclusive, should not be both
  221. // set to true.
  222. Keep bool
  223. }
  224. // Validate validates the fields and sets the default values.
  225. func (o *CheckoutOptions) Validate() error {
  226. if !o.Create && !o.Hash.IsZero() && o.Branch != "" {
  227. return ErrBranchHashExclusive
  228. }
  229. if o.Create && o.Branch == "" {
  230. return ErrCreateRequiresBranch
  231. }
  232. if o.Branch == "" {
  233. o.Branch = plumbing.Master
  234. }
  235. return nil
  236. }
  237. // ResetMode defines the mode of a reset operation.
  238. type ResetMode int8
  239. const (
  240. // MixedReset resets the index but not the working tree (i.e., the changed
  241. // files are preserved but not marked for commit) and reports what has not
  242. // been updated. This is the default action.
  243. MixedReset ResetMode = iota
  244. // HardReset resets the index and working tree. Any changes to tracked files
  245. // in the working tree are discarded.
  246. HardReset
  247. // MergeReset resets the index and updates the files in the working tree
  248. // that are different between Commit and HEAD, but keeps those which are
  249. // different between the index and working tree (i.e. which have changes
  250. // which have not been added).
  251. //
  252. // If a file that is different between Commit and the index has unstaged
  253. // changes, reset is aborted.
  254. MergeReset
  255. // SoftReset does not touch the index file or the working tree at all (but
  256. // resets the head to <commit>, just like all modes do). This leaves all
  257. // your changed files "Changes to be committed", as git status would put it.
  258. SoftReset
  259. )
  260. // ResetOptions describes how a reset operation should be performed.
  261. type ResetOptions struct {
  262. // Commit, if commit is present set the current branch head (HEAD) to it.
  263. Commit plumbing.Hash
  264. // Mode, form resets the current branch head to Commit and possibly updates
  265. // the index (resetting it to the tree of Commit) and the working tree
  266. // depending on Mode. If empty MixedReset is used.
  267. Mode ResetMode
  268. }
  269. // Validate validates the fields and sets the default values.
  270. func (o *ResetOptions) Validate(r *Repository) error {
  271. if o.Commit == plumbing.ZeroHash {
  272. ref, err := r.Head()
  273. if err != nil {
  274. return err
  275. }
  276. o.Commit = ref.Hash()
  277. }
  278. return nil
  279. }
  280. type LogOrder int8
  281. const (
  282. LogOrderDefault LogOrder = iota
  283. LogOrderDFS
  284. LogOrderDFSPost
  285. LogOrderBSF
  286. LogOrderCommitterTime
  287. )
  288. // LogOptions describes how a log action should be performed.
  289. type LogOptions struct {
  290. // When the From option is set the log will only contain commits
  291. // reachable from it. If this option is not set, HEAD will be used as
  292. // the default From.
  293. From plumbing.Hash
  294. // The default traversal algorithm is Depth-first search
  295. // set Order=LogOrderCommitterTime for ordering by committer time (more compatible with `git log`)
  296. // set Order=LogOrderBSF for Breadth-first search
  297. Order LogOrder
  298. // Show only those commits in which the specified file was inserted/updated.
  299. // It is equivalent to running `git log -- <file-name>`.
  300. // this field is kept for compatility, it can be replaced with PathFilter
  301. FileName *string
  302. // Filter commits based on the path of files that are updated
  303. // takes file path as argument and should return true if the file is desired
  304. // It can be used to implement `git log -- <path>`
  305. // either <path> is a file path, or directory path, or a regexp of file/directory path
  306. PathFilter func(string) bool
  307. // Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>.
  308. // It is equivalent to running `git log --all`.
  309. // If set on true, the From option will be ignored.
  310. All bool
  311. // Show commits more recent than a specific date.
  312. // It is equivalent to running `git log --since <date>` or `git log --after <date>`.
  313. Since *time.Time
  314. // Show commits older than a specific date.
  315. // It is equivalent to running `git log --until <date>` or `git log --before <date>`.
  316. Until *time.Time
  317. }
  318. var (
  319. ErrMissingAuthor = errors.New("author field is required")
  320. )
  321. // CommitOptions describes how a commit operation should be performed.
  322. type CommitOptions struct {
  323. // All automatically stage files that have been modified and deleted, but
  324. // new files you have not told Git about are not affected.
  325. All bool
  326. // Author is the author's signature of the commit.
  327. Author *object.Signature
  328. // Committer is the committer's signature of the commit. If Committer is
  329. // nil the Author signature is used.
  330. Committer *object.Signature
  331. // Parents are the parents commits for the new commit, by default when
  332. // len(Parents) is zero, the hash of HEAD reference is used.
  333. Parents []plumbing.Hash
  334. // SignKey denotes a key to sign the commit with. A nil value here means the
  335. // commit will not be signed. The private key must be present and already
  336. // decrypted.
  337. SignKey *openpgp.Entity
  338. }
  339. // Validate validates the fields and sets the default values.
  340. func (o *CommitOptions) Validate(r *Repository) error {
  341. if o.Author == nil {
  342. return ErrMissingAuthor
  343. }
  344. if o.Committer == nil {
  345. o.Committer = o.Author
  346. }
  347. if len(o.Parents) == 0 {
  348. head, err := r.Head()
  349. if err != nil && err != plumbing.ErrReferenceNotFound {
  350. return err
  351. }
  352. if head != nil {
  353. o.Parents = []plumbing.Hash{head.Hash()}
  354. }
  355. }
  356. return nil
  357. }
  358. var (
  359. ErrMissingName = errors.New("name field is required")
  360. ErrMissingTagger = errors.New("tagger field is required")
  361. ErrMissingMessage = errors.New("message field is required")
  362. )
  363. // CreateTagOptions describes how a tag object should be created.
  364. type CreateTagOptions struct {
  365. // Tagger defines the signature of the tag creator.
  366. Tagger *object.Signature
  367. // Message defines the annotation of the tag. It is canonicalized during
  368. // validation into the format expected by git - no leading whitespace and
  369. // ending in a newline.
  370. Message string
  371. // SignKey denotes a key to sign the tag with. A nil value here means the tag
  372. // will not be signed. The private key must be present and already decrypted.
  373. SignKey *openpgp.Entity
  374. }
  375. // Validate validates the fields and sets the default values.
  376. func (o *CreateTagOptions) Validate(r *Repository, hash plumbing.Hash) error {
  377. if o.Tagger == nil {
  378. return ErrMissingTagger
  379. }
  380. if o.Message == "" {
  381. return ErrMissingMessage
  382. }
  383. // Canonicalize the message into the expected message format.
  384. o.Message = strings.TrimSpace(o.Message) + "\n"
  385. return nil
  386. }
  387. // ListOptions describes how a remote list should be performed.
  388. type ListOptions struct {
  389. // Auth credentials, if required, to use with the remote repository.
  390. Auth transport.AuthMethod
  391. }
  392. // CleanOptions describes how a clean should be performed.
  393. type CleanOptions struct {
  394. Dir bool
  395. }
  396. // GrepOptions describes how a grep should be performed.
  397. type GrepOptions struct {
  398. // Patterns are compiled Regexp objects to be matched.
  399. Patterns []*regexp.Regexp
  400. // InvertMatch selects non-matching lines.
  401. InvertMatch bool
  402. // CommitHash is the hash of the commit from which worktree should be derived.
  403. CommitHash plumbing.Hash
  404. // ReferenceName is the branch or tag name from which worktree should be derived.
  405. ReferenceName plumbing.ReferenceName
  406. // PathSpecs are compiled Regexp objects of pathspec to use in the matching.
  407. PathSpecs []*regexp.Regexp
  408. }
  409. var (
  410. ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed")
  411. )
  412. // Validate validates the fields and sets the default values.
  413. func (o *GrepOptions) Validate(w *Worktree) error {
  414. if !o.CommitHash.IsZero() && o.ReferenceName != "" {
  415. return ErrHashOrReference
  416. }
  417. // If none of CommitHash and ReferenceName are provided, set commit hash of
  418. // the repository's head.
  419. if o.CommitHash.IsZero() && o.ReferenceName == "" {
  420. ref, err := w.r.Head()
  421. if err != nil {
  422. return err
  423. }
  424. o.CommitHash = ref.Hash()
  425. }
  426. return nil
  427. }
  428. // PlainOpenOptions describes how opening a plain repository should be
  429. // performed.
  430. type PlainOpenOptions struct {
  431. // DetectDotGit defines whether parent directories should be
  432. // walked until a .git directory or file is found.
  433. DetectDotGit bool
  434. }
  435. // Validate validates the fields and sets the default values.
  436. func (o *PlainOpenOptions) Validate() error { return nil }