Previous Table of Contents Next
Perforce 2009.2: APIs for Scripting



Chapter 3
Introduction
P4Python, the Python interface to the Perforce API , enables you to write Python code that interacts with a Perforce server. P4Python enables your Python scripts to:
System Requirements
P4Python is supported on Windows, Linux, Solaris, OS X, and FreeBSD.
To build P4Python from source, your development machine must also have:
(If you get "unresolved symbol" errors when building or running P4Python, you probably used the wrong compiler or the wrong Perforce API build. )
Installing P4Python
Download P4Python from the Perforce web site downloads page. After downloading, you can either run the installer or build the interface from source, as described in the release notes packaged with P4Python.
Programming with P4Python
P4Python provides an object-oriented interface to Perforce that is intended to be intuitive for Python programmers. Data is loaded and returned in Python arrays and dictionaries. Each P4 object represents a connection to the Perforce Server.
When instantiated, the P4 instance is set up with the default environment settings just as the command line client p4, that is, using environment variables, the registry on Windows and, if defined, the P4CONFIG file. The settings can be checked and changed before the connection to the server is established with the connect() method. After your script connects, it can send multiple commands to the Perforce Server with the same P4 instance. After the script is finished, it should disconnect from the Server by calling the disconnect() method.
The following example illustrates the basic structure of a P4Python script. The example establishes a connection, issues a command, and tests for errors resulting from the command.
from P4 import P4,P4Exception    # Import the module
p4 = P4()                        # Create the P4 instance
p4.port = "1666"
p4.user = "fred"
p4.client = "fred-ws"            # Set some environment variables

try:                             # Catch exceptions with try/except
  p4.connect()                   # Connect to the Perforce Server
  info = p4.run("info")          # Run "p4 info" (returns a dict)
  for key in info[0]:            # and display all key-value pairs
    print key, "=", info[0][key]
  p4.run("edit", "file.txt")     # Run "p4 edit file.txt"
  p4.disconnect()                # Disconnect from the Server
except P4Exception:
  for e in p4.errors:            # Display errors
    print e
This example creates a client workspace from a template and syncs it:.
template = "my-client-template"
client_root = "C:\work\my-root"
p4 = P4()
try:
  p4.connect()
  # Convert client spec into a Python dictionary
  client = p4.fetch_client("-t", template)
  client._root = client_root
  p4.save_client(client)
  p4.run_sync()
except P4Exception:
  # If any errors occur, we'll jump in here. Just log them
  # and raise the exception up to the higher level
Submitting a Changelist
This example creates a changelist, modifies it and then submits it:.
p4 = P4()
p4.connect()
change = p4.fetch_change()
# Files were opened elsewhere and we want to
# submit a subset that we already know about.
myfiles = ['//depot/some/path/file1.c', '//depot/some/path/file1.h']
change._description = "My changelist\nSubmitted from P4Python\n"
change._files = myfiles   # This attribute takes a Python list
Logging into Perforce using ticket-based authentication
On some servers, users might need to log in to Perforce before issuing commands. The following example illustrates login using Perforce tickets.
p4 = P4()
p4.user = "Sven"
p4.password = "my_password"
p4.connect()
p4.run_login()
opened = p4.run_opened()
Changing your password
You can use P4Python to change your password, as shown in the following example:
p4 = P4()
p4.user = "Sven"
p4.password = "MyOldPassword"
p4.connect()
Timestamp conversion
Timestamp information in P4Python is normally represented as seconds since Epoch (with the exception of P4.Revision). To convert this data to a more useful format, use the following procedure:
 
