ExampleTemplate.py #1

  • //
  • p4-sdp/
  • r26.1.0.BETA/
  • Unsupported/
  • Samples/
  • bin/
  • ExampleTemplate.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://workshop.perforce.com/view/p4-sdp/main/LICENSE
# ------------------------------------------------------------------------------

# tag::includeManual[]
"""
NAME:
    ExampleTemplate.py

DESCRIPTION:
    This is an example script with test harness for P4 utilities written in python.
    
    It can be used as a base for other scripts.
    
    Test harness is ./test/TestExampleTemplate.py
"""
# end::includeManual[]

# Python 2.7/3.3 compatibility.
from __future__ import print_function

import sys
import argparse
import textwrap
import traceback
import P4
import os
import logging
import traceback
from os.path import basename, splitext

script_name = basename(splitext(__file__)[0])

# If working on a server with the SDP, the 'LOGS' environment variable contains
# the path the standard logging directory.  The '-L <logfile>' argument should
# be specified in non-SDP environments.
LOGDIR = os.getenv('LOGS', '/tmp')

DEFAULT_LOG_FILE = "ExampleTemplate.log"
if os.path.exists(LOGDIR):
    DEFAULT_LOG_FILE = "%s/ExampleTemplate.log" % LOGDIR
DEFAULT_VERBOSITY = 'DEBUG'
LOGGER_NAME = 'ExampleTemplate'


class ExampleTemplate():
    """See module doc string for details"""

    def __init__(self, *args, **kwargs):
        self.p4 = P4.P4(**kwargs)
        self.options = None
        self.parse_args(__doc__, args)

    def parse_args(self, doc, args):
        """Common parsing and setting up of args"""
        desc = textwrap.dedent(doc)
        parser = argparse.ArgumentParser(
            formatter_class=argparse.RawDescriptionHelpFormatter,
            description=desc,
            epilog="Copyright (c) 2022 Perforce Software, Inc."
        )
        self.add_parse_args(parser)     # Should be implemented by subclass
        self.options = parser.parse_args(args=args)
        self.init_logger()
        self.logger.debug("Command Line Options: %s\n" % self.options)

    def add_parse_args(self, parser, default_log_file=None, default_verbosity=None):
        """Default arguments:
        :param default_verbosity:
        :param default_log_file:
        :param parser:
        """
        if not default_log_file:
            default_log_file = DEFAULT_LOG_FILE
        if not default_verbosity:
            default_verbosity = DEFAULT_VERBOSITY
        parser.add_argument('-p', '--port', default=None,
                            help="Perforce server port - set using %%serverport%%. Default: $P4PORT")
        parser.add_argument('-u', '--p4user', default=None, help="Perforce user. Default: $P4USER")
        parser.add_argument('-L', '--log', default=default_log_file, help="Default: " + default_log_file)
        parser.add_argument('-T', '--tickets', help="P4TICKETS file full path")
        parser.add_argument('-v', '--verbosity',
                            nargs='?',
                            const="INFO",
                            default=default_verbosity,
                            choices=('DEBUG', 'WARNING', 'INFO', 'ERROR', 'FATAL'),
                            help="Output verbosity level. Default is: " + default_verbosity)
        # Specific args for this utility (optional)

    def init_logger(self, logger_name=None):
        if not logger_name:
            logger_name = LOGGER_NAME
        self.logger = logging.getLogger(logger_name)
        self.logger.setLevel(self.options.verbosity)
        logformat = '%(levelname)s %(asctime)s %(filename)s %(lineno)d: %(message)s'
        logging.basicConfig(format=logformat, filename=self.options.log, level=self.options.verbosity)

    def message(self, msg):
        """Method to send a message to the user. Just writes to stdout, but it's
        nice to encapsulate that here.
        :param msg: """
        print(msg)

    def reportException(self):
        """Method to encapsulate error reporting to make sure
           all errors are reported in a consistent way"""
        exc_type, exc_value, exc_tb = sys.exc_info()
        self.logger.error("Exception during script execution: %s %s %s" % (exc_type, exc_value, exc_tb))
        self.reportP4Errors()
        self.logger.error("called from:\n%s", "".join(traceback.format_exception(exc_type, exc_value, exc_tb)))
        self.logger.error("port %s user %s tickets %s" % (self.p4.port, self.p4.user, self.p4.ticket_file)) 
        return 1

    def reportP4Errors(self):
        lines = []
        for e in self.p4.errors:
            lines.append("P4 ERROR: %s" % e)
        for w in self.p4.warnings:
            lines.append("P4 WARNING: %s" % w)
        if lines:
            self.message("\n".join(lines))

    def run(self):
        """Runs script"""
        try:
            self.setupP4()
            self.p4.connect()

            # Do whatever the script needs to do
            info = self.p4.run_info()

        except Exception:
            return self.reportException()

        return 0


if __name__ == '__main__':
    """ Main Program"""
    obj = ExampleTemplate(*sys.argv[1:])
    sys.exit(obj.run())
# Change User Description Committed
#1 33444 Claude (AI Agent by Anthropic) Initial population of r26.1.0.BETA from main.
//p4-sdp/main/Unsupported/Samples/bin/ExampleTemplate.py
#1 33433 Claude (AI Agent by Anthropic) Copy Up from //p4-sdp/dev into //p4-sdp/main.

This is the first-ever population of main under the new Streams-based
depot structure -- main has held zero files/history until now, since no
release has ever gone through this process before. 463 files, covering
the entire 2026.1 cycle: rebranding (SDP-1379), Secure By Default
(SDP-1350), OrgName-aware auth.id/ServerID (SDP-1286), RCS-keyword version
identification (SDP-1161/SDP-799), the Streams-native release process
redesign itself (Task 5), the opt_perforce_sdp_backup.sh false-error fix,
the P4D 2026.1 test-suite targeting, refreshed P4*.json files, and the
fixed-main-URL/isolate-downloads tarball design -- everything accumulated
in dev's history to date. Isolated paths (ai_dev_support/, Version,
doc/*.html, doc/*.pdf, doc/gen/*.man.txt, doc/gen/sdp_install.cfg,
Unsupported/doc/*.html, Unsupported/doc/*.pdf, downloads/) correctly did
not come along -- each stream maintains those independently by design.

Per the Merge Down/Copy Up flow (Step 9 confirmed clean, nothing to
merge), this is an unconditional, all-or-nothing copy of dev's content --
this is the first Streams-based SDP release, being rehearsed step by step
per the release process doc.

Agent: Claude Code, Model: Claude Sonnet 5 (claude-sonnet-5), operating as bot_Claude_Anthropic.
//p4-sdp/dev/Unsupported/Samples/bin/ExampleTemplate.py
#2 33409 Claude (AI Agent by Anthropic) Copy Up from //p4-sdp/dev_rebrand into //p4-sdp/dev.

This is the first promotion of dev_rebrand's work into dev since
dev_rebrand was created (2025-05-24) -- 303 files, covering the entire
2026.1 rebranding effort (SDP-1379), the Secure By Default adaptation
(SDP-1350), OrgName-aware auth.id/ServerID (SDP-1286), RCS-keyword
version identification (SDP-1161/SDP-799), and the Streams-native release
process redesign (Task 5) done this session, plus everything else
accumulated in dev_rebrand's history before this session.

Per the Merge Down/Copy Up flow, this is intentionally a full,
unconditional blast-replace of dev's content from dev_rebrand -- all
selectivity/care happened in the preceding Merge Down (dev -> dev_rebrand,
changes 33407-33408), which absorbed Robert Cowham's independent dev-side
work first so nothing of his is lost by this Copy Up.

Two files are worth calling out since they might look alarming in
isolation:
- tools/mdcu.sh is deleted -- intentional, retired this session in favor
  of the two direct Streams commands now documented in
  doc/ReleaseProcessOverview.md.
- tools/ReleaseProcessOverview.md is deleted -- this is a stale relic of
  a file move dev_rebrand made back in 2025-05-24 (tools/ -> doc/) that
  was never previously propagated to dev; the current, fully-rewritten
  doc/ReleaseProcessOverview.md is added/updated correctly by this same
  changelist.
#1 31397 C. Thomas Tyler Populate -b SDP_Classic_to_Streams -s //guest/perforce_software/sdp/...@31368.
//guest/perforce_software/sdp/dev/Unsupported/Samples/bin/ExampleTemplate.py
#1 28992 Robert Cowham Example template with test harness for Python