Source

hgflow / src / hgflow / hgflow.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
196
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
398
399
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# -*- coding: utf-8 -*-

# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.

# @author : yinwm <yinweiming@gmail.com>

import os
import ConfigParser
            

from mercurial import commands
from mercurial import hg

from mercurial.i18n import _

BASIC_SECTION = 'Basic'
SECNAME_PUBLISH_BRANCH          = 'publish'
SECNAME_DEVELOP_BRANCH          = 'develop'
SECNAME_FEATURE_PREFIX          = 'feature'
SECNAME_RELEASE_PREFIX          = 'release'
SECNAME_HOTFIX_PREFIX           = 'hotfix'
SECNAME_VERSION_TAG_PREFIX      = 'version_tag'


class HgFlow(object):

    def __init__(self, ui, repo):
        self.ui = ui
        self.repo = repo

        self.rootDir = self.repo.root
        self.cfgFile = os.path.join(self.rootDir, '.hgflow')
        self.inited  = os.path.exists(self.cfgFile)

        if self.inited:
            config = ConfigParser.ConfigParser()
            config.read(self.cfgFile)

            self.publishBranch = config.get(BASIC_SECTION, SECNAME_PUBLISH_BRANCH)
            self.developBranch = config.get(BASIC_SECTION, SECNAME_DEVELOP_BRANCH)
            self.featurePrefix = config.get(BASIC_SECTION, SECNAME_FEATURE_PREFIX)
            self.releasePrefix = config.get(BASIC_SECTION, SECNAME_RELEASE_PREFIX)
            self.hotfixPrefix = config.get(BASIC_SECTION, SECNAME_HOTFIX_PREFIX)
            self.versionTagPrefix = config.get(BASIC_SECTION, SECNAME_VERSION_TAG_PREFIX)
            
        #self.output(self.rootDir, '\n', self.cfgFile, '\n', self.inited, '\n')

    def output(self, *args):
        for v in args:
            self.ui.write(v)
            
    def outputln(self, *args):
        args = args + ('\n',)
        self.output(*args)
        

    def input(self, msg):
        self.output(msg)
        return raw_input().strip()

    def _getBranchTags(self):
        d = self.repo.tags()
        #d = self.repo.branchtags()
        t = []
        for k, v in d.iteritems():
            t.append(k)
        return t
            #print v, type(v)

    def _getBranches(self):
        bmap = self.repo.branchmap()
        branches = []
        for b, h in bmap.iteritems():
            branches.append(b)
            #print self.repo.lookupbranch(b)

        return branches

    def _checkInited(self):
        if not self.inited:
            self.output(_('Your workspace is not inited with hg flow, use `hg flow init first`.'), '\n')
            return False

        return True


    def _hasUncommit(self):
        status = self.repo.status()
        for l in status:
            if len(l) > 0:
                self.outputln(_('Your workspace has uncommit content.'))
                return True

        return False


    def _createBranch(self, branch_name, message, from_branch = None):
        if not from_branch is None:
            #first update to from_branch
            commands.update(self.ui, self.repo, from_branch)
            
        commands.branch(self.ui, self.repo, branch_name)
        commands.commit(self.ui, self.repo, message = message)


    def hgflow_func_init(self, args, opts):
        if self.inited:
            self.output(_('Your workspace is already inited, use `hg flow check` for detail hg flow information'), '\n')
            return

        branches = self._getBranches()

        ctx = self.repo[None]
        current_branch = str(ctx.branch())
        

        if len(branches) > 1:
            #more than one brnach, give a warn
            self.output(_('You have more than one branches:'), '\n')
            for b in branches:
                self.output(b, '\t')
                if b != current_branch:
                    self.output('(inactive)')
                self.outputln()

            text = self.input(_('You want to continue flow init? [y] '))
            if not ('' == text or 'y' == text or 'yes' == text):
                return

        if self._hasUncommit():
            return

        publish_branch          = 'default'
        develop_branch          = 'develop'
        feature_branch_prefix   = 'feature/'
        release_branch_prefix   = 'release/'
        hotfix_branch_prefix    = 'hotfix/'
        version_tag_prefix      = ''

        text = self.input(_('Branch name for production release : [default] '))
        if text: publish_branch = text
        
        text = self.input(_('Branch name for "next release" development : [develop] '))
        if text: develop_branch = text

        self.output('\n', _('How to name your supporting branch prefixes?'), '\n');

        text = self.input(_('Feature branches? [feature/] '))
        if text: feature_branch_prefix = text
        text = self.input(_('Release branches? [release/] '))
        if text: release_branch_prefix = text
        text = self.input(_('Hotfix branches? [hotfix/] '))
        if text: hotfix_branch_prefix = text
        text = self.input(_('Version tag prefix? [] '))
        if text: version_tag_prefix = text

        #check existing branch
        
        import ConfigParser
        config = ConfigParser.RawConfigParser()

        config.add_section(BASIC_SECTION)
        config.set(BASIC_SECTION, SECNAME_PUBLISH_BRANCH,       publish_branch)
        config.set(BASIC_SECTION, SECNAME_DEVELOP_BRANCH,       develop_branch)
        config.set(BASIC_SECTION, SECNAME_FEATURE_PREFIX,       feature_branch_prefix)
        config.set(BASIC_SECTION, SECNAME_RELEASE_PREFIX,       release_branch_prefix)
        config.set(BASIC_SECTION, SECNAME_HOTFIX_PREFIX,        hotfix_branch_prefix)
        config.set(BASIC_SECTION, SECNAME_VERSION_TAG_PREFIX,   version_tag_prefix)

        configfile = open(self.cfgFile, 'wb')
        config.write(configfile)
        configfile.close()
        
        commands.add(self.ui, self.repo, self.cfgFile)
        commands.commit(self.ui, self.repo, self.cfgFile, message="hg flow init, add .hgflow file")

        if not publish_branch in branches:
            #create publish_branch
            self._createBranch(publish_branch, 'hg flow init, add branch %s' % (publish_branch, ))

        if not develop_branch in branches:
            self._createBranch(develop_branch, 'hg flow init, add branch %s' % (develop_branch, ))

    def _startBranch(self, target_branch, source_branch):
        branches = self._getBranches()
        if target_branch in branches:
            self.outputln(_('Already has branch named `%s`' % (target_branch, )))
            return

        self._createBranch(target_branch, 'hg flow, add branch `%s`.' % (target_branch, ), source_branch)

    def _findBranch(self, target_branch, name):
        branches = self._getBranches()
        if not target_branch in branches:
            self.outputln(_('No such branch named `%s`' % (name,)))
            return False

        return True

    def _findTag(self, tag_name):
        tl = self._getBranchTags()
        if not tag_name in tl:
            self.outputln(_('No such tag named `%s`' % (tag_name,)))
            return False

        return True


    def hgflow_func_feature(self, args, opts):
        def _feature_func(action, name, target_branch, tag_name):
            if 'start' == action:
                self._startBranch(target_branch, self.developBranch)
            
            elif 'finish' == action:
                '''finish this feature.
                1, Check develop branch version and current feature
                1, Close this branch
                2, Merge it into develop
                3, Commit develop branch
                '''

                if not self._findBranch(target_branch, name):
                    return 

                commands.update(self.ui, self.repo, target_branch)
                commands.commit(self.ui, self.repo, close_branch=True, message='hg flow, close feature %s' % (name,))

                commands.update(self.ui, self.repo, self.developBranch)
                commands.merge(self.ui, self.repo, target_branch)
                #commands.commit(self.ui, self.repo, message='hg flow, merge feature `%s` to develop branch `%s`' % (target_branch, self.developBranch))
                commands.commit(self.ui, self.repo, message='hg flow, merge release `%s` to develop branch `%s`' % (name, self.developBranch))
                #self.outputln(_('WARNING: No automatic commit after merge from feature `%s`, you should resolve the confict (if any) then commit manually.' % (name,)))

            elif 'change' == action:
                commands.update(self.ui, self.repo, target_branch)
                """
            elif 'fetchdev' == action:
                pass
            """
            else:
                self.outputln(_('Please give a valid action.'))

        self._hgflow_func_base(args, opts, self.featurePrefix, _feature_func)


    def _hgflow_func_base(self, args, opts, prefix, func):
        if not self._checkInited():
            return
            
        if len(args) < 2:
            self.outputln(_('Please give a full command.'))
            return

        if self._hasUncommit():
            return


        action = args[0]
        name = args[1]
        target_branch = '%s%s' % (prefix, name)

        tag_name = None
        if len(args) > 2:
            tag_name = args[2]

        func(action, name, target_branch, tag_name)

    def hgflow_func_release(self, args, opts):
        def _release_func(action, name, target_branch, tag_name):
            if 'start' == action:
                '''Create release branch from develop branch
                '''
                self._startBranch(target_branch, self.developBranch)
            elif 'finish' == action:
                '''finish this release
                1, Check publish branch version and current version
                2, Close this branch
                3, Merge it into publish branch
                4, Tag publish branch with release branch name
                5, Merge it into develop branch. Always not successed, should manully do that
                '''

                if not self._findBranch(target_branch, name):
                    return

                #merge tag to publish branch
                if tag_name:
                    if not self._findTag(tag_name):
                        self.outputln(_('Tag `%s` not found.' % (tag_name,)))
                        return
                    else:
                        self._mergeIntoPublishBranch(target_branch, name, tag_name)
                else:
                    self._mergeIntoPublishBranch(target_branch, name)

            else:
                self.outputln(_('Please give a valid action.'))

        self._hgflow_func_base(args, opts, self.releasePrefix, _release_func)

    def hgflow_func_hotfix(self, args, opts):
        def _hotfix_func(action, name, target_branch, tag_name):
            if 'start' == action:
                '''Create hotfix branch from publish branch
                '''
                self._startBranch(target_branch, self.publishBranch)
            elif 'finish' == action:
                '''finish the hotfix
                1, Check publish branch version and current version
                2, Close this branch
                3, Merge it into publich branch
                4, Tag publish branch with hotfix branch name
                5, Merge it into develop branch. Always not successed, otherwise should manually do that
                '''

                if not self._findBranch(target_branch, name):
                    return

                if tag_name:
                    if not self._findTag(tag_name):
                        self.outputln(_('Tag `%s` not found.' % (tag_name,)))
                        return
                    else:
                        self._mergeIntoPublishBranch(target_branch, name, tag_name)
                else:
                    self._mergeIntoPublishBranch(target_branch, name)

            else:
                self.outputln(_('Please give a valid action.'))

        self._hgflow_func_base(args, opts, self.hotfixPrefix, _hotfix_func)
                
    def _mergeIntoPublishBranch(self, target_branch, name, source_tag_name = None):
        commands.update(self.ui, self.repo, target_branch)

        #tag for publish
        tag_name = '%s%s' % (self.versionTagPrefix, name)
        if source_tag_name:
            commands.tag(self.ui, self.repo, tag_name, rev=source_tag_name)
        else:
            commands.tag(self.ui, self.repo, tag_name)
        
        commands.commit(self.ui, self.repo, close_branch=True, message='hg flow, close release %s' % (target_branch,))
        commands.update(self.ui, self.repo, self.publishBranch)

        self.outputln('close target_branch')


        if source_tag_name:
            commands.merge(self.ui, self.repo, source_tag_name)
        else:
            commands.merge(self.ui, self.repo, target_branch)
        commands.commit(self.ui, self.repo, message='hg flow, merge release `%s` to publish branch `%s`' % (name, self.publishBranch))
        self.outputln('merge source_tag_name into publish branch')
        
        '''
        tag_name = '%s%s' % (self.versionTagPrefix, name)
        commands.tag(self.ui, self.repo, tag_name)
        '''
        self.outputln('merge target_branch into develop branch')

        #merge it into develop branch, there should be many confilct code
        commands.update(self.ui, self.repo, self.developBranch)
        commands.merge(self.ui, self.repo, target_branch)
        commands.commit(self.ui, self.repo, message='hg flow, merge release `%s` to develop branch `%s`' % (name, self.developBranch))

        #self.outputln(_('WARNING: No automatic commit after merge from release `%s`, you should resolve the confict (if any) then commit manually' % (name, )))

    def hgflow_func_feature_short(self, name, args, opts):
        if not self._checkInited():
            return
        if self._hasUncommit():
            return

        prefix = self.featurePrefix
        target_branch = '%s%s' % (prefix, name)
        tag_name = None
        if len(args) > 0:
            tag_name = args[0]
        if not self._findBranch(target_branch, name):
            if not (opts['finish'] or opts['close'] or opts['switch']):
                self._startBranch(target_branch, self.developBranch)
            else:
                self.outputln('target_branch %s is not exists' % target_branch)
        else:
            if opts['finish']:
                commands.update(self.ui, self.repo, target_branch)
                commands.commit(self.ui, self.repo, close_branch=True, message='hg flow, close feature %s' % (name,))

                commands.update(self.ui, self.repo, self.developBranch)
                commands.merge(self.ui, self.repo, target_branch)
                #commands.commit(self.ui, self.repo, message='hg flow, merge feature `%s` to develop branch `%s`' % (target_branch, self.developBranch))
                commands.commit(self.ui, self.repo, message='hg flow, merge release `%s` to develop branch `%s`' % (name, self.developBranch))
                #self.outputln(_('WARNING: No automatic commit after merge from feature `%s`, you should resolve the confict (if any) then commit manually.' % (name,)))
            elif opts['close']:
                return
            elif opts['switch']:
                commands.update(self.ui, self.repo, target_branch)
            else:
                commands.update(self.ui, self.repo, target_branch)

    def hgflow_func_release_short(self, name, args, opts):
        if not self._checkInited():
            return
        if self._hasUncommit():
            return

        prefix = self.releasePrefix
        target_branch = '%s%s' % (prefix, name)
        tag_name = None
        if len(args) > 0:
            tag_name = args[0]

        if not self._findBranch(target_branch, name):
            if not (opts['finish'] or opts['close'] or opts['switch']):
                self._startBranch(target_branch, self.developBranch)
            else:
                self.outputln('target_branch %s is not exists' % target_branch)
        else:
            if opts['finish']:
                if tag_name:
                    if not self._findTag(tag_name):
                        self.outputln(_('Tag `%s` not found.' % (tag_name,)))
                        return
                    else:
                        self._mergeIntoPublishBranch(target_branch, name, tag_name)
                else:
                    self._mergeIntoPublishBranch(target_branch, name)
            elif opts['close']:
                return
            elif opts['switch']:
                commands.update(self.ui, self.repo, target_branch)
            else:
                commands.update(self.ui, self.repo, target_branch)

    def hgflow_func_hotfix_short(self, name, args, opts):
        if not self._checkInited():
            return
        if self._hasUncommit():
            return

        prefix = self.hotfixPrefix
        target_branch = '%s%s' % (prefix, name)
        tag_name = None
        if len(args) > 0:
            tag_name = args[0]

        if not self._findBranch(target_branch, name):
            if not (opts['finish'] or opts['close'] or opts['switch']):
                self._startBranch(target_branch, self.publishBranch)
            else:
                self.outputln('target_branch %s is not exists' % target_branch)
        else:
            if opts['finish']:
                if tag_name:
                    if not self._findTag(tag_name):
                        self.outputln(_('Tag `%s` not found.' % (tag_name,)))
                        return
                    else:
                        self._mergeIntoPublishBranch(target_branch, name, tag_name)
                else:
                    self._mergeIntoPublishBranch(target_branch, name)
            elif opts['close']:
                return
            elif opts['switch']:
                commands.update(self.ui, self.repo, target_branch)
            else:
                commands.update(self.ui, self.repo, target_branch)


