Previous Table of Contents Next
Perforce 2009.1: APIs for Scripting



Chapter 1
Introduction
P4Ruby is an extension to the Ruby programming language that allows you to run Perforce commands from within Ruby scripts, and get the results in a Ruby-friendly format.
The main features are:
The output of a command is returned as a Ruby array. For non-tagged output, the elements of the array are strings. For tagged output, the elements of the array are Ruby hashes. For forms, the output is an array of P4::Spec objects.
Exception-based error handling. Trap P4Exceptions for complete, high-level error handling.
System Requirements
P4Ruby is supported on Windows, Linux, Solaris, and FreeBSD.
To build P4Ruby, your development machine must also have:
make (or nmake on Windows)
(If you get "unresolved symbol" errors when building or running P4Ruby, you probably used the wrong compiler or the wrong Perforce API build. )
Installing P4Ruby
Download P4Ruby 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 P4Ruby
The following example shows how to create a new client workspace based on an existing template:
require "P4"
template = "my-client-template"
client_root = 'c:\p4-work'
p4 = P4.new
p4.connect
    # Run a "p4 client -t template -o" and convert it into a Ruby hash
    spec = p4.fetch_client( "-t", template )
    # Now edit the fields in the form
    spec[ "Root" ]  = client_root
    spec[ "Options" ] = spec[ "Options" ].sub( "normdir", "rmdir" )
    # Now save the updated spec
    p4.save_client( spec )
    # And sync it.
    p4.run_sync
rescue P4Exception
    # If any errors occur, we'll jump in here. Just log them
    # and raise the exception up to the higher level
    p4.errors.each { |e| $stderr.puts( e ) }
    raise
