Extensions Extended ExampleΒΆ

This example /home/user/.rccontrol/instance-id/rcextensions/__init.py__ file has been highlighted to show a Redmine integration in full. To extend your RhodeCode Enterprise instances, use the below example to integrate with other applications.

This example file also contains a Slack integration, but it is not highlighted.

  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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
"""
rcextensions module.

"""


import os
import imp
import string
import functools

here = os.path.dirname(os.path.abspath(__file__))
registered_extensions = dict()

class DotDict(dict):

    def __contains__(self, k):
        try:
            return dict.__contains__(self, k) or hasattr(self, k)
        except:
            return False

    # only called if k not found in normal places
    def __getattr__(self, k):
        try:
            return object.__getattribute__(self, k)
        except AttributeError:
            try:
                return self[k]
            except KeyError:
                raise AttributeError(k)

    def __setattr__(self, k, v):
        try:
            object.__getattribute__(self, k)
        except AttributeError:
            try:
                self[k] = v
            except:
                raise AttributeError(k)
        else:
            object.__setattr__(self, k, v)

    def __delattr__(self, k):
        try:
            object.__getattribute__(self, k)
        except AttributeError:
            try:
                del self[k]
            except KeyError:
                raise AttributeError(k)
        else:
            object.__delattr__(self, k)

    def toDict(self):
        return unserialize(self)

    def __repr__(self):
        keys = list(self.iterkeys())
        keys.sort()
        args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])
        return '%s(%s)' % (self.__class__.__name__, args)

    @staticmethod
    def fromDict(d):
        return serialize(d)


def serialize(x):
    if isinstance(x, dict):
        return DotDict((k, serialize(v)) for k, v in x.iteritems())
    elif isinstance(x, (list, tuple)):
        return type(x)(serialize(v) for v in x)
    else:
        return x


def unserialize(x):
    if isinstance(x, dict):
        return dict((k, unserialize(v)) for k, v in x.iteritems())
    elif isinstance(x, (list, tuple)):
        return type(x)(unserialize(v) for v in x)
    else:
        return x


def load_extension(filename, async=False):
    """
    use to load extensions inside rcextension folder.
    for example::

        callback = load_extension('email.py', async=False)
        if callback:
            callback('foobar')

    put file named email.py inside rcextensions folder to load it. Changing
    async=True will make the call of the plugin async, it's useful for
    blocking calls like sending an email or notification with APIs.
    """
    mod = ''.join(filename.split('.')[:-1])
    loaded = imp.load_source(mod, os.path.join(here, filename))

    callback = getattr(loaded, 'run', None)
    if not callback:
        raise Exception('Plugin missing `run` method')
    if async:
        # modify callback so it's actually an async call
        def _async_callback(*args, **kwargs):
            import threading
            thr = threading.Thread(target=callback, args=args, kwargs=kwargs)
            thr.start()
            if kwargs.get('_async_block'):
                del kwargs['_async_block']
                thr.join()

        return _async_callback
    return callback


def _verify_kwargs(expected_parameters, kwargs):
    """
    Verify that exactly `expected_parameters` are passed in as `kwargs`.
    """
    expected_parameters = set(expected_parameters)
    kwargs_keys = set(kwargs.keys())
    if kwargs_keys != expected_parameters:
        missing_kwargs = expected_parameters - kwargs_keys
        unexpected_kwargs = kwargs_keys - expected_parameters
        raise AssertionError(
            "Missing parameters: %r, unexpected parameters: %s" %
            (missing_kwargs, unexpected_kwargs))


def verify_kwargs(required_args):
    """
    decorator to verify extension calls arguments.

    :param required_args:
    """
    def wrap(func):
        def wrapper(*args, **kwargs):
            _verify_kwargs(required_args, kwargs)
            return func(*args, **kwargs)
        return wrapper
    return wrap