HGFLOW_FUNCTIONS = {
    'init'      : HgFlow.hgflow_func_init,
    'feature'   : HgFlow.hgflow_func_feature,
    'release'   : HgFlow.hgflow_func_release,
    'hotfix'    : HgFlow.hgflow_func_hotfix,
    }


def hgflow_cmd(ui, repo, patch, *args, **opts):
    if patch in HGFLOW_FUNCTIONS:
        hf = HgFlow(ui, repo)
        HGFLOW_FUNCTIONS[patch](hf, args, opts)
    else:
        ui.write(_('Invalid command, use `hg flow --help` for detail information' ), '\n')

def hgflow_current_branch(hf, prefix):
    ctx = hf.repo[None] 
    current_branch = str(ctx.branch())
    name = current_branch.replace(prefix, '')
    if name == current_branch:
        return None
    return name
    
def hgfeature_cmd(ui, repo, *args, **opts):
    hf = HgFlow(ui, repo)
    if len(args) > 0 :
        name = args[0]
    else:
        name = hgflow_current_branch(hf, hf.featurePrefix)
        if name is None:
            print "current branch is not feature branch"
            return
    HgFlow.hgflow_func_feature_short(hf, name,  args, opts)

def hgrelease_cmd(ui, repo, *args, **opts):
    hf = HgFlow(ui, repo)
    if len(args) > 0 :
        name = args[0]
    else:
        name = hgflow_current_branch(hf, hf.releasePrefix)
        if name is None:
            print "current branch is not release branch"
            return
    HgFlow.hgflow_func_release_short(hf, name,  args, opts)