P4Ruby 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 P4Ruby will involve this class.
Execute the associated block under a specific exception level, returning to previous exception level when block returns
delete_spectype
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows) the registry.
Control which types of events give rise to exceptions (P4::RAISE_NONE, RAISE_ERRORS, or RAISE_ALL)
fetch_spectype
Convert fields in a hash containing the elements of a Perforce form (spec) into the string representation familiar to users
format_spectype
Shortcut methods; equivalent to:
p4.format_spec( spectype, aHash )
parse_spectype
Shortcut method; equivalent to:
p4.parse_spec(spectype, aString)
Parses a Perforce form (spec) in text form into a Ruby hash using the spec definition obtained from the server.
Get host and port (P4PORT) of the current Perforce server
Shortcut method; equivalent to:
p4.run (cmd, arguments... )
Runs a p4 filelog on the fileSpec provided, returns an array of P4::DepotFile objects
Runs p4 login using a password (or other arguments) set by the user
Interface to p4 resolve.
save_spectype
Shortcut methods; equivalent to:
p4.input = hashOrString
p4.run( spectype, "-i" )
P4Exception
Used as part of error reporting and is derived from the Ruby RuntimeError class.
P4::DepotFile
Utility class allowing access to the attributes of a file in the depot. Returned by P4#run_filelog.
P4::Revision
Utility class allowing access to the attributes of a revision DepotFile object. Returned by P4#run_filelog.
Array of P4.Integration objects
P4::Integration
Utility class allowing access to the attributes of an integration record for a Revision object. Returned by P4#run_filelog.
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 as a parameter to the block 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)
If the environment variable P4MERGE is defined, run it and return a boolean based on the return value of that program
P4::Spec
Subclass of hash allowing access to the fields in a Perforce specification form. Also checks that the fields that are set are valid fields for the given type of spec. Returned by P4#fetch_spectype.
spec._fieldname
spec._fieldname=
Class P4
Description
Main interface to the Perforce client API. Each P4 object provides you with a thread-safe API level interface to Perforce. The basic model is to:
1.
2.
3.
4.
5.
6.
Class Methods
P4.identify -> aString
Return the version of P4Ruby that you are using.
P4.new -> aP4
Constructs a new P4 object.
Instance Methods
p4.api_level= anInteger -> anInteger
Sets 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. This method must be called prior to calling P4#connect.
p4 = P4.new
p4.api_level = 57 # Lock to 2005.1 format
p4.connect
...
For the API integer levels that correspond to each Perforce release, see:
http://kb.perforce.com/?article=512
p4.api_level -> anInteger
Returns the current Perforce 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.at_exception_level( lev ) { ... } -> self
Executes the associated block under a specific exception level. Returns to the previous exception level when the block returns.
p4 = P4.new
p4.client = "www"
p4.connect
p4.charset= aString -> aString
Sets 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.
p4 = P4.new
p4.client = "www"
p4.charset = "iso8859-1"
p4.connect
p4.run_sync
p4.disconnect
p4.charset -> aString
Get the name of the character set in use when working with Unicode-enabled servers.
p4 = P4.new
p4.charset = "utf8"
puts( p4.charset )
p4.client= aString -> aString
Set the name of the client workspace you wish to use. If not called, defaults to the value of P4CLIENT 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.
p4 = P4.new
p4.client = "www"
p4.connect
p4.run_sync
p4.disconnect
p4.client -> aString
Get the name of the Perforce client currently in use
p4 = P4.new
puts( p4.client )
p4.connect -> aBool
Connect to the Perforce Server. You must connect before you can execute commands. Raises a P4Exception if the connection attempt fails.
p4 = P4.new
p4.connect
p4.connected? -> aBool
Test whether or not the session has been connected, and if the connection has not been dropped.
p4 = P4.new
p4.connected?
p4.cwd= aString -> aString
Sets 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.
p4 = P4.new
p4.cwd = "/home/tony"
p4.cwd -> aString
Get the current working directory
p4 = P4.new
puts( p4.cwd )
p4.delete_<spectype>( [options], name ) -> anArray
The delete methods are simply shortcut methods that allow you to quickly delete the definitions of clients, labels, branches, etc. These methods are equivalent to
p4.run( <spectype>, '-d', [options], <spec name> )
For example:
require "P4"
require "parsedate"
include ParseDate
now = Time.now
p4 = P4.new
begin
  p4.connect
  p4.run_clients.each do
    |client|
    atime = parsedate( client[ "Access" ] )
    if( (atime + 24 * 3600 * 365 ) < now )
      p4.delete_client( '-f', client[ "client" ] )
    end
  end
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.disconnect -> true
Disconnect from the Perforce Server.
p4 = P4.new
p4.connect
p4.disconnect
p4.env -> string
Get the value of a Perforce environment variable, taking into account P4CONFIG files and (on Windows) the registry.
p4 = P4.new
puts p4.env( "P4PORT" )
p4.errors -> anArray
Returns the array of errors which occurred during execution of the previous command.
p4 = P4.new
begin
  p4.connect
  p4.exception_level( P4::RAISE_ERRORS ) # ignore "File(s) up-to-date"
  files = p4.run_sync
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.exception_level= anInteger -> anInteger
Configures the events which give rise to exceptions. The following three levels are supported:
P4::RAISE_NONE disables all exception raising and makes the interface completely procedural.
P4::RAISE_ERRORS causes exceptions to be raised only when errors are encountered.
P4::RAISE_ALL causes exceptions to be raised for both errors and warnings. This is the default.
p4 = P4.new
p4.exception_level = P4::RAISE_ERRORS
p4.connect   # P4Exception on failure
p4.run_sync  # File(s) up-to-date is a warning so no exception is raised
p4.disconnect
p4.exception_level -> aNumber
Returns the current exception level.
p4.fetch_<spectype>( [name] ) -> aP4::Spec
The fetch_spectype methods are shortcut methods that allow you to quickly fetch the definitions of clients, labels, branches, etc. They're equivalent to:
p4.run( spectype, '-o', ... ).shift
For example:
p4 = P4.new
begin
  p4.connect
  client       = p4.fetch_client()
  other_client = p4.fetch_client( "other" )
  label        = p4.fetch_label( "somelabel" )
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.format_spec( <spectype>, aHash )-> aString
Converts the fields in a hash 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( hash )
instead of
p4.format_spec( spectype, hash )
where spectype is the name of a Perforce spec, such as client, label, etc.
p4.format_<spectype> aHash -> aHash
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, aHash )
p4.host= aString -> aString
Set the name of the current host. If not called, 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.
p4 = P4.new
p4.host = "workstation123.perforce.com"
p4.connect
...
p4.disconnect
p4.host -> aString
Get the current hostname
p4 = P4.new
puts( p4.host )
p4.input= ( aString|aHash|anArray ) -> aString|aHash|anArray
Store input for the next command.
Call this method prior to running a command requiring input from the user. When the command requests input, the specified data will be supplied to the command. Typically, commands of the form p4 cmd -i are invoked using the P4#save_spectype methods, which call P4#input() internally; there is no need to call 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 array will be shifted each time Perforce asks the user for input.
p4 = P4.new
p4.connect
change = p4.run_change( "-o" ).shift
change[ "Description" ] = "Autosubmitted changelist"
p4.input = change
p4.run_submit( "-i" )
p4.maxlocktime= anInteger -> anInteger
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 = P4.new
begin
  p4.connect
  p4.maxlocktime = 10000 # 10 seconds
  files = p4.run_sync