def register(name=None):
    def wrap(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # register load_extensions in kwargs, so we can chain plugins
            kwargs['_load_extension'] = load_extension
            # append this path for us to use added plugins or modules
            import sys
            _cur_path = os.path.dirname(os.path.abspath(__file__))
            if _cur_path not in sys.path:
                sys.path.append(_cur_path)

            registered_extensions[func.__name__] = func
            return func(*args, **kwargs)
        return wrapper
    return wrap

# =============================================================================
#  END OF UTILITY FUNCTIONS HERE
# =============================================================================

# Additional mappings that are not present in the pygments lexers
# used for building stats
# format is {'ext':['Names']} eg. {'py':['Python']} note: there can be
# more than one name for extension
# NOTE: that this will override any mappings in LANGUAGES_EXTENSIONS_MAP
# build by pygments
EXTRA_MAPPINGS = {}

# additional lexer definitions for custom files it's overrides pygments lexers,
# and uses defined name of lexer to colorize the files. Format is {'ext':
# 'lexer_name'} List of lexers can be printed running:
#   >> python -c "import pprint;from pygments import lexers;
#           pprint.pprint([(x[0], x[1]) for x in lexers.get_all_lexers()]);"

EXTRA_LEXERS = {}


CONFIG = DotDict(
    slack=DotDict(
        api_key='api-key',
        api_url='slack-incoming-hook-url',
        default_room='#slack-channel',
        default_plugin_config={},
    ),
    redmine=DotDict(
        api_key='api-key',
        default_tracker_url='https://redmine.tracker.url',
        default_project_id=None,
        default_status_resolved_id=3
    ),
)

# slack conf
CONFIG.slack.default_plugin_config = {
    'INCOMING_WEBHOOK_URL': CONFIG.slack.api_url,
    'SLACK_TOKEN': CONFIG.slack.api_key,
    'SLACK_ROOM': CONFIG.slack.default_room,
    'SLACK_FROM': 'RhodeCode',
    'SLACK_FROM_ICON_EMOJI': ':rhodecode:',
}

# redmine smart_pr configuration
def configure_redmine_smart_pr(issues, kwargs):
    kwargs['REDMINE_ISSUES'] = issues
    kwargs['redmine_tracker_url'] = kwargs.pop(
        'redmine_tracker_url', '') or CONFIG.redmine.default_tracker_url
    kwargs['redmine_api_key'] = kwargs.pop(
        'redmine_api_key', '') or CONFIG.redmine.api_key
    kwargs['redmine_project_id'] = kwargs.pop(
        'redmine_project_id', '') or CONFIG.redmine.default_project_id


@register('CREATE_REPO_HOOK')
@verify_kwargs(
    ['_load_extension', 'repo_name', 'repo_type', 'description', 'private',
     'created_on', 'enable_downloads', 'repo_id', 'user_id', 'enable_statistics',
     'clone_uri', 'fork_id', 'group_id', 'created_by'])
def _create_repo_hook(*args, **kwargs):
    """
    POST CREATE REPOSITORY HOOK. This function will be executed after
    each repository is created. kwargs available:

    :param repo_name:
    :param repo_type:
    :param description:
    :param private:
    :param created_on:
    :param enable_downloads:
    :param repo_id:
    :param user_id:
    :param enable_statistics:
    :param clone_uri:
    :param fork_id:
    :param group_id:
    :param created_by:
    """
    return 0
CREATE_REPO_HOOK = _create_repo_hook


@register('CREATE_REPO_GROUP_HOOK')
@verify_kwargs(
    ['_load_extension', 'group_name', 'group_parent_id', 'group_description',
     'group_id', 'user_id', 'created_by', 'created_on', 'enable_locking'])
def _create_repo_group_hook(*args, **kwargs):
    """
    POST CREATE REPOSITORY GROUP HOOK, this function will be
    executed after each repository group is created. kwargs available:

    :param group_name:
    :param group_parent_id:
    :param group_description:
    :param group_id:
    :param user_id:
    :param created_by:
    :param created_on:
    :param enable_locking:
    """
    return 0
CREATE_REPO_GROUP_HOOK = _create_repo_group_hook


@register('PRE_CREATE_USER_HOOK')
@verify_kwargs(
    ['_load_extension', 'username', 'password', 'email', 'firstname',
     'lastname', 'active', 'admin', 'created_by'])
def _pre_create_user_hook(*args, **kwargs):
    """
    PRE CREATE USER HOOK, this function will be executed before each
    user is created, it returns a tuple of bool, reason.
    If bool is False the user creation will be stopped and reason
    will be displayed to the user. kwargs available:

    :param username:
    :param password:
    :param email:
    :param firstname:
    :param lastname:
    :param active:
    :param admin:
    :param created_by:
    """

    reason = 'allowed'
    return True, reason
PRE_CREATE_USER_HOOK = _pre_create_user_hook


@register('CREATE_USER_HOOK')
@verify_kwargs(
    ['_load_extension', 'username', 'full_name_or_username', 'full_contact',
     'user_id', 'name', 'firstname', 'short_contact', 'admin', 'lastname',
     'ip_addresses', 'extern_type', 'extern_name', 'email', 'api_key',
     'api_keys', 'last_login', 'full_name', 'active', 'password', 'emails',
     'inherit_default_permissions', 'created_by', 'created_on'])
def _create_user_hook(*args, **kwargs):
    """
    POST CREATE USER HOOK, this function will be executed after each user is created
    kwargs available:

    :param username:
    :param full_name_or_username:
    :param full_contact:
    :param user_id:
    :param name:
    :param firstname:
    :param short_contact:
    :param admin:
    :param lastname:
    :param ip_addresses:
    :param extern_type:
    :param extern_name:
    :param email:
    :param api_key:
    :param api_keys:
    :param last_login:
    :param full_name:
    :param active:
    :param password:
    :param emails:
    :param inherit_default_permissions:
    :param created_by:
    :param created_on:
    """
    return 0
CREATE_USER_HOOK = _create_user_hook


@register('DELETE_REPO_HOOK')
@verify_kwargs(
    ['_load_extension', 'repo_name', 'repo_type', 'description', 'private',
     'created_on', 'enable_downloads', 'repo_id', 'user_id', 'enable_statistics',
     'clone_uri', 'fork_id', 'group_id', 'deleted_by', 'deleted_on'])
def _delete_repo_hook(*args, **kwargs):
    """
    POST DELETE REPOSITORY HOOK, this function will be executed after
    each repository deletion kwargs available:

    :param repo_name:
    :param repo_type:
    :param description:
    :param private:
    :param created_on:
    :param enable_downloads:
    :param repo_id:
    :param user_id:
    :param enable_statistics:
    :param clone_uri:
    :param fork_id:
    :param group_id:
    :param deleted_by:
    :param deleted_on:
    """
    return 0
DELETE_REPO_HOOK = _delete_repo_hook


@register('DELETE_USER_HOOK')
@verify_kwargs(
    ['_load_extension', 'username', 'full_name_or_username', 'full_contact',
     'user_id', 'name', 'firstname', 'short_contact', 'admin', 'lastname',
     'ip_addresses', 'email', 'api_key', 'last_login', 'full_name', 'active',
     'password', 'emails', 'inherit_default_permissions', 'deleted_by'
     ])
def _delete_user_hook(*args, **kwargs):
    """
    POST DELETE USER HOOK, this function will be executed after each
    user is deleted kwargs available:

    :param username:
    :param full_name_or_username:
    :param full_contact:
    :param user_id:
    :param name:
    :param firstname:
    :param short_contact:
    :param admin:
    :param lastname:
    :param ip_addresses:
    :param ldap_dn:
    :param email:
    :param api_key:
    :param last_login:
    :param full_name:
    :param active:
    :param password:
    :param emails:
    :param inherit_default_permissions:
    :param deleted_by:
    """
    return 0
DELETE_USER_HOOK = _delete_user_hook


@register('PRE_PUSH_HOOK')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username',
     'ip', 'action', 'repository', 'repo_store_path'])
def _pre_push_hook(*args, **kwargs):
    """
    Post push hook
    kwargs available:

      :param server_url: url of instance that triggered this hook
      :param config: path to .ini config used
      :param scm: type of VS 'git' or 'hg'
      :param username: name of user who pushed
      :param ip: ip of who pushed
      :param action: push
      :param repository: repository name
      :param repo_store_path: full path to where repositories are stored
    """
    return 0
PRE_PUSH_HOOK = _pre_push_hook


@register('PUSH_HOOK')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username',
     'ip', 'action', 'repository', 'repo_store_path', 'pushed_revs'])
def _push_hook(*args, **kwargs):
    """
    POST PUSH HOOK, this function will be executed after each push it's
    executed after the build-in hook that RhodeCode uses for logging pushes
    kwargs available:

    :param server_url: url of instance that triggered this hook
    :param config: path to .ini config used
    :param scm: type of VS 'git' or 'hg'
    :param username: name of user who pushed
    :param ip: ip of who pushed
    :param action: push
    :param repository: repository name
    :param repo_store_path: full path to where repositories are stored
    :param pushed_revs: list of pushed commit ids
    """
    # backward compat
    kwargs['commit_ids'] = kwargs['pushed_revs']

    # fetch extra fields from repository
    call = load_extension('extra_fields.py')
    _extra_fields = {}
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']
            _extra_fields[key] = data['field_value']

    # fetch pushed commits, from commit_ids list
    call = load_extension('extract_commits.py')
    extracted_commits = {}
    if call:
        extracted_commits = call(**kwargs)
        # store the commits for the next call chain
    kwargs['COMMITS'] = extracted_commits

    # slack !
    call = load_extension('slack_push_notify.py')
    if call:
        kwargs.update(CONFIG.slack.default_plugin_config)
        call(**kwargs)

    # fetch redmine issues from given commits
    call = load_extension('extract_redmine_issues.py')
    issues = {}
    if call:
        issues = call(**kwargs)

    # redmine smart commits
    call = load_extension('redmine_smart_commits.py')
    if call:
        kwargs['REDMINE_ISSUES'] = issues

        kwargs['redmine_tracker_url'] = kwargs.pop(
            'redmine_tracker_url', '') or CONFIG.redmine.default_tracker_url
        kwargs['redmine_api_key'] = kwargs.pop(
            'redmine_api_key', '') or CONFIG.redmine.api_key
        kwargs['redmine_status_resolved_id'] = kwargs.pop(
            'redmine_status_resolved_id', '') or CONFIG.redmine.default_status_resolved_id
        kwargs['redmine_project_id'] = kwargs.pop(
            'redmine_project_id', '') or CONFIG.redmine.default_project_id
        call(**kwargs)

    return 0