P4Python Classes
The P4 module consists of several public classes:
The following tables provide more details about each public class.
P4
Perforce client class. Handles connection and interaction with the Perforce server. There is one instance of each connection.
The following table lists attributes of the class P4 in P4Python. The attributes are readable and writable unless indicated otherwise. The attributes can be strings, objects, or integers.
P4CLIENT, the name of the client workspace to use.
P4HOST, the name of the host used
The location of the configuration file used (P4CONFIG). This attribute is read-only.
P4PASSWD, the password used.
P4PORT, the port used for the connection
To disable tagged output for the following commands, set the value to 0 or False. By default, tagged output is enabled.
P4TICKETS, the ticket file location used
P4USER, the user under which the connection is run
The following table lists all public methods of the class P4. Many methods are wrappers around P4.run(), which sends a command to the Perforce Server. Such methods are provided for your convenience.
In the context of a with statement, temporarily set the exception level for the duration of a block.
delete_spectype()
Deletes the spec spectype. Equivalent to the command P4.run("spectype", "-d").
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows) the registry.
fetch_spectype()
Fetches the spec spectype. Equivalent to the command P4.run("spectype", "-o").
format_spectype()
Converts the spec spectype into a string.
parse_spectype()
Parses a string representation of the spec spectype and returns a dictionary.
run_command()
Runs the command command. Equivalent to P4.run("command").
This command returns a list of DepotFile objects. Specialization for the run() command.
Convenience method: updates the password. Takes two arguments: oldpassword, newpassword
Interface to p4 resolve.
Convenience method for submitting changelists. When invoked with a change spec, it submits the spec. Equivalent to :
p4.input = myspec
p4.run("submit", "-i")
save_spectype()
Saves the spec spectype. Equivalent to the command P4.run("spectype", "-i").
In the context of a with statement, temporarily toggle tagged behavior for the duration of a block.
P4.P4Exception
Exception class. Instances of this class are raised when errors and/or (depending on the exception_level setting) warnings are returned by the server. The exception contains the errors in the form of a string. P4Exception is a subclass of the standard Python Exception class.
P4.DepotFile
Container class returned by P4.run_filelog(). Contains the name of the depot file and a list of P4.Revision objects.
P4.Revision
Container class containing one revision of a DepotFile object.
List of P4.Integration objects
Timestamp (as datetime.datetime object)
P4.Integration
Container class containing one integration for a Revision object
P4.Map
A class that allows users to create and work with Perforce mappings without requiring a connection to the Perforce Server.
P4.MergeData
Class encapsulating the context of an individual merge during execution of a p4 resolve command. Passed to P4.run_resolve.
Returns the path of "their" file in the merge. (temporary file on workstation into which their_name has been loaded)
Returns the path of the base file in the merge. (temporary file on workstation into which base_name has been loaded)
Returns the path to the merge result. (temporary file on workstation into which the automatic merge performed by the server has been loaded)
The MergeData class also has one method:
If the environment variable P4MERGE is defined, run it and return a boolean based on the return value of that program
P4.Resolver
Class for handling resolves in Perforce.
P4.Spec
Class allowing access to the fields in a Perforce specification form.
spec._fieldname
Class P4
Description
Main interface to the Python client API.
This module provides an object-oriented interface to the Perforce SCM system. Data is returned in Python arrays and dictionaries (hashes) and input can also be supplied in these formats.
Each P4 object represents a connection to the Perforce Server, and multiple commands may be executed (serially) over a single connection (which of itself can result in substantially improved performance if executing long sequences of Perforce commands).
1.
2.
3.
4.
5.
6.
Instance Attributes
p4.api_level -> int
Contains the API compatibility level desired. This is useful when writing scripts using Perforce commands that do not yet support tagged output. In these cases, upgrading to a later server that supports tagged output for the commands in question can break your script. Using this method allows you to lock your script to the output format of an older Perforce release and facilitate seamless upgrades. Must be called before calling P4.connect().
from P4 import P4
p4 = P4()
p4.api_level = 57 # Lock to 2005.1 format
p4.connect()
...
p4.disconnect
For the API integer levels that correspond to each Perforce release, see:
http://kb.perforce.com/?article=512
p4.charset -> string
Contains the character set to use when connect to a Unicode enabled server. Do not use when working with non-Unicode-enabled servers. By default, the character set is the value of the P4CHARSET environment variable. If the character set is invalid, this method raises a P4Exception.
from P4 import P4
p4 = P4()
p4.client = "www"
p4.charset = "iso8859-1"
p4.connect()
p4.run_sync()
p4.disconnect()
p4.client -> string
Contains the name of your client workspace. By default, this is the value of the P4CLIENT taken from any P4CONFIG file present, or from the environment according to the normal Perforce conventions.
p4.cwd -> string
Contains the current working directly. Can be called prior to executing any Perforce command. Sometimes necessary if your script executes a chdir() as part of its processing.
from P4 import P4
p4 = P4()
p4.cwd = "/home/sven"
p4.errors -> list (read-only)
Returns an array containing the error messages received during execution of the last command.
try:
  p4.connect()
  p4.exception_level = 1    # ignore "File(s) up-to-date"
  files = p4.run_sync()