rescue P4Exception => ex
  p4.errors.each { |e| $stderr.puts( e ) }
ensure
  p4.disconnect
end
p4.maxlocktime -> anInteger
Get the current maxlocktime setting
p4 = P4.new
puts( p4.maxlocktime )
p4.maxresults= anInteger -> anInteger
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 = P4.new
begin
  p4.connect
  p4.maxresults = 100
  files = p4.run_sync
rescue P4Exception => ex
  p4.errors.each { |e| $stderr.puts( e ) }
ensure
  p4.disconnect
end
p4.maxresults -> anInteger
Get the current maxresults setting
p4 = P4.new
puts( p4.maxresults )
p4.maxscanrows= anInteger -> anInteger
Limit the number of database records Perforce will scan 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 = P4.new
begin
  p4.connect
  p4.maxscanrows = 100
  files = p4.run_sync
rescue P4Exception => ex
  p4.errors.each { |e| $stderr.puts( e ) }
ensure
  p4.disconnect
end
p4.maxscanrows -> anInteger
Get the current maxscanrows setting
p4 = P4.new
puts( p4.maxscanrows )
p4.p4config_file -> aString
Get the path to the current P4CONFIG file
p4 = P4.new
puts( p4.p4config_file )
p4.parse_<spectype> ( aString ) -> aP4::Spec
This is equivalent to parse_spec(spectype, aString).
p4.parse_spec( <spectype>, aString ) -> aP4::Spec
Parses a Perforce form (spec) in text form into a Ruby hash 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.
Note that 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.password= aString -> aString
Set your Perforce password, in plain text. 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 will also be used if you later call p4.run_login to login using the 2003.2 and later ticket system.
p4 = P4.new
p4.password = "mypass"
p4.connect
p4.run_login
p4.password -> aString
Get the current password or ticket. This may be the password in plain text, or if you've used p4.run_login, it'll be the value of the ticket you've been allocated by the server.
p4 = P4.new
puts( p4.password )
p4.port= aString -> aString
Set the host and port of the Perforce server you want to connect to. If not called, defaults to the value of P4PORT in any P4CONFIG file in effect, and then to the value of P4PORT taken from the environment.
p4 = P4.new
p4.port = "localhost:1666"
p4.connect
...
p4.disconnect
p4.port -> aString
Get the host and port of the current Perforce server.
p4 = P4.new
puts( p4.port )
p4.prog= aString -> aString
Set the name of the program, as reported to Perforce system administrators running p4 monitor show -e in Perforce 2004.2 or later releases.
p4 = P4.new
p4.prog = "sync-script"
p4.connect
...
p4.disconnect
p4.prog -> aString
Get the name of the program as reported to the Perforce Server.
p4 = P4.new
p4.prog = "sync-script"
puts( p4.prog )
p4.run_cmd( arguments ) -> anArray
This is equivalent to p4.run (cmd, arguments... ).
p4.run( aCommand, arguments... ) -> anArray
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 to_s.
The p4.run method returns an array of results whether the command succeeds or fails; the array may, however, be empty. Whether the elements of the array are strings or hashes 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 will raise 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.
p4 = P4.new
p4.connect
spec = p4.run( "client", "-o" ).shift
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. Consequently, this:
p4 = P4.new
p4.connect
clientspec = p4.run_client( "-o" ).shift
clientspec[ "Description" ] = "Build client"
p4.input = clientspec
p4.run_client( "-i" )
p4.disconnect
...may be shortened to
p4 = P4.new
p4.connect
clientspec = p4.fetch_client
clientspec[ "Description" ] = "Build client"
p4.save_client( clientspec )
p4.disconnect
The following are equivalent:
p4.delete_spectype
p4.run( "spectype", "-d ")
p4.fetch_spectype
p4.run( "spectype", "-o ").shift
p4.save_spectype( spec )
p4.input = spec
p4.run( "spectype", "-i" )
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:
p4 = P4.new
p4.connect
spec = p4.fetch_change
spec[ "Description" ] = "Automated change"
p4.run_submit( spec )
p4.disconnect
p4.run_filelog( fileSpec ) -> anArray
Runs a p4 filelog on the fileSpec provided and returns an array of P4::DepotFile results when executed in tagged mode, and an array of strings when executed in non-tagged 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.
p4 = P4.new
begin
  p4.connect
  p4.run_filelog( "index.html" ).shift.each_revision do
    |r|
    r.each_integration do
      |i|
      # Do something
    end
  end
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.run_login( arg... ) -> anArray
Runs p4 login using a password (or other arguments) set by the user.
p4.run_password( oldpass, newpass ) -> anArray
A thin wrapper to make it easy to change your password. This method is (literally) equivalent to the following code:
For example:
p4 = P4.new
p4.password = "myoldpass"
begin
  p4.connect
  p4.run_password( "myoldpass", "mynewpass" )
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.run_resolve( args ) [ block ] -> anArray
Interface to p4 resolve. Without a block, simply runs a non-interactive resolve (typically an automatic resolve).
When a block is supplied, the block is invoked once for each merge scheduled by Perforce. For each merge, a P4::MergeData object is passed to the block. This object contains the context of the merge.
The block determines the outcome of the merge by evaluating to one of the following strings:
For example:
p4.run_resolve() do
  |md|
  puts( "Merging..." )
  puts( "Yours: #{md.your_name}" )
  puts( "Theirs: #{md.their_name}" )
  puts( "Base: #{md.base_name}" )
  puts( "Yours file: #{md.your_path}" )
  puts( "Theirs file: #{md.their_path}" )
  puts( "Base file: #{md.base_path}" )
  puts( "Result file: #{md.result_path}" )
  puts( "Merge Hint: #{md.merge_hint}" )
  result = md.merge_hint
  if( result == "e" )
    puts( "Invoking external merge application" )
    result = "s"    # If the merge doesn't work, we'll skip
    result = "am" if md.run_merge()
  end
  result
