diff --git a/README.md b/README.md index 7fee347b..2541f23f 100644 --- a/README.md +++ b/README.md @@ -476,6 +476,8 @@ gitWithCreds 'https://your.repo' // Implicitly passed credentials ### Changes to local repository +* `git.checkout('branchname')` +* `git.checkoutOrCreate('branchname')` - Creates new Branch if it does not exist; otherwise, it is reset * `git.add('.')` * `git.commit('message', 'Author', 'Author@mail.server)` * `git.commit('message')` - uses the name and email of the last committer as author and committer. diff --git a/src/com/cloudogu/ces/cesbuildlib/Git.groovy b/src/com/cloudogu/ces/cesbuildlib/Git.groovy index b6614eeb..a45cc747 100644 --- a/src/com/cloudogu/ces/cesbuildlib/Git.groovy +++ b/src/com/cloudogu/ces/cesbuildlib/Git.groovy @@ -200,6 +200,17 @@ class Git implements Serializable { script.sh "git checkout ${branchName}" } + /** + * Switch branch of the local repository. Creates new Branch if it does not exist; otherwise, it is reset + * Note: In a multibranch pipeline Jenkins will only fetch the changed branch, + * so you have to call {@link #fetch()} before checkout. + * + * @param branchName name of branch to switch to + */ + void checkoutOrCreate(String branchName) { + script.sh "git checkout -B ${branchName}" + } + /** * Merge branch into the current checked out branch. * diff --git a/test/com/cloudogu/ces/cesbuildlib/GitTest.groovy b/test/com/cloudogu/ces/cesbuildlib/GitTest.groovy index dfd9e017..b6f463da 100644 --- a/test/com/cloudogu/ces/cesbuildlib/GitTest.groovy +++ b/test/com/cloudogu/ces/cesbuildlib/GitTest.groovy @@ -220,6 +220,15 @@ class GitTest { assert scriptMock.actualShStringArgs[0] == "git checkout master" } + @Test + void switchBranch() { + ScriptMock scriptMock = new ScriptMock() + Git git = new Git(scriptMock) + git.checkoutOrCreate("master") + + assert scriptMock.actualShStringArgs[0] == "git checkout -B master" + } + @Test void merge() { ScriptMock scriptMock = new ScriptMock()