Class: GitMaintain::Branch

Inherits:
Object
  • Object
show all
Defined in:
lib/branch.rb

Direct Known Subclasses

GitMaintainBranch, RDMACoreBranch

Constant Summary collapse

ACTION_LIST =
[
    :cp, :steal, :list, :list_stable,
    :merge, :push, :monitor,
    :push_stable, :monitor_stable,
    :release, :reset, :create, :delete
]
NO_FETCH_ACTIONS =
[
    :cp, :merge, :monitor, :release, :delete
]
NO_CHECKOUT_ACTIONS =
[
    :create, :delete, :list, :list_stable, :push, :monitor, :monitor_stable
]
ALL_BRANCHES_ACTIONS =
[
    :create
]
ACTION_HELP =
{
    :cp => "Backport commits and eventually push them to github",
    :create => "Create missing local branches from all the stable branches",
    :delete => "Delete all local branches using the suffix",
    :steal => "Steal commit from upstream that fixes commit in the branch or were tagged as stable",
    :list => "List commit present in the branch but not in the stable branch",
    :list_stable => "List commit present in the stable branch but not in the latest associated relase",
    :merge => "Merge branch with suffix specified in -m <suff> into the main branch",
    :push => "Push branches to github for validation",
    :monitor => "Check the CI state of all branches",
    :push_stable => "Push to stable repo",
    :monitor_stable => "Check the CI state of all stable branches",
    :release => "Create new release on all concerned branches",
    :reset => "Reset branch against upstream",
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(repo, version, ci, branch_suff) ⇒ Branch

Returns a new instance of Branch.



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/branch.rb', line 197

def initialize(repo, version, ci, branch_suff)
    GitMaintain::checkDirectConstructor(self.class)

    @repo          = repo
    @ci            = ci
    @version       = version
    @branch_suff   = branch_suff

    if version =~ /^[0-9]+$/
        @local_branch  = @repo.versionToLocalBranch(@version, @branch_suff)
        @remote_branch = @repo.versionToStableBranch(@version)
        @branch_type = :std
        @verbose_name = "v"+version
    else
        @remote_branch = @local_branch = version
        @branch_type = :user_specified
        @verbose_name = version
    end

    @head          = @repo.runGit("rev-parse --verify --quiet #{@local_branch}")
    @remote_ref    = "#{@repo.stable_repo}/#{@remote_branch}"
    @stable_head   = @repo.runGit("rev-parse --verify --quiet #{@remote_ref}")
    case @branch_type
    when :std
        @stable_base   = @repo.findStableBase(@local_branch)
    when :user_specified
        @stable_base   = @remote_ref
    end
end

Instance Attribute Details

#existsObject (readonly)

Returns the value of attribute exists.



226
227
228
# File 'lib/branch.rb', line 226

def exists
  @exists
end

#headObject (readonly)

Returns the value of attribute head.



226
227
228
# File 'lib/branch.rb', line 226

def head
  @head
end

#local_branchObject (readonly)

Returns the value of attribute local_branch.



226
227
228
# File 'lib/branch.rb', line 226

def local_branch
  @local_branch
end

#remote_branchObject (readonly)

Returns the value of attribute remote_branch.



226
227
228
# File 'lib/branch.rb', line 226

def remote_branch
  @remote_branch
end

#remote_refObject (readonly)

Returns the value of attribute remote_ref.



226
227
228
# File 'lib/branch.rb', line 226

def remote_ref
  @remote_ref
end

#stable_baseObject (readonly)

Returns the value of attribute stable_base.



226
227
228
# File 'lib/branch.rb', line 226

def stable_base
  @stable_base
end

#stable_headObject (readonly)

Returns the value of attribute stable_head.



226
227
228
# File 'lib/branch.rb', line 226

def stable_head
  @stable_head
end

#verbose_nameObject (readonly)

Returns the value of attribute verbose_name.



226
227
228
# File 'lib/branch.rb', line 226

def verbose_name
  @verbose_name
end

#versionObject (readonly)

Returns the value of attribute version.



226
227
228
# File 'lib/branch.rb', line 226

def version
  @version
end

Class Method Details

.check_opts(opts) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/branch.rb', line 119

def self.check_opts(opts)
    if opts[:action] == :push_stable ||
       opts[:action] == :release then
        if opts[:br_suff] != "master" then
            raise "Action #{opts[:action]} can only be done on 'master' suffixed branches"
        end
    end
    if opts[:action] == :delete && opts[:delete_remote] != true then
        if opts[:br_suff] == "master" then
            raise "Action #{opts[:action]} can NOT be done on 'master' suffixed branches"
        end
    end
    opts[:version] = [ /.*/ ] if opts[:version].length == 0
end

.delete_epilogue(opts, branches) ⇒ Object



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# File 'lib/branch.rb', line 490

def self.delete_epilogue(opts, branches)
    # Compact to remove empty entries
    branches.compact!()

    return if branches.length == 0
    puts "Deleting #{opts[:delete_remote] == true ? "remote" : "local"} branches: #{branches.join(" ")}"
    rep = GitMaintain::confirm(opts, "continue", true)
    if rep != "y" then
        log(:INFO, "Cancelling")
        return
    end
    if opts[:delete_remote] == true then
        opts[:repo].runGit("push #{opts[:repo].valid_repo} #{branches.map(){|x| ":" + x}.join(" ")}")
    else
        opts[:repo].runGit("branch -D  #{branches.join(" ")}")
    end
end

.execAction(opts, action) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/branch.rb', line 134

def self.execAction(opts, action)
    repo   = Repo::load()
    ci = CI::load(repo)
    opts[:repo] = repo
    opts[:ci] = ci
    brClass = GitMaintain::getClass(self, repo.name)

    if NO_FETCH_ACTIONS.index(action) == nil && opts[:fetch] != false then
        GitMaintain::log(:INFO, "Fetching stable repo")
        repo.stableUpdate(opts[:fetch])
    end

    branchList=[]
    if opts[:manual_branch] == nil then
        unfilteredList = nil
        if ALL_BRANCHES_ACTIONS.index(action) != nil then
            unfilteredList = repo.getStableBranchList()
        else
            unfilteredList = repo.getBranchList(opts[:br_suff])
        end
        branchList = unfilteredList.map(){|br|
            branch = Branch::load(repo, br, ci, opts[:br_suff])
            case branch.is_targetted?(opts)
            when :too_old
                GitMaintain::log(:VERBOSE, "Skipping older v#{branch.version}")
                next
            when :no_match
                GitMaintain::log(:VERBOSE, "Skipping v#{branch.version} not matching" +
                                           opts[:version].to_s())
                next
            end
            branch
        }.compact()
    else
        branchList = [ Branch::load(repo, opts[:manual_branch], ci, opts[:br_suff]) ]
    end

    loop do
        system("clear; date") if opts[:watch] != false

        res=[]

        # Iterate concerned on all branches
        branchList.each(){|branch|
            if NO_CHECKOUT_ACTIONS.index(action) == nil  then
                GitMaintain::log(:INFO, "Working on #{branch.verbose_name}")
                branch.checkout()
            end
            res << branch.send(action, opts)
        }

        # Run epilogue (if it exists)
        begin
            brClass.send(action.to_s() + "_epilogue", opts, res)
        rescue NoMethodError => e
        end

        break if opts[:watch] == false
        sleep(opts[:watch])
        ci.emptyCache()
    end
end

.load(repo, version, ci, branch_suff) ⇒ Object



43
44
45
46
# File 'lib/branch.rb', line 43

def self.load(repo, version, ci, branch_suff)
    repo_name = File.basename(repo.path)
    return GitMaintain::loadClass(Branch, repo_name, repo, version, ci, branch_suff)
end

.push_epilogue(opts, branches) ⇒ Object



361
362
363
364
365
366
367
368
369
# File 'lib/branch.rb', line 361

def self.push_epilogue(opts, branches)
    # Compact to remove empty entries
    branches.compact!()

    return if branches.length == 0

    opts[:repo].runGit("push #{opts[:push_force] == true ? "-f" : ""} "+
                       "#{opts[:repo].valid_repo} #{branches.join(" ")}")
end

.push_stable_epilogue(opts, branches) ⇒ Object



427
428
429
430
431
432
433
# File 'lib/branch.rb', line 427

def self.push_stable_epilogue(opts, branches)
    # Compact to remove empty entries
    branches.compact!()

    return if branches.length == 0
    opts[:repo].runGit("push #{opts[:repo].stable_repo} #{branches.join(" ")}")
end

.set_opts(action, optsParser, opts) ⇒ Object



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/branch.rb', line 48

def self.set_opts(action, optsParser, opts)
    opts[:base_ver] = 0
    opts[:version] = []
    opts[:commits] = []
    opts[:do_merge] = false
    opts[:push_force] = false
    opts[:no_ci] = false
    opts[:steal_base] = nil
    opts[:check_only] = false
    opts[:fetch] = nil
    opts[:watch] = false
    opts[:delete_remote] = false
    opts[:no_edit] = false

    optsParser.on("-v", "--base-version [MIN_VER]", Integer, "Older release to consider.") {
        |val| opts[:base_ver] = val}
    optsParser.on("-V", "--version [regexp]", Regexp, "Regexp to filter versions.") {
        |val| opts[:version] << val}

    if  ALL_BRANCHES_ACTIONS.index(action) == nil &&
        action != :merge &&
        action != :delete then
        optsParser.on("-B", "--manual-branch <branch name>", "Work on a specific (non-stable) branch.") {
            |val| opts[:manual_branch] = val}
    end

    if NO_FETCH_ACTIONS.index(action) == nil
        optsParser.on("--[no-]fetch", "Enable/Disable fetch of stable repo.") {
            |val| opts[:fetch] = val}
    end

    case action
    when :cp
        optsParser.banner += "-c <sha1> [-c <sha1> ...]"
        optsParser.on("-c", "--sha1 [SHA1]", String, "Commit to cherry-pick. Can be used multiple time.") {
            |val| opts[:commits] << val}
    when :delete
        optsParser.on("--remote", "Delete the remote staging branch instead of the local ones.") {
            |val| opts[:delete_remote] = true}
    when :merge
        optsParser.banner += "-m <suffix>"
        optsParser.on("-m", "--merge [SUFFIX]", "Merge branch with suffix.") {
            |val| opts[:do_merge] = val}
    when :monitor, :monitor_stable
        optsParser.on("-w", "--watch <PERIOD>", Integer,
                      "Watch and refresh CI status every <PERIOD>.") {
            |val| opts[:watch] = val}
    when :push
        optsParser.banner += "[-f]"
        optsParser.on("-f", "--force", "Add --force to git push (for 'push' action).") {
            |val| opts[:push_force] = val}
    when :push_stable
        optsParser.banner += "[-T]"
        optsParser.on("-T", "--no-ci", "Ignore CI build status and push anyway.") {
            |val| opts[:no_ci] = true}
        optsParser.on("-c", "--check", "Check if there is something to be pushed.") {
            |val| opts[:check_only] = true}
    when :release
         optsParser.on("--no-edit", "Do not edit release commit nor tag.") {
             opts[:no_edit] = true }
    when :steal
        optsParser.banner += "[-a][-b <HEAD>]"
        optsParser.on("-a", "--all", "Check all commits from master. "+
                                       "By default only new commits (since last successful run) are considered.") {
            |val| opts[:steal_base] = :all}
        optsParser.on("-b", "--base <HEAD>", "Check all commits from this commit. "+
                                       "By default only new commits (since last successful run) are considered.") {
            |val| opts[:steal_base] = val}
    end
end

Instance Method Details

#checkoutObject

Checkout the repo to the given branch



245
246
247
248
249
250
# File 'lib/branch.rb', line 245

def checkout()
    print @repo.runGit("checkout -q #{@local_branch}")
    if $? != 0 then
        raise "Error: Failed to checkout the branch"
    end
end

#cp(opts) ⇒ Object

Cherry pick an array of commits



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/branch.rb', line 253

def cp(opts)
    opts[:commits].each(){|commit|
        prev_head=@repo.runGit("rev-parse HEAD")
        log(:INFO, "Applying #{@repo.getCommitHeadline(commit)}")
        @repo.runGitInteractive("cherry-pick #{commit}")
        if $? != 0 then
            log(:WARNING, "Cherry pick failure. Starting bash for manual fixes. Exit shell to continue")
   @repo.runBash()
  end
        new_head=@repo.runGit("rev-parse HEAD")
        # Do not make commit pretty if it was not applied
        if new_head != prev_head
      make_pretty(commit)
        end
    }
end

#create(opts) ⇒ Object



465
466
467
468
469
# File 'lib/branch.rb', line 465

def create(opts)
    return if @head != ""
    log(:INFO, "Creating missing #{@local_branch} from #{@remote_ref}")
    @repo.runGit("branch #{@local_branch} #{@remote_ref}")
end

#delete(opts) ⇒ Object



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/branch.rb', line 471

def delete(opts)
    if opts[:delete_remote] == true then
        @repo.runGit("rev-parse --verify --quiet #{@repo.valid_repo}/#{@local_branch}")
        if $? != 0 then
            log(:DEBUG, "Skipping non existing remote branch #{@local_branch}.")
            return
        end
        msg = "delete remote branch #{@repo.valid_repo}/#{@local_branch}"
    else
        msg = "delete branch #{@local_branch}"
    end
    rep = GitMaintain::confirm(opts, msg)
    if rep == "y" then
        return @local_branch
    else
        log(:INFO, "Skipping deletion")
        return
    end
end

#is_targetted?(opts) ⇒ Boolean

Returns:

  • (Boolean)


233
234
235
236
237
238
239
240
241
242
# File 'lib/branch.rb', line 233

def is_targetted?(opts)
    return true if @branch_type == :user_specified
    if @version.to_i < opts[:base_ver] then
        return :too_old
    end
    opts[:version].each() {|regexp|
        return true if @version =~ regexp
    }
    return :no_match
end

#list(opts) ⇒ Object

List commits in the branch that are no in the stable branch



309
310
311
312
# File 'lib/branch.rb', line 309

def list(opts)
    GitMaintain::log(:INFO, "Working on #{@verbose_name}")
    GitMaintain::showLog(opts, @local_branch, @remote_ref)
end

#list_stable(opts) ⇒ Object

List commits in the stable_branch that are no in the latest release



315
316
317
318
# File 'lib/branch.rb', line 315

def list_stable(opts)
    GitMaintain::log(:INFO, "Working on #{@verbose_name}")
    GitMaintain::showLog(opts, @remote_ref, @repo.runGit("describe --abbrev=0 #{@local_branch}"))
end

#log(lvl, str) ⇒ Object



229
230
231
# File 'lib/branch.rb', line 229

def log(lvl, str)
    GitMaintain::log(lvl, str)
end

#merge(opts) ⇒ Object

Merge merge_branch into this one



321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/branch.rb', line 321

def merge(opts)
    merge_branch = @repo.versionToLocalBranch(@version, opts[:do_merge])

    # Make sure branch exists
    hash_to_merge = @repo.runGit("rev-parse --verify --quiet #{merge_branch}")
    if $? != 0 then
        log(:INFO, "Branch #{merge_branch} does not exists. Skipping...")
        return
    end

    # See if there is anything worth merging
    merge_base_hash = @repo.runGit("merge-base #{merge_branch} #{@local_branch}")
    if merge_base_hash == hash_to_merge then
        log(:INFO, "Branch #{merge_branch} has no commit that needs to be merged")
        return
    end

    rep = GitMaintain::checkLog(opts, merge_branch, @local_branch, "merge")
    if rep == "y" then
        @repo.runGitInteractive("merge #{merge_branch}")
        if $? != 0 then
            log(:WARNING, "Merge failure. Starting bash for manual fixes. Exit shell to continue")
   @repo.runBash()
  end
    else
        log(:INFO, "Skipping merge")
        return
    end 
end

#monitor(opts) ⇒ Object

Monitor the build status on CI



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/branch.rb', line 372

def monitor(opts)
    st = @ci.getValidState(self, @head)
    suff=""
    case st
    when "started"
        suff= " started at #{@ci.getValidTS(self, @head)}"
    end
    log(:INFO, "Status for v#{@version}: " + st + suff)
    if @ci.isErrored(self, st) && opts[:watch] == false
        rep = "y"
        suff=""
        while rep == "y"
            rep = GitMaintain::confirm(opts, "see the build log#{suff}")
            if rep == "y" then
                log = @ci.getValidLog(self, @head)
                tmp = `mktemp`.chomp()
                tmpfile = File.open(tmp, "w+")
                tmpfile.puts(log)
                tmpfile.close()
                system("less -r #{tmp}")
                `rm -f #{tmp}`
            end
            suff=" again"
        end
    end
end

#monitor_stable(opts) ⇒ Object

Monitor the build status of the stable branch on CI



435
436
437
438
439
440
441
442
443
# File 'lib/branch.rb', line 435

def monitor_stable(opts)
    st = @ci.getStableState(self, @stable_head)
    suff=""
    case st
    when "started"
        suff= " started at #{@ci.getStableTS(self, @stable_head)}"
    end
    log(:INFO, "Status for v#{@version}: " + st + suff)
end

#push(opts) ⇒ Object

Push the branch to the validation repo



352
353
354
355
356
357
358
359
# File 'lib/branch.rb', line 352

def push(opts)
    if same_sha?(@local_branch, @repo.valid_repo + "/" + @local_branch) ||
       same_sha?(@local_branch, @remote_ref) then
        log(:INFO, "Nothing to push on #{@local_branch}")
        return
    end
    return "#{@local_branch}:#{@local_branch}"
end

#push_stable(opts) ⇒ Object

Push branch to the stable repo



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/branch.rb', line 400

def push_stable(opts)
    if same_sha?(@local_branch, @remote_ref) then
        log(:INFO, "Stable is already up-to-date")
        return
    end

    if (opts[:no_ci] != true && @NO_CI != true) &&
       @ci.checkValidState(self, @head) != true then
        log(:WARNING, "Build is not passed on CI. Skipping push to stable")
        return
    end

    if opts[:check_only] == true then
        GitMaintain::checkLog(opts, @local_branch, @remote_ref, "")
        return
    end

    rep = GitMaintain::checkLog(opts, @local_branch, @remote_ref, "submit")
    if rep == "y" then
        return "#{@local_branch}:#{@remote_branch}"
    else
        log(:INFO, "Skipping push to stable")
        return
    end
end

#release(opts) ⇒ Object



461
462
463
# File 'lib/branch.rb', line 461

def release(opts)
    log(:ERROR,"#No release command available for this repo")
end

#reset(opts) ⇒ Object

Reset the branch to the upstream stable one



446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/branch.rb', line 446

def reset(opts)
    if same_sha?(@local_branch, @remote_ref) then
        log(:INFO, "Nothing to reset")
        return
    end

    rep = GitMaintain::checkLog(opts, @local_branch, @remote_ref, "reset")
    if rep == "y" then
        @repo.runGit("reset --hard #{@remote_ref}")
    else
        log(:INFO, "Skipping reset")
        return
    end
end

#steal(opts) ⇒ Object

Steal upstream commits that are not in the branch



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# File 'lib/branch.rb', line 271

def steal(opts)
    base_ref=@stable_base

    # If we are not force checking everything,
    # try to start from the last tag we steal upto
    case opts[:steal_base]
        when nil
            sha = @repo.runGit("rev-parse 'git-maintain/steal/last/#{@stable_base}' 2>&1")
            if $? == 0 then
                base_ref=sha
                log(:VERBOSE, "Starting from last successfull run:")
                log(:VERBOSE, @repo.getCommitHeadline(base_ref))
            end
        when :all
            base_ref=@stable_base
        else
            sha = @repo.runGit("rev-parse #{opts[:steal_base]} 2>&1")
            if $? == 0 then
                base_ref=sha
                log(:VERBOSE, "Starting from base:")
                log(:VERBOSE, @repo.getCommitHeadline(base_ref))
            end
    end

    master_sha=@repo.runGit("rev-parse origin/master")
    res = steal_all(opts, "#{base_ref}..#{master_sha}", true)

    # If we picked all the commits (or nothing happened)
    # Mark the current master as the last checked point so we
    # can just steal from this point on the next run
    if res == true then
        @repo.runGit("tag -f 'git-maintain/steal/last/#{@stable_base}' origin/master")
        log(:VERBOSE, "Marking new last successfull run at:")
        log(:VERBOSE, @repo.getCommitHeadline(master_sha))
    end
end