except P4Exception:
  for e in p4.errors:
    print e
finally:
  p4.disconnect()
p4.exception_level -> int
Configures the events which give rise to exceptions. The following three levels are supported:
0 disables all exception handling and makes the interface completely procedural; you are responsible for checking the p4.errors and p4.warnings arrays.
For example
from P4 import P4
p4 = P4()
p4.exception_level = 1
p4.connect()   # P4Exception on failure
p4.run_sync()  # File(s) up-to-date is a warning - no exception raised
p4.disconnect()
p4.host -> string
Contains the name of the current host. It defaults to the value of P4HOST taken from any P4CONFIG file present, or from the environment as per the usual Perforce convention. Must be called before connecting to the Perforce server.
from P4 import P4
p4 = P4()
p4.host = "workstation123.perforce.com"
p4.connect()
...
p4.disconnect()
p4.input -> string | dict | list
Contains input for the next command.
Set this attribute prior to running a command that requires input from the user. When the command requests input, the specified data is supplied to the command. Typically, commands of the form p4 cmd -i are invoked using the P4.save_spectype methods, which retrieve the value from p4.input internally; there is no need to set p4.input when using the P4.save_spectype shortcuts.
You may pass a string, a hash, or (for commands that take multiple inputs from the user) an array of strings or hashes. If you pass an array, note that the first element of the array will be popped each time Perforce asks the user for input.
For example, the following code supplies a description for the default changelist and then submits it to the depot:
from P4 import P4
p4 = P4()
p4.connect()
change = p4.run_change( "-o" )[0]
change[ "Description" ] = "Autosubmitted changelist"
p4.input = change
p4.run_submit( "-i" )
p4.disconnect()
p4.maxlocktime -> int
Limit the amount of time (in milliseconds) spent during data scans to prevent the server from locking tables for too long. Commands that take longer than the limit will be aborted. The limit remains in force until you disable it by setting it to zero. See p4 help maxlocktime for information on the commands that support this limit.
p4.maxresults -> int
Limit the number of results Perforce permits for subsequent commands. Commands that produce more than this number of results will be aborted. The limit remains in force until you disable it by setting it to zero. See p4 help maxresults for information on the commands that support this limit.
p4.maxscanrows -> int
Limit the number of database records Perforce scans for subsequent commands. Commands that attempt to scan more than this number of records will be aborted. The limit remains in force until you disable it by setting it to zero. See p4 help maxscanrows for information on the commands that support this limit.
p4.p4config_file -> string (read-only)
Contains the name of the current P4CONFIG file, if any. This attribute cannot be set.
p4.password -> string
Contains your Perforce password or login ticket. If not used, takes the value of P4PASSWD from any P4CONFIG file in effect, or from the environment according to the normal Perforce conventions.
This password is also used if you later call p4.run_login() to log in using the 2003.2 and later ticket system. After running p4.run_login(), the attribute contains the ticket the allocated by the server.
from P4 import P4
p4 = P4()
p4.password = "mypass"
p4.connect()
p4.run_login()
p4.port -> string
Contains the host and port of the Perforce server to which you want to connect. It defaults to the value of P4PORT in any P4CONFIG file in effect, and then to the value of P4PORT taken from the environment.
from P4 import P4
p4 = P4()
p4.port = "localhost:1666"
p4.connect()
...
p4.prog -> string
Contains the name of the program, as reported to Perforce system administrators running p4 monitor show -e. The default is unnamed p4-python script
from P4 import P4
p4 = P4()
p4.prog = "sync-script"
puts( p4.prog )
p4.connect
...
p4.server_level -> int (read-only)
Returns the current Perforce server level. Each iteration of the Perforce Server is given a level number. As part of the initial communication this value is passed between the client application and the Perforce Server. This value is used to determine the communication that the Perforce Server will understand. All subsequent requests can therefore be tailored to meet the requirements of this Server level.
This attribute is 0 before the first command is run, and is set automatically after the first communication with the server.
For the API integer levels that correspond to each Perforce release, see:
http://kb.perforce.com/?article=571
p4.tagged -> int
If 1 or True, p4.tagged enables tagged output. By default, tagged output is on.
from P4 import P4
p4 = P4()
p4.tagged = False
print p4.tagged
p4.ticket_file -> string
Contains the location of the P4TICKETS file
p4.user -> string
Contains the Perforce username. It defaults to the value of P4USER taken from any P4CONFIG file present, or from the environment as per the usual Perforce convention.
from P4 import P4
p4 = P4()
p4.user = "sven"
p4.connect()
...
p4.disconnect()
p4.version -> string
Contains the version of the program, as reported to Perforce system administrators in the server log.
from P4 import P4
p4 = P4()
p4.version = "123"
puts( p4.version )
p4.connect
...
p4.warnings -> list (read-only)
Contains the array of warnings that arose during execution of the last command
try:
  p4.connect()
  p4.exception_level = 2 # File(s) up-to-date is a warning
  files = p4.run_sync()
except P4Exception, ex:
  for w in p4.warnings:
    print w
finally:
  p4.disconnect()
Class Methods
P4.P4()
Construct a new P4 object. For example:
P4.identify()
Return the version of P4Python that you are using.
Instance Methods
p4.at_exception_level()
In the context of a with statement, temporarily set the exception level for a block. For example:
from P4 import P4
p4 = P4()
p4.connect()
with p4.at_exception_level(P4.RAISE_ERROR):
  # no exceptions for warnings
  p4.run_sync("//depot/main/...")
p4.connect()
Initializes the Perforce client and connects to the server.
If the connection is successfully established, returns None. If the connection fails and exception_level is 0, returns False, otherwise raises a P4Exception. If already connected, prints a message.
from P4 import P4
p4 = P4()
p4.connect()
...
p4.disconnect()
P4.connect returns a context management object that is usable with a with statement within a block; after the block is finished, the connection is automatically disconnected:
import P4
p4 = P4.P4()
with p4.connect():
  # block in context of connection
  ...
p4.connected() -> boolean
Returns true if connected to the Perforce Server and the connection is alive, otherwise false.
print p4.connected()
p4.connect()
print p4.connected()
p4.delete_<spectype>( [ options ], name ) -> list
The delete_spectype methods are shortcut methods that allow you to delete the definitions of clients, labels, branches, etc. These methods are equivalent to:
p4.run( <spectype>, '-d', [options], <spec name> )
The following code uses delete_client to delete client workspaces that have not been accessed in more than 365 days:
from P4 import P4, P4Exception
from datetime import datetime, timedelta
try:
  p4.connect()
  for client in p4.run_clients():
    atime = datetime.utcfromtimestamp( int( client[ "Access" ] ) )
    # If the client has not been accessed for a year, delete it
    if ( atime + timedelta(365) ) < now :
      p4.delete_client( '-f', client[ "client" ] )
except P4Exception:
  for e in p4.errors:
    print e
finally:
  p4.disconnect()