end
p4.run_submit( [aHash], [arg...] ) -> anArray
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>( hashOrString, [options] ) -> anArray
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 = hashOrString
p4.run( spectype, "-i" )
For example:
p4 = P4.new
begin
  p4.connect
  client            = p4.fetch_client()
  client[ "Owner" ] = p4.user
  p4.save_client( client )
rescue P4Exception
  p4.errors.each { |e| puts( e ) }
ensure
  p4.disconnect
end
p4.server_level -> anInteger
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.
For more information, see:
http://kb.perforce.com/?article=571
p4.tagged( aBool ) { block }
Temporarily toggles the use of tagged output for the duration of the block, and then resets it when the block terminates.
p4.tagged= aBool -> aBool
Sets tagged output. By default, tagged output is on.
p4 = P4.new
p4.tagged = false
p4.tagged? -> aBool
Detects whether or not you are in tagged mode.
p4 = P4.new
puts ( p4.tagged? )
p4.tagged = false
puts ( p4.tagged? )
p4.ticketfile= aString -> aString
Sets the location of the P4TICKETS file
p4 = P4.new
p4.ticketfile = "/home/tony/tickets"
p4.ticketfile -> aString
Get the path to the current P4TICKETS file.
p4 = P4.new
puts( p4.ticketfile )
p4.ticketfile = "/home/tony/tickets"
p4.user= aString -> aString
Set the Perforce username. If not called, defaults to the value of P4USER 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.
p4 = P4.new
p4.user = "tony"
p4.connect
...
p4.disconnect
p4.user -> aString
Returns the current Perforce username
p4 = P4.new
puts( p4.user )
p4.version= aString -> aString
Set the version of your script, as reported to the Perforce Server.
p4.version -> aString
Get the version of your script, as reported to the Perforce Server.
p4.warnings -> anArray
Returns the array of warnings which arose during execution of the last command.
p4 = P4.new
begin
  p4.connect
  p4.exception_level( P4::RAISE_ALL ) # File(s) up-to-date is a warning
  files = p4.run_sync