PUSH_HOOK = _push_hook


@register('PRE_PULL_HOOK')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository'])
def _pre_pull_hook(*args, **kwargs):
    """
    Post pull hook
    kwargs available::

      :param server_url: url of instance that triggered this hook
      :param config: path to .ini config used
      :param scm: type of VS 'git' or 'hg'
      :param username: name of user who pulled
      :param ip: ip of who pulled
      :param action: pull
      :param repository: repository name
    """
    return 0
PRE_PULL_HOOK = _pre_pull_hook


@register('PULL_HOOK')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository'])
def _pull_hook(*args, **kwargs):
    """
    POST PULL HOOK, this function will be executed after each push it's
    executed after the build-in hook that RhodeCode uses for logging pulls

    kwargs available:

    :param server_url: url of instance that triggered this hook
    :param config: path to .ini config used
    :param scm: type of VS 'git' or 'hg'
    :param username: name of user who pulled
    :param ip: ip of who pulled
    :param action: pull
    :param repository: repository name
    """
    return 0
PULL_HOOK = _pull_hook


# =============================================================================
#  PULL REQUEST RELATED HOOKS
# =============================================================================
@register('CREATE_PULL_REQUEST')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository', 'pull_request_id', 'url', 'title', 'description',
     'status', 'created_on', 'updated_on', 'commit_ids', 'review_status',
     'mergeable', 'source', 'target', 'author', 'reviewers'])
