P4 struct
The P4 struct provides a Go interface for the
P4 Server
client API. Each P4 struct allows you to interact with the
P4 Server
in a thread-safe manner. The typical workflow is as follows:
- Instantiate your
P4object. -
Specify your P4 Server client environment.
ClientHostPasswordPortUser
-
Connect to the Perforce service.
- Run your P4 Server commands.
- Disconnect from the Perforce service.
For applications with multiple threads, ensure each thread uses a separate connection. Alternatively, make sure each thread has synchronized access to a shared connection.
Table of methods
P4 is the main struct used for executing Perforce commands. Most commands within Go use the following methods.
| Method | Description |
|---|---|
|
|
Creates and initializes a new P4 instance. |
|
|
Cleans up resources when the client is no longer needed. |
|
|
Establishes a connection to the P4 Server, returns |
|
|
Checks if the P4 instance is currently connected to the server. |
|
|
Disconnect from the P4 Server, returns Error on failure. |
|
|
Return the version of P4 API for Go in use. |
|
|
Returns the current P4 Server level. |
|
|
Detects whether or not the server is in unicode mode. |
|
|
Detects whether or not the server is case sensitive. |
|
|
Runs the specified Perforce command with the arguments supplied. |
|
|
Shortcut methods for retrieving the definitions of clients, labels, etc. |
|
|
Shortcut method; equivalent to: Copy
|
|
|
Submit a changelist to the server. |
|
|
Shelves files or changelists. |
|
|
Shortcut methods for deleting clients, labels, etc. |
|
|
Runs a |
|
|
A thin wrapper to make it easy to change your password. |
|
|
Runs |
|
|
Get a list of tickets from the local tickets file. |
|
|
Parses a Perforce form (spec) in text form to a dictionary using the spec definition obtained from the server. |
|
|
Convert fields in a hash containing the elements of a Perforce form (spec) into the string representation familiar to users. |
|
|
Shortcut methods for iterating through clients, labels, etc. |
|
|
Store input for next command. |
|
|
On Windows or macOS, set a variable in the registry or user preferences. |
|
|
Get the value of a Perforce environment variable, taking into account |
|
|
Set the path to the Perforce environment file. |
|
|
Get the path to the Perforce environment file. |
|
|
Set the name of the current host ( |
|
|
Get the current hostname. |
|
|
Set the path to the ignore file. |
|
|
Get the path to the ignore file. |
|
|
Checks if a specified file or directory is ignored based on the ignore file. |
|
|
Set the language. |
|
|
Get the current language setting. |
|
|
Get the location of the configuration file used ( |
|
|
Sets the password for the Perforce user. |
|
|
Get the current password or ticket. |
|
|
Set host and port ( |
|
|
Get host and port ( |
|
|
Set program name as shown by |
|
|
Get program name as shown by |
|
|
Sets a Perforce protocol variable. |
|
|
Sets a Perforce variable. |
|
|
Set the location of the |
|
|
Get the location of the |
|
|
Set the path to the Perforce trust file. |
|
|
Get the path to the Perforce trust file. |
|
|
Set the Perforce username ( |
|
|
Get the Perforce username ( |
|
|
Set your script’s version as reported to the server. |
|
|
Get your script’s version as reported by the server. |
|
|
Set character set when connecting to Unicode servers. |
|
|
Get character set when connecting to Unicode servers. |
|
|
Set client workspace ( |
|
|
Get current client workspace ( |
|
|
Set current working directory. |
|
|
Get current working directory. |
|
|
Set the API level for the Perforce client. |
|
|
Get the API level of the Perforce client. |
|
|
Enable or disable support for streams. |
|
|
Test whether or not the server supports streams. |
|
|
Set tagged output. By default, tagged output is on. |
|
|
Detects whether or not tagged output is enabled. |
|
|
Enables or disable server performance tracking. |
|
|
Detect whether server performance tracking is active. |
|
|
Enables or disables graph depot support. |
|
|
Checks if graph depot support is enabled. |
|
|
Set the debug level. |
|
|
Get the current debug level. |
|
|
Set MaxResults used for all following commands. |
|
|
Get MaxResults used for all following commands. |
|
|
Set MaxScanRows used for all following commands. |
|
|
Get MaxScanRows used for all following commands. |
|
|
Set MaxLockTime used for all following commands. |
|
|
Get MaxLockTime used for all following commands. |
|
|
Set progress indicator. |
|
|
Set output handler. |
|
|
Set SSO handler. |
|
|
Set Resolve handler. |
Examples
Initialization and Cleanup
-
New() -> *P4
Creates and returns a new instance of the P4 struct. This method initializes the Perforce client API and prepares it for use.
p4 := New()
defer p4.Close()
fmt.Println("Perforce client initialized.")
-
Close()
Cleans up resources associated with the P4 instance, including handlers and the client API. This method should always be called when the P4 instance is no longer needed to avoid resource leaks.
p4 := New()
defer p4.Close()
// Perform operations with the Perforce client
fmt.Println("Perforce client closed.")
Connection Management
-
Connect() -> (bool, error)
Establishes a connection to the P4 Server. This method is used to authenticate and connect the client to the server.
connected, err := p4.Connect()
if err != nil {
fmt.Println("Failed to connect:", err)
} else if connected {
fmt.Println("Connected to P4 server.")
}
-
Connected() -> bool
Checks if the client is currently connected to the P4 Server. This method is useful for verifying the connection status before executing commands.
if p4.Connected() {
fmt.Println("Client is connected.")
}
-
Disconnect() -> (bool, error)
Disconnects from the P4 Server. This method is used to cleanly terminate the connection to the server.
disconnected, err := p4.Disconnect()
if err != nil {
fmt.Println("Failed to disconnect:", err)
} else if disconnected {
fmt.Println("Disconnected from P4 server.")
}
Server Information
-
Identify() -> string
Return the version of P4 API for Go that you are using.
fmt.Println("Server ID:", p4.Identify())
-
ServerLevel() -> int
Retrieves the server level, which indicates the version or capabilities of the P4 Server. This method is useful for determining if certain features are supported by the server.
level, err := p4.ServerLevel()
if err != nil {
fmt.Println("Error in getting server level:", err)
}
fmt.Println("Server Level:", level)
if level >= 33 {
fmt.Println("Server supports unload depots.")
}
-
ServerUnicode() -> bool
Checks if the server supports Unicode. This method is used to determine if the server is operating in Unicode mode, which is important for handling internationalized text.
result, err := p4.ServerUnicode()
if err != nil {
fmt.Println("Error in server unicode:", err)
}
if result {
fmt.Println("Server is running in Unicode mode.")
} else {
fmt.Println("Server is not running in Unicode mode.")
}
-
ServerCaseSensitive() -> bool
Checks if the server is case-sensitive. This method is useful for understanding how the server treats file names and paths, especially in environments where case sensitivity matters.
result, err := p4.ServerCaseSensitive()
if err != nil {
fmt.Println("Error in case-sensitive:", err)
}
if result {
fmt.Println("Server is case-sensitive.")
} else {
fmt.Println("Server is not case-sensitive.")
}
Command Execution
-
Run(cmd string, args ...string) -> []P4Result
Executes a Perforce command with the specified arguments and returns the results as a slice of P4Result. This is the most generic method for running commands and is used for commands like info, sync, files, etc.
results, err := p4.Run("info")
fmt.Println("Server Info:", results)
-
RunFetch(spec string, args ...string) -> (Dictionary, error)
Fetches a Perforce spec (for example, client, label, branch) and returns it as a dictionary. This method is used to retrieve the current configuration or details of a specific spec.
clientSpec, err := p4.RunFetch("client")
if err == nil {
fmt.Println("Client Spec:", clientSpec)
}
-
RunSave(spec string, specdict Dictionary, args ...string) -> (*P4Message, error)
Saves a Perforce spec (for example, client, label, branch) using the provided dictionary. This method is used to update or create a new spec in the P4 Server.
clientSpec["Root"] = "/new/root"
msg, err := p4.RunSave("client", clientSpec)
if err == nil {
fmt.Println("Client saved:", msg.String())
}
-
RunSubmit(args ...interface{}) -> ([]Dictionary, error)
Submits a changelist or files to the P4 Server. This method is used to finalize changes and make them part of the Perforce depot.
changeSpec, _ := p4.RunFetch("change")
changeSpec["Description"] = "Submitting changes"
_, err := p4.RunSubmit(changeSpec)
-
RunShelve(args ...interface{}) -> ([]Dictionary, error)
Shelves files or changelists in the P4 Server. Shelving allows you to temporarily store changes without submitting them.
changeSpec, _ := p4.RunFetch("change")
changeSpec["Description"] = "Shelving changes"
_, err := p4.RunShelve(changeSpec)
-
RunDelete(spec string, args ...string) -> (*P4Message, error)
Deletes a Perforce spec (for example, client, label, branch). This method is used to remove configurations or objects from the P4 Server.
msg, err := p4.RunDelete("client", "my_client")
if err == nil {
fmt.Println("Client deleted:", msg.String())
}
-
RunFilelog(args ...string) -> ([]*P4DepotFile, error)
Retrieves the file history for a specified file or set of files. This method is used to analyze the revision history, changes, and integrations of files.
filelog, _ := p4.RunFilelog("//depot/file.txt")
for _, file := range filelog {
fmt.Println("File:", file.Name)
}
// Process the filelog output
for _, df := range filelog {
// Print depot file name
fmt.Println("Depot File:", df.Name)
// Iterate through revisions
for _, rev := range df.Revisions {
fmt.Println("\nRevision Details:")
fmt.Println(" Revision Number:", rev.Rev)
fmt.Println(" Change Number:", rev.Change)
fmt.Println(" Action:", rev.Action)
fmt.Println(" Type:", rev.Type)
fmt.Println(" User:", rev.User)
fmt.Println(" Client:", rev.Client)
fmt.Println(" Description:", rev.Desc)
fmt.Println(" Time:", rev.Time)
// Print integrations (if any)
if len(rev.Integrations) > 0 {
fmt.Println(" Integrations:")
for _, integ := range rev.Integrations {
fmt.Println(" How:", integ.How)
fmt.Println(" File:", integ.File)
fmt.Println(" Start Revision:", integ.SRev)
fmt.Println(" End Revision:", integ.ERev)
}
}
}
}
-
RunLogin(args ...string) -> (Dictionary, error)
Logs in to the P4 Server using the current password. This method is used to authenticate the client with the P4 Server.
loginResult, err := p4.RunLogin()
if err == nil {
fmt.Println("Login successful:", loginResult)
}
-
RunPassword(old string, new string) -> (*P4Message, error)
Changes the user's password. This method is used to update the password for the current user.
msg, err := p4.RunPassword("", "newpassword")
if err == nil {
fmt.Println("Password updated:", msg.String())
}
-
RunTickets() -> ([]map[string]string, error)
Reads the Perforce tickets file and returns a list of tickets. This method is used to retrieve authentication tickets stored locally.
tickets, err := p4.RunTickets()
if err == nil {
fmt.Println("Tickets:", tickets)
}
Spec Parsing and Formatting
-
ParseSpec(spec string, form string) -> Dictionary
Parses a Perforce spec (for example, client, label, branch) from a string into a Dictionary. This method is used to convert a raw spec string into a structured format for easier manipulation.
rawSpec := `
Client: test_client
Root: /workspace
Options: noallwrite noclobber nocompress unlocked nomodtime normdir
View:
//depot/... //test_client/...
`
parsedSpec, err := p4.ParseSpec("client", rawSpec)
fmt.Println("Parsed Spec:", parsedSpec)
-
FormatSpec(spec string, dict Dictionary) -> string
Formats a Dictionary into a Perforce spec string. This method is used to convert a structured spec back into a raw string format for saving or submission.
specDict := Dictionary{
"Client": "test_client",
"Root": "/workspace",
"Options": "noallwrite noclobber nocompress unlocked nomodtime normdir",
"View0": "//depot/... //test_client/...",
}
formattedSpec, err := p4.FormatSpec("client", specDict)
fmt.Println("Formatted Spec:\n", formattedSpec)
-
SpecIterator(spec string, args ...string) ([]Dictionary, error)
The SpecIterator method retrieves a list of Perforce specs (for example, client, label, branch) and iterates over them to fetch detailed information for each spec. It returns the results as a slice of Dictionary objects, where each dictionary represents a single spec with its key-value pairs.
This method is particularly useful for retrieving and processing multiple specs of a specific type (such as, all clients, all labels) in a structured format.
Supported spec types are:
-
clients -
labels -
branches -
changes -
streams -
jobs -
users -
groups -
depots -
servers -
ldaps -
remotes
// Example : Retrieve the first 5 labels.
labels, err := p4.SpecIterator("labels", "-m", "5")
if err != nil {
fmt.Println("Error fetching labels:", err)
return
}
// Print label details
for _, label := range labels {
fmt.Println("Label:", label["Label"])
fmt.Println("Owner:", label["Owner"])
fmt.Println("Description:", label["Description"])
fmt.Println("----")
}
Configuration Management
-
SetInput(input ...string)Sets the input for the nextPerforce command. This method is useful for commands that require user input, such as submitting a changelist, resolving conflicts, or creating specs. The input provided will be consumed by the next command executed via the
Runmethod.Copy// Example : Use SetInput to provide the changelist description
// or other required input for the submit command.
changeSpec, _ := p4.RunFetch("change")
changeSpec["Description"] = "Submitting changes via SetInput"
formattedSpec, err := p4.FormatSpec("change", changeSpec)
p4.SetInput(formattedSpec)
result := p4.Run("submit", "-i")
fmt.Println("Submit Result:", result) -
SetEnv(env string, value string)Sets an environment variable for the Perforce client.
Copy_, err := p4.SetEnv("P4PORT", "perforce:1666")
fmt.Println("P4PORT set to:", p4.Env("P4PORT")) -
Env(env string) -> stringRetrieves the value of an environment variable.
Copyfmt.Println("P4PORT:", p4.Env("P4PORT")) -
SetEnviroFile(enviroFile string)Sets the path to the Perforce environment file.
Copyp4.SetEnviroFile("/path/to/enviro")
fmt.Println("Enviro file set to:", p4.EnviroFile()) -
EnviroFile() -> stringRetrieves the path to the Perforce environment file.
Copyfmt.Println("Enviro file path:", p4.EnviroFile()) -
SetCharset(charset string)Sets the character set for the Perforce client.
Copy_, err := p4.SetCharset("utf8")
fmt.Println("Charset set to:", p4.Charset()) -
Charset() -> stringRetrieves the current character set.
Copyfmt.Println("Current charset:", p4.Charset()) -
SetCwd(cwd string)Sets the current working directory for the Perforce client.
Copyp4.SetCwd("/path/to/workspace")
fmt.Println("Working directory set to:", p4.Cwd()) -
Cwd() -> stringRetrieves the current working directory.
Copyfmt.Println("Current working directory:", p4.Cwd()) -
SetClient(client string)Sets the client workspace name.
Copyp4.SetClient("my_client")
fmt.Println("Client workspace set to:", p4.Client()) -
Client() -> stringRetrieves the current client workspace name.
Copyfmt.Println("Current client workspace:", p4.Client()) -
SetUser(user string)Sets the username for the Perforce client.
Copyp4.SetUser("username")
fmt.Println("User set to:", p4.User()) -
User() -> stringRetrieves the current username.
Copyfmt.Println("Current user:", p4.User()) -
SetPassword(password string)Sets the password for the Perforce client.
Copyp4.SetPassword("mypassword")
fmt.Println("Password set.") -
Password() -> stringRetrieves the current password.
Copyfmt.Println("Current password:", p4.Password()) -
SetPort(port string)Sets the P4 Server port.
Copyp4.SetPort("perforce:1666")
fmt.Println("Server port set to:", p4.Port()) -
Port() -> stringRetrieves the current P4 Server port.
Copyfmt.Println("Current server port:", p4.Port()) -
SetProg(prog string)Sets the program name for the Perforce client.
Copyp4.SetProg("my_program")
fmt.Println("Program name set to:", p4.Prog()) -
Prog() -> stringRetrieves the current program name.
Copyfmt.Println("Current program name:", p4.Prog()) -
SetTicketFile(ticketFile string)Sets the path to the Perforce tickets file.
Copyp4.SetTicketFile("/path/to/tickets")
fmt.Println("Ticket file set to:", p4.TicketFile()) -
TicketFile() -> stringRetrieves the path to the Perforce tickets file.
Copyfmt.Println("Current ticket file path:", p4.TicketFile()) -
SetTrustFile(trustFile string)Sets the path to the Perforce trust file.
Copyp4.SetTrustFile("/path/to/trust")
fmt.Println("Trust file set to:", p4.TrustFile()) -
TrustFile() -> stringRetrieves the path to the Perforce trust file.
Copyfmt.Println("Current trust file path:", p4.TrustFile()) -
SetVar(variable string, value string)Sets a Perforce variable.
Copyp4.SetVar("P4DEBUG", "1")
fmt.Println("P4DEBUG set.") -
SetProtocol(protocol string, value string)Sets a Perforce protocol variable.
Copyp4.SetProtocol("api", "80")
fmt.Println("Protocol set.") -
Version() -> stringRetrieves the Perforce client version.This method is used to get the version of the Perforce client API being used, which can be helpful for debugging or compatibility checks.
Copyversion := p4.Version()
fmt.Println("Client Version:", version) -
SetVersion(version string)Sets the Perforce client version.
This method is used to specify the version of the client API, which can be useful for compatibility with specific server versions.Copyp4.SetVersion("2023.1")
fmt.Println("Client version set to:", p4.Version()) -
SetHost(host string)Sets the hostname for the Perforce client. This is used to identify the client machine to the P4 Server.
Copyp4.SetHost("my-hostname")
fmt.Println("Host set to:", p4.Host()) -
Host() stringRetrieves the hostname of the Perforce client.
Copyhost := p4.Host()
fmt.Println("Current Host:", host) -
SetIgnoreFile(ignoreFile string)Sets the path to the ignore file for the Perforce client. The ignore file specifies files or directories to exclude from version control.
Copyp4.SetIgnoreFile(".p4ignore")
fmt.Println("Ignore file set to:", p4.IgnoreFile()) -
IgnoreFile() stringRetrieves the path to the ignore file used by the Perforce client.
CopyignoreFile := p4.IgnoreFile()
fmt.Println("Current Ignore File:", ignoreFile) -
Ignored(path string) boolChecks if a specified file or directory is ignored based on the ignore file.
CopyisIgnored := p4.Ignored("temp.txt")
if isIgnored {
fmt.Println("File temp.txt is ignored.")
} else {
fmt.Println("File temp.txt is not ignored.")
} -
SetLanguage(language string)Sets the language for the Perforce client. This is used for localization and internationalization.
Copyp4.SetLanguage("en")
fmt.Println("Language set to:", p4.Language()) -
Language() stringRetrieves the current language setting of the Perforce client.
Copylanguage := p4.Language()
fmt.Println("Current Language:", language) -
GetP4ConfigFile() stringRetrieves the path to the Perforce configuration file (
P4CONFIG) used by the client.CopyconfigFile := p4.GetP4ConfigFile()
fmt.Println("P4 Config File:", configFile) -
ApiLevel() intRetrieves the API level of the Perforce client. The API level determines the features and behaviors supported by the client.
CopyapiLevel := p4.ApiLevel()
fmt.Println("Current API Level:", apiLevel) -
SetApiLevel(apiLevel int)Sets the API level for the Perforce client. This is useful for enabling or disabling specific features based on the API version.
Copyp4.SetApiLevel(80)
fmt.Println("API Level set to 80.") -
Streams() boolChecks if streams are enabled for the Perforce client. Streams are a feature for managing branching and merging workflows.
Copyif p4.Streams() {
fmt.Println("Streams are enabled.")
} else {
fmt.Println("Streams are not enabled.")
} -
SetStreams(enableStreams bool)Enables or disables streams for the Perforce client.
Copyp4.SetStreams(true)
fmt.Println("Streams enabled.") -
Tagged() boolChecks if tagged output is enabled for the Perforce client. Tagged output provides structured data for easier parsing.
Copyif p4.Tagged() {
fmt.Println("Tagged output is enabled.")
} else {
fmt.Println("Tagged output is not enabled.")
} -
SetTagged(enableTagged bool)Enables or disables tagged output for the Perforce client.
Copyp4.SetTagged(true)
fmt.Println("Tagged output enabled.") -
Track() boolChecks if tracking is enabled for the Perforce client. Tracking provides additional information about command execution.
Copyif p4.Track() {
fmt.Println("Tracking is enabled.")
} else {
fmt.Println("Tracking is not enabled.")
} -
SetTrack(enableTrack bool)Enables or disables performance tracking for thePerforce client. This setting must be configured before establishing a connection to the client. By default, tracking is disabled (
false).Copyresult, err := p4.SetTrack(true)
if err != nil {
fmt.Println("Error in setting track:", err)
}
fmt.Println("Tracking enabled.") -
Graph() boolChecks if graph depot support is enabled for the Perforce client. Graph depots are used for managing Git repositories in Perforce.
Copyif p4.Graph() {
fmt.Println("Graph depot support is enabled.")
} else {
fmt.Println("Graph depot support is not enabled.")
} -
SetGraph(enableGraph bool)Enables or disables graph depot support for the Perforce client.
Copyp4.SetGraph(true)
fmt.Println("Graph depot support enabled.") -
Debug() intRetrieves the current debug level for the Perforce client. The debug level controls the verbosity of debug output.
CopydebugLevel := p4.Debug()
fmt.Println("Current Debug Level:", debugLevel) -
SetDebug(debugLevel int)Sets the debug level for the Perforce client.
Copyp4.SetDebug(2)
fmt.Println("Debug level set to 2.") -
MaxResults() intRetrieves the maximum number of results that the Perforce client will return for a command.
CopymaxResults := p4.MaxResults()
fmt.Println("Max Results:", maxResults) -
SetResults(maxResults int)Sets the maximum number of results that the Perforce client will return for a command.
Copyp4.SetResults(1000)
fmt.Println("Max Results set to 1000.") -
MaxScanRows() intRetrieves the maximum number of rows that the Perforce client will scan for a command.
CopymaxScanRows := p4.MaxScanRows()
fmt.Println("Max Scan Rows:", maxScanRows) -
SetMaxScanRows(maxScanRows int)Sets the maximum number of rows that the Perforce client will scan for a command.
Copyp4.SetMaxScanRows(5000)
fmt.Println("Max Scan Rows set to 5000.") -
MaxLockTime() intRetrieves the maximum lock time (in milliseconds) for a command executed by the Perforce client.
CopymaxLockTime := p4.MaxLockTime()
fmt.Println("Max Lock Time:", maxLockTime, "ms") -
SetMaxLockTime(maxLockTime int)Sets the maximum lock time (in milliseconds) for a command executed by the Perforce client.
Copyp4.SetMaxLockTime(10000)
fmt.Println("Max Lock Time set to 10000 ms.")
Handlers
-
SetProgress(progress P4Progress)Sets a progress handler for the Perforce client. The progress handler is used to track the progress of long-running commands, such as sync or
submit. The handler implements theP4Progressinterface, which provides methods to monitor progress updates.CopyprogressHandler := &MyProgressHandler{}
p4.SetProgress(progressHandler)
p4.Run("sync", "//...") -
SetHandler(handler P4OutputHandler)Sets an output handler for the Perforce client. The output handler is used to process the output of Perforce commands, such as text, binary data, or structured dictionaries. The handler implements the
P4OutputHandlerinterface.CopyoutputHandler := &MyOutputHandler{}
p4.SetHandler(outputHandler)
p4.Run("files", "//...") -
SetSSOHandler(handler P4SSOHandler)Sets a single sign-on (SSO) handler for the Perforce client. The SSO handler is used to manage authentication when SSO is enabled on the P4 Server. The handler implements the
P4SSOHandlerinterface.CopyssoHandler := &MySSOHandler{}
p4.SetSSOHandler(ssoHandler)
p4.Run("login") -
SetResolveHandler(handler P4ResolveHandler)Sets a resolve handler for the Perforce client. The resolve handler is used to manage file conflict resolution during operations like
mergeorintegrate. The handler implements theP4ResolveHandlerinterface.CopyresolveHandler := &MyResolveHandler{}
p4.SetResolveHandler(resolveHandler)
p4.Run("resolve")