rescue P4Exception => ex
  p4.warnings.each { |w| puts( w ) }
ensure
  p4.disconnect
end
 
Class P4Exception
Shallow subclass of RuntimeError to be used for catching Perforce specific errors. Doesn't contain any extra information. See P4#errors and P4#warnings for details of the errors giving rise to the exception.
Class Methods
None.
Instance 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 an array of P4::DepotFile objects.
Class Methods
None
Instance Methods
df.depot_file -> aString
Returns the name of the depot file to which this object refers.
df.each_revision { |rev| block } -> revArray
Iterates over each revision of the depot file
df.revisions -> aArray
Returns an array of revisions of the depot file
Class P4::Revision
Description
Utility class providing easy access to the revisions of a file in a Perforce depot. P4::Revision objects can store basic information about revisions and a list of the integrations for that revision. Created by run_filelog.
Class Methods
None
Instance Methods
rev.action -> aString
Returns the name of the action which gave rise to this revision of the file.
rev.change -> aNumber
Returns the change number that gave rise to this revision of the file.
rev.client -> aString
Returns the name of the client from which this revision was submitted.
rev.depot_file -> aString
Returns the name of the depot file to which this object refers.
rev.desc -> aString
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 -> aString
Returns the MD5 digest for this revision of the file.
rev.each_integration { |integ| block } -> integArray
Iterates over each the integration records for this revision of the depot file.
rev.filesize -> aNumber
Returns size of this revision.
rev.integrations -> integArray
Returns the list of integrations for this revision.
rev.rev -> aNumber
Returns the number of this revision of the file.
rev.time -> aTime
Returns the date/time that this revision was created.
rev.type -> aString
Returns this revision's Perforce filetype.
rev.user -> aString
Returns the name of the user who created this revision.
Class P4::Integration
Description
Utility class providing easy access to the details of an integration record. Created by run_filelog.
Class Methods
None.
Instance Methods
integ.how -> aString
Returns the type of the integration record - how that record was created.
integ.file -> aPath
Returns the path to the file being integrated to/from.
integ.srev -> aNumber
Returns the start revision number used for this integration.
integ.erev -> aNumber
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 ( [ anArray ] ) -> 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 = P4::Map.new
client_map.insert( "//depot/main/...", "//client/..." )
# Map client syntax to local syntax
client_root = P4::Map.new
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 -> true
Empty a map.
map.count -> anInteger
Return the number of entries in a map.
map.empty? -> aBool
Test whether a map object is empty.
map.insert( aString, [ aString ] ) -> aMap
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 ( aString, [ aBool ] )-> aString
Translate a string through a map, and return the result. If the optional second argument is true, translate forward, and if it is false, translate in the reverse direction. By default, translation is in the forward direction.
map.includes? ( aString ) -> aBool
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 -> anArray
Returns the left side of a mapping as an array.
map.rhs -> anArray
Returns the right side of a mapping as an array.
map.to_a -> anArray
Returns the map as an array.
Class P4::MergeData
Description
Class containing the context for an individual merge during execution of a p4 resolve.
Class Methods
None
Instance Methods
md.your_name() -> aString
Returns the name of "your" file in the merge. This is typically a path to a file in the workspace.
p4.run_resolve() do
  |md|
  yours = md.your_name
  md.merge_hint # merge result
