File: policy.py

package info (click to toggle)
azure-devops-cli-extension 1.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,384 kB
  • sloc: python: 160,782; xml: 198; makefile: 56; sh: 51
file content (685 lines) | stat: -rw-r--r-- 31,527 bytes parent folder | download | duplicates (4)
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
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=line-too-long
# This file a lot of these are intentional because that makes grouping variables easy

from knack.util import CLIError
from knack.log import get_logger
from azext_devops.devops_sdk.v5_0.policy.models import PolicyConfiguration

from azext_devops.dev.common.git import resolve_git_ref_heads
from azext_devops.dev.common.services import (get_policy_client, resolve_instance_and_project)
from azext_devops.dev.common.identities import resolve_identity_as_id

logger = get_logger(__name__)


def list_policy(organization=None, project=None, repository_id=None, branch=None, detect=None):
    """List all policies in a project.
    :param repository_id: Id of the repository.
    :type repository_id: string
    :param branch: Branch. (--repository-id is required)
    :type branch: string
    :rtype: [PolicyConfiguration]
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)

    if branch is not None and repository_id is None:
        raise CLIError('--repository-id is required with --branch')

    scope = None

    if repository_id is not None:
        repository_id = repository_id.replace('-', '')
        scope = repository_id
        if branch is not None:
            branch = resolve_git_ref_heads(branch)
            scope = scope + ':' + branch

    policy_client = get_policy_client(organization)
    return policy_client.get_policy_configurations(project=project, scope=scope)


def get_policy(policy_id, organization=None, project=None, detect=None):
    """Show policy details.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    return policy_client.get_policy_configuration(project=project, configuration_id=policy_id)


def delete_policy(policy_id, organization=None, project=None, detect=None):
    """Delete a policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    return policy_client.delete_policy_configuration(project=project, configuration_id=policy_id)


def create_policy_configuration_file(policy_configuration, organization=None, project=None, detect=None):
    '''Create a policy using a configuration file.
    Recommended when creating policies using multiple scopes for a policy.
    See https://aka.ms/azure-devops-cli-docs-policy-file for more information.
    '''
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    with open(policy_configuration) as f:
        import json
        configuration = json.load(f)
        return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_configuration_file(policy_id, policy_configuration, organization=None, project=None, detect=None):
    """Update a policy using a configuration file.
    Recommended when creating policies using multiple scopes for a policy.
    See https://aka.ms/azure-devops-cli-docs-policy-file for more information.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    with open(policy_configuration) as f:
        import json
        configuration = json.load(f)
        return policy_client.update_policy_configuration(
            configuration=configuration,
            project=project,
            configuration_id=policy_id)


def create_policy_approver_count(repository_id, branch, blocking, enabled,
                                 minimum_approver_count, creator_vote_counts, allow_downvotes, reset_on_source_push,
                                 branch_match_type='exact',
                                 organization=None, project=None, detect=None):
    """Create approver count policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    param_name_array = ['minimumApproverCount', 'creatorVoteCounts', 'allowDownvotes', 'resetOnSourcePush']
    param_value_array = [minimum_approver_count, creator_vote_counts, allow_downvotes, reset_on_source_push]
    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd',
                                                param_name_array, param_value_array, branch_match_type)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_approver_count(policy_id,
                                 repository_id=None, branch=None, blocking=None, enabled=None, branch_match_type=None,
                                 minimum_approver_count=None, creator_vote_counts=None, allow_downvotes=None, reset_on_source_push=None,
                                 organization=None, project=None, detect=None):
    """Update approver count policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)
    param_name_array = ['minimumApproverCount', 'creatorVoteCounts', 'allowDownvotes', 'resetOnSourcePush']

    current_setting = current_policy.settings
    current_scope = current_policy.settings['scope'][0]

    param_value_array = [
        minimum_approver_count if minimum_approver_count is not None else current_setting.get('minimumApproverCount', None),
        creator_vote_counts if creator_vote_counts is not None else current_setting.get('creatorVoteCounts', None),
        allow_downvotes if allow_downvotes is not None else current_setting.get('allowDownvotes', None),
        reset_on_source_push if reset_on_source_push is not None else current_setting.get('resetOnSourcePush', None)
    ]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        'fa4e907d-c16b-4a4c-9dfa-4906e5d171dd',
        param_name_array,
        param_value_array,
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_required_reviewer(repository_id, branch, blocking, enabled,
                                    message, required_reviewer_ids,
                                    branch_match_type='exact',
                                    path_filter=None,
                                    organization=None, project=None, detect=None):
    """Create required reviewer policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    requiredReviewerIds = resolveIdentityMailsToIds(required_reviewer_ids, organization)
    policy_client = get_policy_client(organization)
    param_name_array = ['requiredReviewerIds', 'message', 'filenamePatterns']
    param_value_array = [requiredReviewerIds, message, createFileNamePatterns(path_filter)]
    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                'fd2167ab-b0be-447a-8ec8-39368250530e',
                                                param_name_array, param_value_array,
                                                branch_match_type)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_required_reviewer(policy_id,
                                    repository_id=None, branch=None, branch_match_type=None,
                                    blocking=None, enabled=None,
                                    message=None, required_reviewer_ids=None,
                                    path_filter=None,
                                    organization=None, project=None, detect=None):
    """Update required reviewer policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)
    param_name_array = ['requiredReviewerIds', 'message', 'filenamePatterns']
    requiredReviewerIds = resolveIdentityMailsToIds(required_reviewer_ids, organization)

    current_setting = current_policy.settings
    current_scope = current_policy.settings['scope'][0]

    param_value_array = [
        requiredReviewerIds or current_setting.get('requiredReviewerIds', None),
        message or current_setting.get('message', None),
        createFileNamePatterns(path_filter) or current_setting.get('filenamePatterns', None)
    ]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        'fd2167ab-b0be-447a-8ec8-39368250530e',
        param_name_array,
        param_value_array,
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


_MERGE_POLICY_DEPRECATED_OPTION_ERROR = '--use-squash-merge has been deprecated to align with the new merge '\
                                        'strategies in Azure Repos. Use --allow-squash instead. Refer '\
                                        'https://aka.ms/merge-types for more information.'


def create_policy_merge_strategy(repository_id, branch, blocking, enabled,
                                 use_squash_merge=None,
                                 allow_squash=None,
                                 allow_rebase=None,
                                 allow_rebase_merge=None,
                                 allow_no_fast_forward=None,
                                 branch_match_type='exact',
                                 organization=None, project=None, detect=None):
    """Create merge strategy policy
    """
    if (use_squash_merge is None and not allow_squash and not allow_rebase_merge and
            not allow_rebase and not allow_no_fast_forward):
        raise CLIError("Atleast one merge type must be enabled.")
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    if use_squash_merge is None:
        param_name_array = ['allowSquash', 'allowRebase', 'allowRebaseMerge', 'allowNoFastForward']
        param_value_array = [allow_squash, allow_rebase, allow_rebase_merge, allow_no_fast_forward]
        for i, value in enumerate(param_value_array):
            if value is None:
                param_value_array[i] = False
    else:
        if allow_rebase or allow_no_fast_forward or allow_rebase_merge or allow_squash:
            raise CLIError(_MERGE_POLICY_DEPRECATED_OPTION_ERROR)
        param_name_array = ['useSquashMerge']
        param_value_array = [use_squash_merge]

    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab',
                                                param_name_array, param_value_array, branch_match_type)
    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_merge_strategy(policy_id,
                                 repository_id=None, branch=None, branch_match_type=None,
                                 blocking=None, enabled=None,
                                 use_squash_merge=None,
                                 allow_squash=None,
                                 allow_rebase=None,
                                 allow_rebase_merge=None,
                                 allow_no_fast_forward=None,
                                 organization=None, project=None, detect=None):
    """Update merge strategy policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)
    current_setting = current_policy.settings
    current_scope = current_policy.settings['scope'][0]
    current_setting_new_merge_values_array = [
        current_setting.get('allowSquash', None),
        current_setting.get('allowRebase', None),
        current_setting.get('allowRebaseMerge', None),
        current_setting.get('allowNoFastForward', None)]
    is_new_merge_type_update = (
        allow_squash is not None or
        allow_no_fast_forward is not None or
        allow_rebase is not None or
        allow_rebase_merge is not None)

    if is_new_merge_type_update:
        if use_squash_merge is not None:
            raise CLIError(_MERGE_POLICY_DEPRECATED_OPTION_ERROR)
        # Update is trying to set some new merge type (this should consider useSquashMerge as deprecated)
        param_name_array = ['allowSquash', 'allowRebase', 'allowRebaseMerge', 'allowNoFastForward']
        param_value_array = [
            allow_squash if allow_squash is not None else current_setting.get(
                'allowSquash', current_setting.get('useSquashMerge', None)),
            allow_rebase if allow_rebase is not None else current_setting.get('allowRebase', None),
            allow_rebase_merge if allow_rebase_merge is not None else current_setting.get('allowRebaseMerge', None),
            allow_no_fast_forward if allow_no_fast_forward is not None else current_setting.get(
                'allowNoFastForward', None)
        ]
        # We cannot send setting as None in the API
        for i, value in enumerate(param_value_array):
            if value is None:
                param_value_array[i] = False
        # API does not fail but the update is rejected if the last setting is being set to false.
        # So this check prevents it from client side.
        if not [i for i, value in enumerate(param_value_array) if value]:
            raise CLIError("Atleast one merge type must be enabled.")
    # Update is trying to set legacy option
    elif use_squash_merge is not None:
        # Moving from non legacy to legacy - NOT ALLOWED
        if [i for i, value in enumerate(current_setting_new_merge_values_array) if value is not None]:
            raise CLIError(_MERGE_POLICY_DEPRECATED_OPTION_ERROR)
        # Changing from legacy to legacy
        param_name_array = ['useSquashMerge']
        param_value_array = [use_squash_merge]
    # No update to merge types only other options are getting updated
    else:
        # Current setting is new values type
        if [i for i, value in enumerate(current_setting_new_merge_values_array) if value is not None]:
            param_name_array = ['allowSquash', 'allowRebase', 'allowRebaseMerge', 'allowNoFastForward']
            param_value_array = current_setting_new_merge_values_array
            # We cannot send setting as None in the API
            for i, value in enumerate(param_value_array):
                if value is None:
                    param_value_array[i] = False
        # Current setting is legacy option
        else:
            param_name_array = ['useSquashMerge']
            param_value_array = [current_setting.get('useSquashMerge', False)]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        'fa4e907d-c16b-4a4c-9dfa-4916e5d171ab',
        param_name_array,
        param_value_array,
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_build(repository_id, branch, blocking, enabled,
                        build_definition_id, queue_on_source_update_only, manual_queue_only, display_name, valid_duration,
                        path_filter=None,
                        branch_match_type='exact',
                        organization=None, project=None, detect=None):
    """Create build policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    param_name_array = [
        'buildDefinitionId',
        'queueOnSourceUpdateOnly',
        'manualQueueOnly',
        'displayName',
        'validDuration',
        'filenamePatterns']
    param_value_array = [
        build_definition_id,
        queue_on_source_update_only,
        manual_queue_only,
        display_name,
        valid_duration,
        createFileNamePatterns(path_filter)]
    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                '0609b952-1397-4640-95ec-e00a01b2c241',
                                                param_name_array, param_value_array,
                                                branch_match_type)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_build(policy_id,
                        repository_id=None, branch=None, branch_match_type=None, blocking=None, enabled=None,
                        build_definition_id=None, queue_on_source_update_only=None, manual_queue_only=None, display_name=None, valid_duration=None,
                        path_filter=None,
                        organization=None, project=None, detect=None):
    """Update build policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)
    param_name_array = [
        'buildDefinitionId',
        'queueOnSourceUpdateOnly',
        'manualQueueOnly',
        'displayName',
        'validDuration',
        'filenamePatterns']

    current_setting = current_policy.settings
    current_scope = current_policy.settings['scope'][0]

    param_value_array = [
        build_definition_id or current_setting.get('buildDefinitionId', None),
        queue_on_source_update_only if queue_on_source_update_only is not None else current_setting.get('queueOnSourceUpdateOnly', None),
        manual_queue_only if manual_queue_only is not None else current_setting.get('manualQueueOnly', None),
        display_name or current_setting.get('displayName', None),
        valid_duration or current_setting.get('validDuration', None),
        createFileNamePatterns(path_filter) or current_setting.get('filenamePatterns', None)
    ]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        '0609b952-1397-4640-95ec-e00a01b2c241',
        param_name_array,
        param_value_array,
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_file_size(repository_id, blocking, enabled,
                            maximum_git_blob_size, use_uncompressed_size,
                            organization=None, project=None, detect=None):
    """Create file size policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    param_name_array = ['maximumGitBlobSizeInBytes', 'useUncompressedSize']
    param_value_array = [maximum_git_blob_size, use_uncompressed_size]
    configuration = create_configuration_object(repository_id, None, blocking, enabled,
                                                '2e26e725-8201-4edd-8bf5-978563c34a80',
                                                param_name_array, param_value_array)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_file_size(policy_id,
                            repository_id=None, blocking=None, enabled=None,
                            maximum_git_blob_size=None, use_uncompressed_size=None,
                            organization=None, project=None, detect=None):
    """Update file size policy
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)
    param_name_array = ['maximumGitBlobSizeInBytes', 'useUncompressedSize']

    current_setting = current_policy.settings
    current_scope = current_policy.settings['scope'][0]

    param_value_array = [
        maximum_git_blob_size or current_setting.get('maximumGitBlobSizeInBytes', None),
        use_uncompressed_size if use_uncompressed_size is not None else current_setting.get('useUncompressedSize', None)
    ]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        None,
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        '2e26e725-8201-4edd-8bf5-978563c34a80',
        param_name_array,
        param_value_array
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_comment_required(repository_id, branch,
                                   blocking, enabled,
                                   branch_match_type='exact',
                                   organization=None, project=None, detect=None):
    """Create comment resolution required policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                'c6a1889d-b943-4856-b76f-9e46bb6b0df2', [], [], branch_match_type)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_comment_required(policy_id,
                                   repository_id=None, branch=None, branch_match_type=None,
                                   blocking=None, enabled=None,
                                   organization=None, project=None, detect=None):
    """Update comment resolution required policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)

    current_scope = current_policy.settings['scope'][0]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        'c6a1889d-b943-4856-b76f-9e46bb6b0df2',
        [],
        [],
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_work_item_linking(repository_id, branch,
                                    blocking, enabled,
                                    branch_match_type='exact',
                                    organization=None, project=None, detect=None):
    """Create work item linking policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    configuration = create_configuration_object(repository_id, branch, blocking, enabled,
                                                '40e92b44-2fe1-4dd6-b3d8-74a9c21d0c6e', [], [], branch_match_type)

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_work_item_linking(policy_id,
                                    repository_id=None, branch=None, branch_match_type=None,
                                    blocking=None, enabled=None,
                                    organization=None, project=None, detect=None):
    """Update work item linking policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)

    current_scope = current_policy.settings['scope'][0]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        branch or current_scope['refName'],
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        '40e92b44-2fe1-4dd6-b3d8-74a9c21d0c6e',
        [],
        [],
        branch_match_type or current_scope['matchKind']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_policy_case_enforcement(repository_id, blocking, enabled,
                                   organization=None, project=None, detect=None):
    """Create case enforcement policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    configuration = create_configuration_object(repository_id, None, blocking, enabled,
                                                '7ed39669-655c-494e-b4a0-a08b4da0fcce',
                                                ['enforceConsistentCase'],
                                                ['true'])

    return policy_client.create_policy_configuration(configuration=configuration, project=project)