p4.disconnect()
Disconnect from the Perforce Server. Call this method before exiting your script.
p4.connect()
...
p4.disconnect()
p4.env( var )
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows) the registry.
p4.fetch_<spectype>() -> P4.Spec
The fetch_spectype methods are shortcuts for running p4.run("spectype", "-o").pop(0). For example:
label      = p4.fetch_label(labelname)
change     = p4.fetch_change(changeno)
clientspec = p4.fetch_client(clientname)
are equivalent to
label      = p4.run("label", "-o", labelname)[0]
change     = p4.run("change", "-o", changeno)[0]
clientspec = p4.run("client", "-o", clientname)[0]
p4.format_spec( <spectype>, dict ) -> string
Converts the fields in the dict containing the elements of a Perforce form (spec) into the string representation familiar to users. The first argument is the type of spec to format: for example, client, branch, label, and so on. The second argument is the hash to parse.
There are shortcuts available for this method. You can use p4.format_spectype( dict ) instead of p4.format_spec( spectype, dict ), where spectype is the name of a Perforce spec, such as client, label, etc.
p4.format_<spectype>( dict ) -> string
The format_spectype methods are shortcut methods that allow you to quickly fetch the definitions of clients, labels, branches, etc. They're equivalent to:
p4.format_spec( spectype, dict )
p4.parse_spec( <spectype>, string ) -> P4.Spec
Parses a Perforce form (spec) in text form into a Python dict using the spec definition obtained from the server. The first argument is the type of spec to parse: client, branch, label, and so on. The second argument is the string buffer to parse.
There are shortcuts available for this method. You can use:
p4.parse_spectype( buf )
instead of
p4.parse_spec( spectype, buf )
where spectype is one of client, branch, label, and so on.
p4.parse_<spectype>( string ) -> P4.Spec
This is equivalent to parse_spec( spectype, string ).
For example, parse_job(myJob) converts the String representation of a job spec into a Spec object.
To parse a spec, P4 needs to have the spec available. When not connected to the Perforce Server, P4 assumes the default format for the spec, which is hardcoded. This assumption can fail for jobs if the Server's jobspec has been modified. In this case, your script can load a job from the Server first with the command fetch_job('somename'), andP4 will cache and use the spec format in subsequent parse_job() calls.
p4.run(cmd, [arg, ...])
Base interface to all the run methods in this API. Runs the specified Perforce command with the arguments supplied. Arguments may be in any form as long as they can be converted to strings by str().
The p4.run() method returns a list of results whether the command succeeds or fails; the list may, however, be empty. Whether the elements of the array are strings or dictionaries depends on
(a) server support for tagged output for the command, and
(b) whether tagged output was disabled by calling p4.tagged = False.
In the event of errors or warnings, and depending on the exception level in force at the time, run() raises a P4Exception. If the current exception level is below the threshold for the error/warning, run() returns the output as normal and the caller must explicitly review p4.errors and p4.warnings to check for errors or warnings.
from P4 import P4
p4 = P4()
p4.connect()
spec = p4.run( "client", "-o" )[0]
p4.disconnect()
Shortcuts are available for p4.run. For example, p4.run_command( args ) is equivalent to p4.run( "command", args )
There are also some shortcuts for common commands such as editing Perforce forms and submitting. For example, this:
from P4 import P4
p4 = P4()
p4.connect()
clientspec = p4.run_client( "-o" ).pop(0)
clientspec[ "Description" ] = "Build client"
p4.input = clientspec
p4.run_client( "-i" )
p4.disconnect()
...may be shortened to
from P4 import P4
p4 = P4()
p4.connect()
clientspec = p4.fetch_client()
clientspec[ "Description" ] = "Build client"
p4.save_client( clientspec )
p4.disconnect()
The following are equivalent:
As the commands associated with fetch_spectype typically return only one item, these methods do not return an array, but instead return the first result element.
For convenience in submitting changelists, changes returned by fetch_change() can be passed to run_submit(). For example:
from P4 import P4
p4 = P4()
p4.connect()
spec = p4.fetch_change()
spec[ "Description" ] = "Automated change"
p4.run_submit( spec )
p4.disconnect
p4.run_<cmd>()
Shorthand for p4.run("cmd", arguments... )
p4.run_filelog(<fileSpec >) -> list
Runs a p4 filelog on the fileSpec provided and returns an array of P4.DepotFile results (when executed in tagged mode), or an array of strings when executed in nontagged mode. By default, the raw output of p4 filelog is tagged; this method restructures the output into a more user-friendly (and object-oriented) form.
For example:
try:
  p4.connect()
  for r in p4.run_filelog( "index.html" )[0].revisions:
    for i in r.integrations:
      # Do something
except P4Exception:
  for e in p4.errors:
    print e
finally:
  p4.disconnect()
p4.run_login( arg... ) -> list
Runs p4_login using a password (or other arguments) set by the user.
p4.run_password( oldpass, newpass ) -> list
A thin wrapper to make it easy to change your password. This method is (literally) equivalent to the following:
For example
from P4 import P4, P4Exception
p4 = P4()
p4.password = "myoldpass"
try:
  p4.connect()
  p4.run_password( "myoldpass", "mynewpass" )
except P4Exception:
  for e in p4.errors:
    print e
finally:
  p4.disconnect()
p4.run_resolve( [resolver], [arg...] ) -> list
Run a p4 resolve command. Interactive resolves require the resolver parameter to be an object of a class derived from P4.Resolver. In these cases, the resolve method of this class is called to handle the resolve. For example:
To perform an automated merge that skips whenever conflicts are detected:
class MyResolver(P4.Resolver):
  def resolve(self, mergeData):
    if not mergeData.merge_hint == "e":
       return mergeData.merge_hint
    else:
       return "s" # skip the resolve, there is a conflict