end
md.their_name() -> aString
Returns the name of "their" file in the merge. This is typically a path to a file in the depot.
p4.run_resolve() do
  |md|
  theirs = md.their_name
  md.merge_hint # merge result
end
md.base_name() -> aString
Returns the name of the "base" file in the merge. This is typically a path to a file in the depot.
p4.run_resolve() do
  |md|
  base = md.base_name
  md.merge_hint # merge result
end
md.your_path() -> aString
Returns the path of "your" file in the merge. This is typically a path to a file in the workspace.
p4.run_resolve() do
  |md|
  your_path = md.your_path
  md.merge_hint # merge result
end
md.their_path() -> aString
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.
p4.run_resolve() do
  |md|
  their_name = md.their_name
  their_file = File.open( md.their_path )
  md.merge_hint # merge result
end
md.base_path() -> aString
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.
p4.run_resolve() do
  |md|
  base_name = md.base_name
  base_file = File.open( md.base_path )
  md.merge_hint # merge result
end
md.result_path() -> aString
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.
p4.run_resolve() do
  |md|
  result_file = File.open( md.result_path )
  md.merge_hint # merge result
end
md.merge_hint() -> aString
Returns the hint from the server as to how it thinks you might best resolve this merge.
p4.run_resolve() do
  |md|
  puts ( md.merge_hint ) # merge result
end
md.run_merge() -> aBool
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.
p4.run_resolve() do
  |md|
  if ( md.run_merge() )
    "am"
  else
    "s"
  end
end
 
Class P4::Spec
Description
The P4::Spec class is a hash containing key/value pairs for all the fields in a Perforce form. It provides two things over and above its parent class (Hash):
Fieldname validation. Only valid field names may be set in a P4::Spec object. Note that only the field name is validated, not the content.
Class Methods
new P4::Spec.new( anArray ) -> aP4::Spec
Constructs a new P4::Spec object given an array of valid fieldnames.
Instance Methods
spec._<fieldname> -> aValue
Returns the value associated with the field named <fieldname>. This is equivalent to spec[ "<fieldname>" ] with the exception that when used as a method, the fieldnames may be in lowercase regardless of the actual case of the fieldname.
client = p4.fetch_client()
root   = client._root
desc   = client._description
spec._<fieldname>= aValue -> aValue
Updates the value of the named field in the spec. Raises a P4Exception if the fieldname is not valid for specs of this type.
client = p4.fetch_client()
client._root         = "/home/tony/new-client"
client._description  = "My new client spec"
p4.save_client( client )
spec.permitted_fields -> anArray
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.fetch_client()
spec.permitted_fields.each do
  | field |
  printf ( "%14s = %s\n", field, client[ field ] ))
end
 


Previous Table of Contents Next

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