def _create_pull_request_hook(*args, **kwargs):
    """

    """
    # extract extra fields and default reviewers from target
    kwargs['REPOSITORY'] = kwargs['target']['repository']

    call = load_extension('extra_fields.py')
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']

    call = load_extension('default_reviewers.py')
    if call:
        # read default_reviewers key propagated from extra fields
        kwargs['default_reviewers'] = map(string.strip, kwargs.pop(
            'default_reviewers', '').split(','))
        call(**kwargs)

    # extract below from source repo as commits are there
    kwargs['REPOSITORY'] = kwargs['source']['repository']

    # # fetch pushed commits, from commit_ids list
    # call = load_extension('extract_commits.py')
    # extracted_commits = {}
    # if call:
    #     extracted_commits = call(**kwargs)
    #     # store the commits for the next call chain
    # kwargs['COMMITS'] = extracted_commits
    #
    # # fetch issues from given commits
    # call = load_extension('extract_redmine_issues.py')
    # issues = {}
    # if call:
    #     issues = call(**kwargs)
    #
    # # redmine smart pr update
    # call = load_extension('redmine_pr_flow.py')
    # if call:
    #     # updates kwargs on the fly
    #     configure_redmine_smart_pr(issues=issues, kwargs=kwargs)
    #     call(**kwargs)
    #
    # # slack notification on merging PR
    # call = load_extension('slack_message.py')
    # if call:
    #     kwargs.update(CONFIG.slack.default_plugin_config)
    #     kwargs['SLACK_ROOM'] = '#develop'
    #     kwargs['SLACK_MESSAGE'] = 'Pull request <%s|#%s> (%s) was created.' % (
    #         kwargs.get('url'), kwargs.get('pull_request_id'), kwargs.get('title'))
    #
    #     call(**kwargs)

    return 0
CREATE_PULL_REQUEST = _create_pull_request_hook


@register('REVIEW_PULL_REQUEST')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository', 'pull_request_id', 'url', 'title', 'description',
     'status', 'created_on', 'updated_on', 'commit_ids', 'review_status',
     'mergeable', 'source', 'target', 'author', 'reviewers'])
def _review_pull_request_hook(*args, **kwargs):
    """

    """
    # extract extra fields and default reviewers from target
    kwargs['REPOSITORY'] = kwargs['target']['repository']

    # fetch extra fields
    call = load_extension('extra_fields.py')
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']

    # extract below from source repo as commits are there
    kwargs['REPOSITORY'] = kwargs['source']['repository']

    # fetch pushed commits, from commit_ids list
    call = load_extension('extract_commits.py')
    extracted_commits = {}
    if call:
        extracted_commits = call(**kwargs)
        # store the commits for the next call chain
    kwargs['COMMITS'] = extracted_commits

    # fetch issues from given commits
    call = load_extension('extract_redmine_issues.py')
    issues = {}
    if call:
        issues = call(**kwargs)

    # redmine smart pr update
    call = load_extension('redmine_pr_flow.py')
    if call:
        # updates kwargs on the fly
        configure_redmine_smart_pr(issues=issues, kwargs=kwargs)
        call(**kwargs)

    return 0
REVIEW_PULL_REQUEST = _review_pull_request_hook


@register('UPDATE_PULL_REQUEST')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository', 'pull_request_id', 'url', 'title', 'description',
     'status', 'created_on', 'updated_on', 'commit_ids', 'review_status',
     'mergeable', 'source', 'target', 'author', 'reviewers'])
def _update_pull_request_hook(*args, **kwargs):
    """

    """
    # extract extra fields and default reviewers from target
    kwargs['REPOSITORY'] = kwargs['target']['repository']

    # fetch extra fields
    call = load_extension('extra_fields.py')
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']

    # extract below from source repo as commits are there
    kwargs['REPOSITORY'] = kwargs['source']['repository']

    # fetch pushed commits, from commit_ids list
    call = load_extension('extract_commits.py')
    extracted_commits = {}
    if call:
        extracted_commits = call(**kwargs)
        # store the commits for the next call chain
    kwargs['COMMITS'] = extracted_commits

    # fetch issues from given commits
    call = load_extension('extract_redmine_issues.py')
    issues = {}
    if call:
        issues = call(**kwargs)

    # redmine smart pr updated
    call = load_extension('redmine_pr_flow.py')
    if call:
        # updates kwargs on the fly
        configure_redmine_smart_pr(issues=issues, kwargs=kwargs)
        call(**kwargs)

    return 0