In non-interactive resolves, no P4.Resolver object is required. For example:
p4.run_submit( [ hash ], [ arg... ] ) -> list
Submit a changelist to the server. To submit a changelist, set the fields of the changelist as required and supply any flags:
change = p4.fetch_change()
change._description = "Some description"
p4.run_submit( "-r", change )
You can also submit a changelist by supplying the arguments as you would on the command line:
p4.save_<spectype>()>
The save_spectype methods are shortcut methods that allow you to quickly update the definitions of clients, labels, branches, etc. They are equivalent to:
p4.input = dictOrString
p4.run( spectype, "-i" )
For example:
try:
  p4.connect()
  client = p4.fetch_client()
  client[ "Owner" ] = p4.user
  p4.save_client( client )
except P4Exception:
  for e in p4.errors:
    print e
finally:
  p4.disconnect()
p4.server_case_sensitive() -> boolean
Detects whether or not the server is case-sensitive. Cannot be called until a command has been issued to the server.
p4.while_tagged( boolean )
In the context of a with statement, enable or disable tagged behavior for the duration of a block. For example:
from P4 import P4
p4 = P4()
p4.connect()
with p4.while_tagged(False):
# tagged output disabled for this block
  print p4.run_info()
 
Class P4.P4Exception
Description
Instances of this class are raised when P4 encounters an error or a warning from the server. The exception contains the errors in the form of a string. P4Exception is a shallow subclass of the standard Python Exception class.
Class Attributes
None.
Class Methods
None.
Class P4.DepotFile
Description
Utility class providing easy access to the attributes of a file in a Perforce depot. Each P4.DepotFile object contains summary information about the file and a list of revisions (P4.Revision objects) of that file. Currently, only the P4.run_filelog method returns a list of P4.DepotFile objects.
Instance Attributes
df.depotFile -> string
Returns the name of the depot file to which this object refers.
df.revisions -> list
Returns a list of P4.Revision objects, one for each revision of the depot file.
Class Methods
None.
Instance Methods
None.
 
