Programically Check Git Repo, Shelve changes and Checkout from git with a commit hash

Answered

Hi, all,

    

    We have a requirement that we have to let idea checkout with the commit hash provided by a remote server automatically.

    So, these are the questions:

    1. Idea can checkout from git with a commit hash in "Git Branches" -> "Checkout Tag or Revision..". Can we do this programatically? Or, where can we find the related source code?

    2. We need to check which git repo user using, In "Git"->"Pull...", the "Remote" field can show the repository url. How can we get that?

    3. Because we checkout codes automatically, we have to lead user shelve their changes. How can we Invoke "VCS"->"Shelve Changes" Automatically and know the use shelved their changes or not(if not, we won't continue the checkout)

 

Thanks,

 

Meilun Sheng

1 comment
Comment actions Permalink

1. Check GitBrancher.checkout()

2. At first, you have to find the GitRepository object which corresponds to the Git root. You can find one from GitRepositoryManager (GitUtil.getRepositoryManager(project)).

If your users can have several Git roots in the project, the way you select the root may vary. In IDEA in most cases we take the root from the context, e.g. from the file currently open in the editor. See GitBranchesAction, for instance: it calls GitBranchUtil.getCurrentRepository or getRepositoryOrGuess.

Once you have a GitRepository, you can take its remotes: GitRepository.getRemotes(), and each GitRemote has fetch and push URLs, just like in .git/config. If the user has several remotes, probably you want to use the one which is tracked by the current local branch: then see e.g. GitUtil.getTrackInfoForCurrentBranch.

3. You can use GitShelveChangesSaver.save(), or you can operate with the ShelveChangesManager directly. You can also use GitPreservingProcess which will stash - call your operation - and unstash. Currently GitPreservingProcess works only with Git stash, we have plans to support both stash and shelve very soon. I guess that shouldn't really matter whether to use stash or shelve, if you just need to temporarily store the local changes somewhere.

Note that GitBrancher.checkout() calls GitCheckoutOperation inside. The latter has some complex logic to handle different kinds of errors preventing checkout. For example, if the "local changes would be overwritten by checkout" it shows a dialog proposing to do "smart checkout" (stash-checkout-unstash), "force checkout" and "no checkout". If you don't want to give the user this choice, for example if you want always to stash local changes, maybe you'd want to modify the behavior of the GitCheckoutOperation. It is a bit hacky, but you may supply your own GitBranchUiHandler here, as it is done in the tests (see usages of GitBranchUiHandler).

0

Please sign in to leave a comment.