UPDATE_PULL_REQUEST = _update_pull_request_hook


@register('MERGE_PULL_REQUEST')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository', 'pull_request_id', 'url', 'title', 'description',
     'status', 'created_on', 'updated_on', 'commit_ids', 'review_status',
     'mergeable', 'source', 'target', 'author', 'reviewers'])
def _merge_pull_request_hook(*args, **kwargs):
    """

    """
    # extract extra fields and default reviewers from target
    kwargs['REPOSITORY'] = kwargs['target']['repository']

    # fetch extra fields
    call = load_extension('extra_fields.py')
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']

    # extract below from source repo as commits are there
    kwargs['REPOSITORY'] = kwargs['source']['repository']

    # fetch pushed commits, from commit_ids list
    call = load_extension('extract_commits.py')
    extracted_commits = {}
    if call:
        extracted_commits = call(**kwargs)
        # store the commits for the next call chain
    kwargs['COMMITS'] = extracted_commits

    # fetch issues from given commits
    call = load_extension('extract_redmine_issues.py')
    issues = {}
    if call:
        issues = call(**kwargs)

    # redmine smart pr update
    call = load_extension('redmine_pr_flow.py')
    if call:
        # updates kwargs on the fly
        configure_redmine_smart_pr(issues=issues, kwargs=kwargs)
        call(**kwargs)

    # slack notification on merging PR
    call = load_extension('slack_message.py')
    if call:
        kwargs.update(CONFIG.slack.default_plugin_config)
        kwargs['SLACK_ROOM'] = '#develop'
        kwargs['SLACK_MESSAGE'] = 'Pull request <%s|#%s> (%s) was merged.' % (
            kwargs.get('url'), kwargs.get('pull_request_id'), kwargs.get('title'))
        call(**kwargs)

    return 0
MERGE_PULL_REQUEST = _merge_pull_request_hook


@register('CLOSE_PULL_REQUEST')
@verify_kwargs(
    ['_load_extension', 'server_url', 'config', 'scm', 'username', 'ip',
     'action', 'repository', 'pull_request_id', 'url', 'title', 'description',
     'status', 'created_on', 'updated_on', 'commit_ids', 'review_status',
     'mergeable', 'source', 'target', 'author', 'reviewers'])
def _close_pull_request_hook(*args, **kwargs):
    """

    """
    # extract extra fields and default reviewers from target
    kwargs['REPOSITORY'] = kwargs['target']['repository']

    # fetch extra fields
    call = load_extension('extra_fields.py')
    if call:
        repo_extra_fields = call(**kwargs)
        # now update if we have extra fields, they have precedence
        # this way users can store any configuration inside the database per
        # repo
        for key, data in repo_extra_fields.items():
            kwargs[key] = data['field_value']

    # extract below from source repo as commits are there
    kwargs['REPOSITORY'] = kwargs['source']['repository']

    # fetch pushed commits, from commit_ids list
    call = load_extension('extract_commits.py')
    extracted_commits = {}
    if call:
        extracted_commits = call(**kwargs)
        # store the commits for the next call chain
    kwargs['COMMITS'] = extracted_commits

    # fetch issues from given commits
    call = load_extension('extract_redmine_issues.py')
    issues = {}
    if call:
        issues = call(**kwargs)

    # redmine smart pr update
    call = load_extension('redmine_pr_flow.py')
    if call:
        # updates kwargs on the fly
        configure_redmine_smart_pr(issues=issues, kwargs=kwargs)
        call(**kwargs)

    return 0
CLOSE_PULL_REQUEST = _close_pull_request_hook