Class P4.Revision
Description
Utility class providing easy access to the revisions of P4.DepotFile objects. Created by P4.run_filelog().
Instance Attributes
rev.action -> string
Returns the name of the action which gave rise to this revision of the file.
rev.change -> int
Returns the change number that gave rise to this revision of the file.
rev.client -> string
Returns the name of the client from which this revision was submitted.
rev.depotFile -> string
Returns the name of the depot file to which this object refers.
rev.desc -> string
Returns the description of the change which created this revision. Note that only the first 31 characters are returned unless you use p4 filelog -L for the first 250 characters, or p4 filelog -l for the full text.
rev.digest -> string
Returns the MD5 checksum of this revision.
rev.fileSize -> string
Returns this revision's size in bytes.
rev.integrations -> list
Returns the list of P4.Integration objects for this revision.
rev.rev -> int
Returns the number of this revision of the file.
rev.time -> datetime
Returns the date/time that this revision was created.
rev.type -> string
Returns this revision's Perforce filetype.
rev.user -> string
Returns the name of the user who created this revision.
Class Methods
None.
Instance Methods
None.
Class P4.Integration
Description
Utility class providing easy access to the details of an integration record. Created by P4.run_filelog().
Instance Attributes
integ.how -> string
Returns the type of the integration record - how that record was created.
integ.file -> string
Returns the path to the file being integrated to/from.
integ.srev -> int
Returns the start revision number used for this integration.
integ.erev -> int
Returns the end revision number used for this integration.
Class Methods
None.
Instance Methods
None.
Class P4.Map
Description
The P4.Map class allows users to create and work with Perforce mappings, without requiring a connection to a Perforce server.
Instance Attributes
None
Class Methods
P4.Map( [ list ] ) -> P4.Map
Constructs a new P4.Map object.
P4.Map.join ( map1, map2 ) -> P4.Map
Join two P4.Map objects and create a third.
The new map is composed of the left-hand side of the first mapping, as joined to the right-hand side of the second mapping. For example:
# Map depot syntax to client syntax
client_map = P4.Map()
client_map.insert( "//depot/main/...", "//client/..." )
# Map client syntax to local syntax
client_root = P4.Map()
client_root.insert( "//client/...", "/home/tony/workspace/..." )
# Join the previous mappings to map depot syntax to local syntax
local_map = P4.Map.join( client_map, client_root )
local_path = local_map.translate( "//depot/main/www/index.html" )
Instance Methods
map.clear()
Empty a map.
map.count() -> int
Return the number of entries in a map.
map.is_empty() -> boolean
Test whether a map object is empty.
map.insert( string ... )
Inserts an entry into the map.
May be called with one or two arguments. If called with one argument, the string is assumed to be a string containing either a half-map, or a string containing both halves of the mapping. In this form, mappings with embedded spaces must be quoted. If called with two arguments, each argument is assumed to be half of the mapping, and quotes are optional.
# called with two arguments:
map.insert( "//depot/main/...", "//client/..." )
# called with one argument containing both halves of the mapping:
map.insert( "//depot/live/... //client/live/..." )
# called with one argument containing a half-map:
# This call produces the mapping "depot/... depot/..."
map.insert( "depot/..." )
map.translate ( string, [ boolean ] )-> string
Translate a string through a map, and return the result. If the optional second argument is 1, translate forward, and if it is 0, translate in the reverse direction. By default, translation is in the forward direction.
map.includes( string ) -> boolean
Tests whether a path is mapped or not.
map.reverse() -> P4.Map
Return a new P4.Map object with the left and right sides of the mapping swapped. The original object is unchanged.
map.lhs() -> list
Returns the left side of a mapping as an array.
map.rhs() -> list
Returns the right side of a mapping as an array.
map.as_array() -> list
Returns the map as an array.
Class P4.MergeData
Description
Class containing the context for an individual merge during execution of a p4 resolve.
Instance Attributes
md.your_name -> string
Returns the name of "your" file in the merge. This is typically a path to a file in the workspace.
md.their_name -> string
Returns the name of "their" file in the merge. This is typically a path to a file in the depot.
md.base_name -> string
Returns the name of the "base" file in the merge. This is typically a path to a file in the depot.
md.your_path -> string
Returns the path of "your" file in the merge. This is typically a path to a file in the workspace.
md.their_path -> string
Returns the path of "their" file in the merge. This is typically a path to a temporary file on your local machine in which the contents of their_name have been loaded.
md.base_path -> string
Returns the path of the base file in the merge. This is typically a path to a temporary file on your local machine in which the contents of base_name have been loaded.
md.result_path -> string
Returns the path to the merge result. This is typically a path to a temporary file on your local machine in which the contents of the automatic merge performed by the server have been loaded.
md.merge_hint -> string
Returns the hint from the server as to how it thinks you might best resolve this merge.
Instance Methods
md.run_merge() -> boolean
If the environment variable P4MERGE is defined, run_merge() invokes the specified program and returns a boolean based on the return value of that program.
Class P4.Resolver
Description
P4.Resolver is a class for handling resolves in Perforce. It is intended to be subclassed, and for subclasses to override the resolve() method. When P4.run_resolve() is called with a P4.Resolver object, it calls the resolve() method of the object once for each scheduled resolve.
Instance Attributes
None
Class Methods
None
Instance Methods
resolver.resolve(self, mergeData) -> string
Returns the resolve decision as a string. The standard Perforce resolve strings apply:
By default, all automatic merges are accepted, and all merges with conflicts are skipped. The resolve method is called with a single parameter, which is a reference to a P4.MergeData object.
Class P4.Spec
Description
Utility class providing easy access to the attributes of the fields in a Perforce form.
Only valid field names may be set in a P4.Spec object. Only the field name is validated, not the content. Attributes provide easy access to the fields.
Instance Attributes
spec._<fieldname> -> string
Contains the value associated with the field named <fieldname>.
spec.permitted_fields -> dict
Contains an array containing the names of fields that are valid in this spec object. This does not imply that values for all of these fields are actually set in this object, merely that you may choose to set values for any of these fields if you want to.
Class Methods
P4.Spec.new( dict ) ->P4.Spec
Constructs a new P4.Spec object given an array of valid fieldnames.
Instance Methods
None.


Previous Table of Contents Next

Perforce 2009.2: APIs for Scripting
Copyright 2008-2009 Perforce Software.