CheckFixes.py #2

  • //
  • guest/
  • perforce_software/
  • sdp/
  • dev/
  • Server/
  • Unix/
  • p4/
  • common/
  • bin/
  • triggers/
  • CheckFixes.py
  • View
  • Commits
  • Open Download .zip Download (5 KB)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# ==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Server Deployment Package (SDP), and also available online:
# https://swarm.workshop.perforce.com/projects/perforce-software-sdp/view/main/LICENSE
# ------------------------------------------------------------------------------

"""
NAME:
    CheckFixes.py

DESCRIPTION:
    This trigger is intended for use with P4DTG (Defect Tracking Replication) installations.

    It will allows fixes to be added or deleted depending on the values of job fields.
    Thus you can control workflow and disallow fixes if jobs are in a particular state.
    So if the field JiraStatus is closed, then you are not allowed to add or delete a fix.

    To install, add a line to your Perforce triggers table like the following:

        check-fixes fix-add //... "python /p4/common/bin/triggers/CheckFixes.py -p %serverport% -u perforce %change% "
        check-fixes fix-delete //... "python /p4/common/bin/triggers/CheckFixes.py -p %serverport% -u perforce %change% "

    or (if server is standard SDP and has appropriate environment defaults for P4PORT and P4USER):

        check-fixes fix-add //... "python /p4/common/bin/triggers/CheckFixes.py %change% "
        check-fixes fix-delete //... "python /p4/common/bin/triggers/CheckFixes.py %change% "

    You may need to provide the full path to python executable, or edit the path to the trigger.

    Also, don't forget to make the file executable.

    To configure, read and modify the following lines up to the comment that
    reads "END OF CONFIGURATION BLOCK".  You may also need to modify the
    definition of which fields constitute a new job based on your jobspec.  This
    is in the allowed_job() function.
"""

# Python 2.7/3.3 compatibility.
from __future__ import print_function

import sys
import re
import argparse
import textwrap
import P4Triggers
import shutil
import os
import yaml

class CheckFixes(P4Triggers.P4Trigger):
    """See module doc string for details"""

    def __init__(self, *args, **kwargs):
        P4Triggers.P4Trigger.__init__(self, **kwargs)
        self.parse_args(__doc__, args)

    def add_parse_args(self, parser):
        """Specific args for this trigger - also calls super class to add common trigger args"""
        parser.add_argument('-c', '--config-file', default=None,
                            help="Configuration file for trigger. Default: CheckFixes.yaml")
        parser.add_argument('-d', '--delete', default=False, action="store_true",
                            help="Whether this is Fix-Delete trigger. Default: False so Fix-Add assumed")
        parser.add_argument('change', help="User carrying out the command - %%user%% argument from triggers entry.")
        parser.add_argument('jobs', nargs='+',
                            help="List of jobs - %%jobs%% argument from triggers entry.")
        super(CheckFixes, self).add_parse_args(parser)

    def load_config(self, config_file=None):
        if not config_file:
            config_file = "/p4/common/config/CheckFixes.yaml"
        config = {}
        try:
            with open(config_file, 'r') as f:
                config = yaml.load(f)
        except Exception as e:
            self.logger.error(str(e))
        return config

    def run(self):
        """Runs trigger"""
        try:
            self.logger.debug("CheckFixes firing")
            config = self.load_config(self.options.config_file)
            errors = []
            for k in "fix_state_field fix_allowed_states msg_cant_link_jobs".split():
                if k not in config:
                    errors.append("Config file %s missing definition for %s" %
                                  (self.options.config_file, k))
            if errors:
                msg = "Invalid config file for trigger" + str(errors) + "\n"
                self.message(msg)
                return 1

            self.setupP4()
            self.p4.connect()

            jobs = []
            for jobname in self.options.jobs:
                jobs.append(self.p4.fetch_job(jobname))

            errors = []
            for job in jobs:
                if job[config['fix_state_field']] not in config['fix_allowed_states']:
                    errors.append("Job %s has state '%s'" %
                                  (job['Job'], job[config['fix_state_field']]))

            if errors:
                err_msg = "\n".join(config['msg_cant_link_jobs'])
                msg = err_msg + str(errors) + "\n\n"
                self.message(msg)
                return 1
        except Exception:
            return self.reportException()

        return 0


if __name__ == '__main__':
    """ Main Program"""
    trigger = CheckFixes(*sys.argv[1:])
    sys.exit(trigger.run())
# Change User Description Committed
#12 26652 Robert Cowham This is Tom's change:

Introduced new 'Unsupported' directory to clarify that some files
in the SDP are not officially supported. These files are samples for
illustration, to provide examples, or are deprecated but not yet
ready for removal from the package.

The Maintenance and many SDP triggers have been moved under here,
along with other SDP scripts and triggers.

Added comments to p4_vars indicating that it should not be edited
directly. Added reference to an optional site_global_vars file that,
if it exists, will be sourced to provide global user settings
without needing to edit p4_vars.

As an exception to the refactoring, the totalusers.py Maintenance
script will be moved to indicate that it is supported.

Removed settings to support long-sunset P4Web from supported structure.

Structure under new .../Unsupported folder is:
   Samples/bin             Sample scripts.
   Samples/triggers        Sample trigger scripts.
   Samples/triggers/tests  Sample trigger script tests.
   Samples/broker          Sample broker filter scripts.
   Deprecated/triggers     Deprecated triggers.

To Do in a subsequent change: Make corresponding doc changes.
#11 24158 Robert Cowham Refactor - tidy up triggers to make a little more consistent.
No functional change.
#10 23830 Robert Cowham Refactor and move detection of shelved change up to P4Triggers.
Also WorkflowTriggers
#9 23670 Robert Cowham Properly test CheckFixes when no matching project found.
#8 23558 Robert Cowham Allow fixes to be deleted for pending changes
Refactored tests a little.
#7 23553 Robert Cowham Cope with default jobs
#6 23528 Robert Cowham Handled default change
#5 23527 Robert Cowham Add a config option fix_allowed_paths per project for CheckFixes.py
#4 23241 Robert Cowham New triggers with tests
#3 23161 Robert Cowham Tweak error message
#2 23157 Robert Cowham Move configuration to a yaml file
#1 23156 Robert Cowham Initial tests for CheckFixes