def hghotfix_cmd(ui, repo, *args, **opts):
    hf = HgFlow(ui, repo)
    if len(args) > 0 :
        name = args[0]
    else:
        name = hgflow_current_branch(hf, hf.hotfixPrefix)
        if name is None:
            print "current branch is not hotfix branch"
            return
    HgFlow.hgflow_func_hotfix_short(hf, name,  args, opts)
    
    '''
    print ui
    print repo
    print patch
    print args
    print opts
    '''



cmdtable = {
    'flow' : (
      (
        hgflow_cmd,
        [],
        ('hg flow ')
        )
      ),
    'feature' : (
      hgfeature_cmd,
      [ ('c', 'close', None, 'close the branch'),
        ('s', 'switch', None, 'switch the branch'),
        ('f', 'finish', None, 'finish the branch') ],
      ('hg feature [options] [branch_name]')
      ),
    'release' : (
      hgrelease_cmd,
      [ ('c', 'close', None, 'close the branch'),
        ('s', 'switch', None, 'switch the branch'),
        ('f', 'finish', None, 'finish the branch') ],
      ('hg release [options] [branch_name]')
      ),
    'hotfix' : (
      hghotfix_cmd,
      [ ('c', 'close', None, 'close the branch'),
        ('s', 'switch', None, 'switch the branch'),
        ('f', 'finish', None, 'finish the branch') ],
      ('hg hotfix [options] [branch_name]')
      )
    }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.