Previous Table of Contents Next
Perforce 2009.1: APIs for Scripting



Chapter 2
Introduction
P4Perl is a Perl module that provides an object-oriented API to the Perforce SCM system. Using P4Perl is faster than using the command-line interface in scripts, because multiple command can be executed on a single connection, and because it returns the Perforce Server's responses as Perl hashes and arrays.
The main features are:
System Requirements
P4Perl is supported on Windows, Linux, Solaris, and FreeBSD. To build P4Perl, your development machine must also have:
make (or nmake on Windows)
(If you get "unresolved symbol" errors when building or running P4Perl, you probably used the wrong compiler or the wrong Perforce API build. )
Installing P4Perl
Download P4Perl 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.
Programming with P4Perl
The following example shows how to connect to a Perforce server, run a p4 info command, and open a file for edit.
use P4;
my $p4 = new P4;
$p4->SetClient( $clientname );
$p4->SetPort ( $p4port );
$p4->SetPassword( $p4password );
$p4->Connect() or die( "Failed to connect to Perforce Server" );

my $info = $p4->Run( "info" );
$p4->RunEdit( "file.txt" );
die( "Failed to edit file.txt" ) if $p4->ErrorCount()
   || $p4->WarningCount;
$p4->Disconnect();
P4Perl Classes
The P4 module consists of several public classes:
The following tables provide brief details about each public class.
P4
The main class used for executing Perforce commands. Almost everything you do with P4Perl will involve this class.
Shorthand for running
$p4->Run( "spectype", "-o" )
Shorthand for running
$p4->FormatSpec( <spectype>, hash )
Converts a Perforce form of the specified type (client/label etc.) held in the supplied hash into its string representation.
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows) the registry.
Shorthand for running
$p4-ParseSpec( <spectype>, buffer )
Converts a Perforce form of the specified type (client/label etc.) held in the supplied string into a hash and returns a reference to that hash
Shorthand for running
$p4-Run (cmd, arg, ...)
Runs a p4 filelog on the fileSpec provided and returns an array of P4::DepotFile objects
Runs p4 login using a password (or other arguments) set by the user.
Interface to p4 resolve.
Shorthand for
$p4->SetInput( $spectype );
$p4->Run( "spectype", "-i");
P4::DepotFile
Utility class allowing access to the attributes of a file in the depot. Returned by P4::RunFilelog.
P4::Revision
Utility class allowing access to the attributes of a revision of a file in the depot. Returned by P4::RunFilelog.
P4::Integration
Utility class allowing access to the attributes of an integration record for a revision of a file in the depot. Returned by P4::RunFilelog.
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::RunResolve.
Returns the path of "their" file in the merge. (temporary file on workstation into which TheirName() has been loaded)
Returns the path of the base file in the merge. (temporary file on workstation into which BaseName() 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)
If the environment variable P4MERGE is defined, run it and indicate whether or not the merge tool successfully executed.
P4::Resolver
Class for handling resolves in Perforce.
P4::Spec
Utility class allowing access to the attributes of the fields in a Perforce form.
_fieldname
_fieldname()
Class P4
Description
Main interface to the Perforce client API.
This module provides an object-oriented interface to the Perforce SCM system. Data is returned in Perl arrays and 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.
The basic model is to:
1.
2.
3.
4.
5.
Base methods
P4::new() -> P4
Construct a new P4 object. For example:
P4::Identify() -> string
Print build information including P4Perl version and Perforce API version.
P4::Connect() -> bool
Initializes the Perforce client and connects to the server. Returns false on failure and true on success.
P4::Disconnect() -> undef
Terminate the connection and clean up. Should be called before exiting.
P4::ErrorCount() -> integer
Returns the number of errors encountered during execution of the last command
P4::Errors() -> list
Returns a list of the error messages received during execution of the last command.
P4::Fetch<spectype>( [name] ) -> hashref
Shorthand for running $p4->Run( "spectype", "-o" ) and returning the first element of the result array. For example:
$label      = $p4->FetchLabel( $labelname );
$change     = $p4->FetchChange( $changeno );
$clientspec = $p4->FetchClient( $clientname );
P4::Format<spectype>( hash ) -> string
Shorthand for running $p4->FormatSpec( <spectype>, hash ) and returning the results. For example:
$change     = $p4->FetchChange();
$change->{ 'Description' } = 'Some description';
$form       = $p4->FormatChange( $change );
printf( "Submitting this change:\n\n%s\n", $form );
$p4->RunSubmit( $change );
P4::FormatSpec( $spectype, $string ) -> string
Converts a Perforce form of the specified type (client/label etc.) held in the supplied hash into its string representation. Shortcut methods are available that obviate the need to supply the type argument. The following two examples are equivalent:
my $client = $p4->FormatSpec( "client", $hash );
my $client = $p4->FormatClient( $hash );
P4::GetApiLevel() -> integer
Returns the current API compatibility level. Each iteration of the Perforce Server is given a level number. As part of the initial communication, the client protocol level is passed between client application and the Perforce Server. This value, defined in the Perforce API, determines the communication protocol level that the Perforce client will understand. All subsequent responses from the Perforce Server can be tailored to meet the requirements of that client protocol level.
For more information, see:
http://kb.perforce.com/?article=512
P4::GetCharset() -> string
Return the name of the current charset in use. Applicable only when used with Perforce servers running in unicode mode.
P4::GetClient() -> string
Returns the current Perforce client name. This may have previously been set by SetClient(), or may be taken from the environment or P4CONFIG file if any. If all that fails, it will be your hostname.
P4::GetCwd() -> string
Returns the current working directory as your Perforce client sees it.
P4::GetEnv( $var ) -> string
Returns the value of a Perforce environment variable, taking into account the settings of Perforce variables in P4CONFIG files, and, on Windows, in the registry.
P4::GetHost() -> string
Returns the client hostname. Defaults to your hostname, but can be overridden with SetHost()
P4::GetMaxLockTime( $value ) -> integer
Get the current maxlocktime setting.
P4::GetMaxResults( $value ) -> integer
Get the current maxresults setting.
P4::GetMaxScanRows( $value ) -> integer
Get the current maxscanrows setting.
P4::GetPassword() -> string
Returns your Perforce password. Taken from a previous call to SetPassword() or extracted from the environment ( $ENV{P4PASSWD}), or a P4CONFIG file.
P4::GetPort() -> string
Returns the current address for your Perforce server. Taken from a previous call to SetPort(), or from $ENV{P4PORT} or a P4CONFIG file.
P4::GetProg() -> string
Get the name of the program as reported to the Perforce Server.
P4::GetTicketFile( [$string] ) -> string
Return the path of the current P4TICKETS file.
P4::GetUser() -> String
Get the current user name. Taken from a previous call to SetUser(), or from $ENV{P4USER} or a P4CONFIG file.
P4::GetVersion ( $string ) -> string
Get the version of your script, as reported to the Perforce Server.
P4::IsConnected() -> bool
Returns true if the session has been connected, and has not been dropped.
P4::IsTagged() -> bool
Returns true if Tagged mode is enabled on this client.
P4::P4ConfigFile() -> string
Get the path to the current P4CONFIG file.
P4::Parse<Spectype>( $string ) -> hashref
Shorthand for running $p4-ParseSpec( <spectype>, buffer ) and returning the results. For example:
$p4 = new P4;
$p4->Connect() or die( "Failed to connect to server" );
$client = $p4->FetchClient();               # Returns a hashref
$client = $p4->FormatClient( $client );     # Convert to string
$client = $p4->ParseClient( $client );      # Convert back to hashref
P4::ParseSpec( $spectype, $string ) -> hashref
Converts a Perforce form of the specified type (client/label etc.) held in the supplied string into a hash and returns a reference to that hash. Shortcut methods are available to avoid the need to supply the type argument. The following two examples are equivalent:
my $hash = $p4->ParseSpec( "client", $clientspec );
my $hash = $p4->ParseClient( $clientspec );
P4::Run<cmd>( [ $arg... ] ) -> list | arrayref
Shorthand for running $p4-Run (cmd, arg, ...) and returning the results.
P4::Run( cmd, [ $arg... ] ) -> list | arrayref
Run a Perforce command and return its results. Because Perforce commands can partially succeed and partially fail, it is good practice to check for errors using P4::ErrorCount().
Results are returned as follows:
The AutoLoader enables you to treat Perforce commands as methods:
p4->RunEdit( "filename.txt );
is equivalent to
$p4->Run( "edit", "filename.txt" );
Note that the content of the array of results you get depends on (a) whether you're using tagged mode, (b) the command you've executed, (c) the arguments you supplied, and (d) your Perforce server version.
Tagged mode and form parsing mode are turned on by default; each result element is a hashref, but this is dependent on the command you ran and your server version.
In non-tagged mode, each result element is a string. In this case, because the Perforce server sometimes asks the client to write a blank line between result elements, some of these result elements can be empty.
Note that the return values of individual Perforce commands are not documented because they may vary between server releases.
To correlate the results returned by the P4 interface with those sent to the command line client, try running your command with RPC tracing enabled. For example:
Tagged mode
p4 -Ztag -vrpc=1 describe -s 4321
Non-Tagged mode
p4 -vrpc=1 describe -s 4321
Pay attention to the calls to client-FstatInfo(), client-OutputText(), client-OutputData() and client-HandleError(). Each call to one of these functions results in either a result element, or an error element.
P4::RunFilelog ( [$args ...], $fileSpec ... ) -> list | arrayref
Runs a p4 filelog on the fileSpec provided and returns an array of P4::DepotFile objects when executed in tagged mode.
P4::RunLogin (...) -> list | arrayref
Runs p4 login using a password (or other arguments) set by the user.
P4::RunPassword ( $oldpass, $newpass ) -> list | arrayref
A thin wrapper for changing your password from $oldpass to $newpass. Not to be confused with P4::SetPassword.
P4::RunResolve ( [$resolver], [$args ...] ) -> string
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:
$resolver = new MyResolver;
$p4->RunResolve ( $resolver );
To perform an automated merge that skips whenever conflicts are detected:
package MyResolver;
our @ISA = qw( P4::Resolver );
sub Resolve( $ )
{
  my $self      = shift;
  my $mergeData = shift;
  # "s"kip if server-recommended hint is to "e"dit the file,
  # because such a recommendation implies the existence of a conflict
  return "s" if( $mergeData->Hint() eq "e" );
  return $mergeData->Hint();
}
1;
$p4 = new P4;
$resolver = new MyResolver;
In non-interactive resolves, no P4::Resolver object is required. For example:
P4::RunSubmit ( $arg | $hashref, ...) -> list | arrayref
Submit a changelist to the server. To submit a changelist, set the fields of the changelist as required and supply any flags:
$change = $p4->FetchChange();
$change->{ 'Description' } = "Some description";
$p4->RunSubmit( "-r", $change );
You can also submit a changelist by supplying the arguments as you would on the command line:
P4::Save<Spectype>() -> list | arrayref
Shorthand for:
$p4->SetInput( $spectype );
$p4->Run( "spectype", "-i");
For example:
$p4->SaveLabel( $label );
$p4->SaveChange( $changeno );
$p4->SaveClient( $clientspec );
P4::ServerLevel() -> integer
Returns an integer specifying the server protocol level. This is not the same as, but is closely aligned to, the server version. To find out your server's protocol level, run
p4 -vrpc=5 info and look for the server2 protocol variable in the output. For more information, see:
http://kb.perforce.com/?article=571
Must be called after running a command.
P4::SetApiLevel( $integer ) -> undef
Specify the API compatibility level to use for this script. This is useful when you want your script to continue to work on newer server versions, even if the new server adds tagged output to previously unsupported commands.
The additional tagged output support can change the server's output, and confound your scripts. Setting the API level to a specific value allows you to lock the output to an older format, thus increasing the compatibility of your script.
Must be called before calling P4::Connect(). For example:
$p4->SetApiLevel( 57 ); # Lock to 2005.1 format
$p4->Connect() or die( "Failed to connect to Perforce" );
etc.
P4::SetCharset( $charset ) -> undef
Specify the character set to use for local files when used with a Perforce server running in unicode mode. Do not use unless your Perforce server is in unicode mode. Must be called before calling P4::Connect(). For example:
$p4->SetCharset( "winansi" );
$p4->SetCharset( "iso8859-1" );
$p4->SetCharset( "utf8" );
etc.
P4::SetClient( $client ) -> undef
Sets the name of your Perforce client workspace. If you don't call this method, then the client workspace name will default according to the normal Perforce conventions:
1.
2.
Value from $ENV{P4CLIENT}
3.
P4::SetCwd( $path ) -> undef
Sets the current working directory for the client.
P4::SetHost( $hostname ) -> undef
Sets the name of the client host, overriding the actual hostname. This is equivalent to p4 -H hostname, and only useful when you want to run commands as if you were on another machine.
P4::SetInput( $string | $hashref | $arrayref ) -> undef
Save the supplied argument as input to be supplied to a subsequent command. The input may be a hashref, a scalar string, or an array of hashrefs or scalar strings. If you pass an array, the array will be shifted once each time the Perforce command being executed asks for user input.
P4::SetMaxLockTime( $integer ) -> undef
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 maxresults for information on the commands that support this limit.
P4::SetMaxResults( $integer ) -> undef
Limit the number of results for subsequent commands to the value specified. Perforce will abort the command if continuing would produce more than this number of results. Once set, this limit remains in force unless you remove the restriction by setting it to a value of 0.
P4::SetMaxScanRows( $integer ) -> undef
Limit the number of records Perforce will scan when processing subsequent commands to the value specified. Perforce will abort the command once this number of records has been scanned. Once set, this limit remains in force unless you remove the restriction by setting it to a value of 0.
P4::SetPassword( $password ) -> undef
Specify the password to use when authenticating this user against the Perforce Server - overrides all defaults. Not to be confused with P4::Password().
P4::SetPort( $port ) -> undef
Set the port on which your Perforce server is listening. Defaults to:
1.
2.
Value from $ENV{P4PORT}
3.
P4::SetProg( $program_name ) -> undef
Set the name of your script. This value is displayed in the server log on 2004.2 or later servers.
P4::SetTicketFile( [$string] ) -> string
Set the path to the current P4TICKETS file (and return it).
P4::SetUser( $username ) -> undef
Set your Perforce username. Defaults to:
1.
2.
Value from C<$ENV{P4USER}>
3.
P4::SetVersion ( $version ) -> undef
Specify the version of your script, as recorded in the Perforce server log file.
P4::Tagged( 0 | 1 | $coderef ) -> undef
Enable (1) or disable (0) tagged output from the server, or temporarily toggle it.
By default, tagged output is enabled, but can be disabled (or re-enabled) by calling this method. If you provide a code reference, you can run a subroutine with the tagged status toggled for the duration of that reference. For example:
my $GetChangeCounter = sub{ $p4->RunCounter('change')->[ 0 ] );
my $changeno = $p4->Tagged( 0, $GetChangeCounter );
When running in tagged mode, responses from commands that support tagged output will be returned in the form of a hashref. When running in non-tagged mode, responses from commands are returned in the form of strings (that is, in plain text).
P4::WarningCount() -> integer
Returns the number of warnings issued by the last command.
P4::Warnings() -> list
Returns a list of warnings from the last command
 
Class P4::DepotFile
Description
P4::DepotFile objects are used to present information about files in the Perforce repository. They are returned by P4::RunFilelog.
Class Methods
None
Instance Methods
$df->DepotFile() -> string
Returns the name of the depot file to which this object refers.
$df->Revisions() -> array
Returns an array of P4::Revision objects, one for each revision of the depot file
 
Class P4::Revision
Description
P4::Revision objects are represent individual revisions of files in the Perforce repository. They are returned as part of the output of P4::RunFilelog.
Class Methods
$rev->Integrations() -> array
Returns an array of P4::Integration objects representing all integration records for this revision.
Instance Methods
$rev->Action() -> string
Returns the name of the action which gave rise to this revision of the file.
$rev->Change() -> integer
Returns the changelist 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 digest for this revision.
$rev->FileSize() -> string
Returns the size of this revision.
$rev->Rev() -> integer
Returns the number of this revision of the file.
$rev->Time() -> string
Returns the date/time that this revision was created.
$rev->Type() -> string
Returns this revision's Perforce filetype.
$rev->User()
Returns the name of the user who created this revision.
Class P4::Integration
Description
P4::Integration objects represent Perforce integration records. They are returned as part of the output of P4::RunFilelog.
Class Methods
None
Instance Methods
$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() -> integer
Returns the start revision number used for this integration.
$integ->ERev() -> integer
Returns the end revision number used for this integration.
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.
Class Methods
$map = new P4::Map( [ array ] ) -> aMap
Constructs a new P4::Map object.
$map->Join( map1, map2 ) -> aMap
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 = new P4::Map;
$client_map->Insert( "//depot/main/...", "//client/..." );
# Map client syntax to local syntax
$client_root = new 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() -> undef
Empty a map.
$map->Count() -> integer
Return the number of entries in a map.
$map->IsEmpty() -> bool
Test whether a map object is empty.
$map->Insert( string ... ) -> undef
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, [ bool ] ) -> 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 ) -> bool
Tests whether a path is mapped or not.
$map->Reverse() -> aMap
Return a new P4::Map object with the left and right sides of the mapping swapped. The original object is unchanged.
$map->Lhs() -> array
Returns the left side of a mapping as an array.
$map->Rhs() -> array
Returns the right side of a mapping as an array.
$map->AsArray() -> array
Returns the map as an array.
Class P4::MergeData
Description
Class containing the context for an individual merge during execution of a p4 resolve. Users may not create objects of this class; they are created internally during P4::RunResolve(), and passed down to the Resolve() method of a P4::Resolver subclass.
Class Methods
None
Instance Methods
$md.YourName() -> string
Returns the name of "your" file in the merge, in client syntax.
$md.TheirName() -> string
Returns the name of "their" file in the merge, in client syntax, including the revision number.
$md.BaseName() -> string
Returns the name of the "base" file in the merge, in depot syntax, including the revision number.
$md.YourPath() -> string
Returns the path of "your" file in the merge. This is typically a path to a file in the client workspace.
$md.TheirPath() -> 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 TheirName() have been loaded.
$md.BasePath() -> 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 BaseName() have been loaded.
$md.ResultPath() -> 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.MergeHint() -> string
Returns a string containing the hint from Perforce's merge algorithm, indicating the recommended action for performing the resolve.
$md.RunMergeTool() -> integer
If the environment variable P4MERGE is defined, RunMergeTool() invokes the specified program and returns true if the merge tool was successfully executed, otherwise returns false.
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::RunResolve() is called with a P4::Resolver object, it calls the Resolve() method of the object once for each scheduled resolve.
Class Methods
None
Instance Methods
$resolver.Resolve() -> 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
P4::Spec objects are used to present information about files in the Perforce repository.
The P4::Spec class uses Perl's AutoLoader to simplify form manipulation. Form fields can be accessed by calling a method with the same name as the field prefixed by an underscore (_).
Class Methods
$spec = new P4::Spec( $fieldMap ) -> array
Constructs a new P4::Spec object for a form containing the specified fields. (The object also contains a _fields_ member that stores a list of field names that are valid in forms of this type.)
Instance Methods
$spec->_<fieldname> -> string
Returns the value associated with the field named <fieldname>.
$client = $p4->FetchClient( $clientname );
$client->_Root();    # Get client root
$spec->_<fieldname>( $string )-> string
Updates the value of the named field in the spec.
$client = $p4->FetchClient( $clientname );
$client->_Root( $newroot );    # Set client root
$spec->PermittedFields() -> array
Returns 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.
$client = $p4->FetchClient( $clientname );
@fields = $p4->PermittedFields( $client );
foreach $field (@fields) {
  echo $field;
}
 


Previous Table of Contents Next

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