def update_policy_case_enforcement(policy_id,
                                   repository_id=None, blocking=None, enabled=None,
                                   organization=None, project=None, detect=None):
    """Update case enforcement policy.
    """
    organization, project = resolve_instance_and_project(
        detect=detect, organization=organization, project=project)
    policy_client = get_policy_client(organization)
    current_policy = policy_client.get_policy_configuration(project=project, configuration_id=policy_id)

    current_scope = current_policy.settings['scope'][0]

    updated_configuration = create_configuration_object(
        repository_id or current_scope['repositoryId'],
        None,
        blocking if blocking is not None else current_policy.is_blocking,
        enabled if enabled is not None else current_policy.is_enabled,
        '7ed39669-655c-494e-b4a0-a08b4da0fcce',
        ['enforceConsistentCase'],
        ['true']
    )

    return policy_client.update_policy_configuration(
        configuration=updated_configuration,
        project=project,
        configuration_id=policy_id
    )


def create_configuration_object(repository_id,
                                branch,
                                blocking,
                                enabled,
                                policy_type_id,
                                param_name_array,
                                param_value_array,
                                branch_match_type='exact'):
    branch = resolve_git_ref_heads(branch)
    policyConfiguration = PolicyConfiguration(is_blocking=blocking, is_enabled=enabled)
    scope = createScope(repository_id, branch, branch_match_type)
    policyConfiguration.settings = {
        'scope': scope
    }
    policyConfiguration.type = {
        'id': policy_type_id
    }

    index = 0
    for param in param_name_array:
        policyConfiguration.settings[param] = param_value_array[index]
        index = index + 1

    return policyConfiguration


def createFileNamePatterns(filePatterns):
    if filePatterns is None:
        return []

    return filePatterns.split(';')


def createScope(repository_id, branch, branch_match_type):
    scope = [
        {
            'repositoryId': repository_id,
            'refName': branch,
            'matchKind': branch_match_type
        }
    ]

    if branch is None:
        scope = [
            {
                'repositoryId': repository_id,
            }
        ]

    return scope


def resolveIdentityMailsToIds(mailList, organization):
    if mailList is None:
        return []

    logger.debug('mail list %s ', mailList)
    if not mailList or (not mailList.strip()):
        return None

    idList = []
    for mail in mailList.split(';'):
        mailStripped = mail.strip()
        logger.debug('trying to resolve %s', mailStripped)
        identityId = resolve_identity_as_id(mailStripped, organization)
        logger.debug('got id as %s', identityId)
        idList.append(identityId)

    return idList