Skip to content

Instantly share code, notes, and snippets.

@jvlad
Created March 23, 2019 17:24
Show Gist options
  • Save jvlad/6c406bb93d31135caddf8dbdefb3cb6d to your computer and use it in GitHub Desktop.
Save jvlad/6c406bb93d31135caddf8dbdefb3cb6d to your computer and use it in GitHub Desktop.
@CommandLine.Command(description = ["Prepend branch's name with `z_archive_`, " +
"push to remote and then delete it's local ref. Default: if no branch specified, " +
"current branch is targeted"])
fun archiveBranches(
@CommandLine.Parameters(
description = ["branches to archive. Run `git branch -a` to list branches"],
index = "0..*"
) branchesToArchive: List<String>?,
@CommandLine.Option(
names = ["-r", "--remote"],
description = ["URL or alias of a custom remote"],
defaultValue = "origin",
showDefaultValue = CommandLine.Help.Visibility.ALWAYS
) remote: String
) {
val currentBranch = currentBranch()
var branchesToArchive = branchesToArchive
var isNeedReturnToMainBranch = false
if (isEmpty(branchesToArchive)) {
branchesToArchive = listOf(currentBranch)
isNeedReturnToMainBranch = true
}
val mainBranch = mainBranch()
branchesToArchive?.forEach { branchToArchive ->
if (!isNeedReturnToMainBranch) {
isNeedReturnToMainBranch = branchToArchive == currentBranch
}
printer.ln("Archiving $branchToArchive...")
val archivedBranch = "z_archive_$branchToArchive"
(
// this step is needed in case if we don't have local ref to target branch yet
"git checkout $branchToArchive && " +
"git branch -m $branchToArchive $archivedBranch ; " +
"git push $remote $archivedBranch ; " +
"git push $remote :$branchToArchive ; " +
"git checkout ${if (isNeedReturnToMainBranch) mainBranch else currentBranch} ; " +
"git branch -D $archivedBranch"
).runAsShellCommand().ln(printer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment