Create a new client workspace based on an existing template

The following is an example of how to create a new client workspace based on an existing template with P4 API for Go.

Copy
package main

import (
    "fmt"
    "log"
    "p4"
)

func main() {
    p4api := p4.New()
    defer p4api.Close()
    
    // Set connection details
    p4api.SetPort("perforce:1666")
    p4api.SetUser("username")
    p4api.SetPassword("password")
    
    template := "my-client-template"
    clientRoot := "c:\\p4-work"
    clientName := "my-new-client"
    
    // Connect to the P4 server
    if _, err := p4api.Connect(); err != nil {
        log.Fatalf("Failed to connect to P4 server: %v", err)
    }
    
    // Fetch the client spec based on the template
    spec, err := p4api.RunFetch("client", "-t", template, clientName)
    if err != nil {
        log.Fatalf("Failed to fetch client spec: %v", err)
    }
    
    // Update the client spec fields
    spec["Root"] = clientRoot
    if options, ok := spec["Options"]; ok {
        spec["Options"] = strings.Replace(options, "normdir", "rmdir", 1)
    }
    
    // Save the updated client spec
    if _, err := p4api.RunSave("client", spec); err != nil {
        log.Fatalf("Failed to save client spec: %v", err)
    }
    
    // Set the new client
    p4api.SetClient(clientName)
    
    // Sync the client workspace
    if _, err := p4api.Run("sync"); err != nil {
        log.Fatalf("Failed to sync client workspace: %v", err)
    }
    
    fmt.Println("Client workspace created and synced successfully.")
}