Quick start for P4 API for Ruby on Windows

Before you begin

Ensure you have the following:

  • P4 API for C/C++ for Windows. P4 API for Ruby depends on the native Perforce C/C++ API.

    • On Windows, this API is not installed automatically and must be installed before running gem install p4ruby.

    • You must have a version of P4 API for C/C++ that is compatible with P4 API for Ruby. To learn more, see Get P4 API for C/C++

  • A compatible version of Ruby: P4 API for Ruby works with Ruby Versions 3.2, 3.3 or 3.4.

    Use RubyInstaller x64 with DevKit. Ruby installations without DevKit or using MSVC builds are not supported.
  • Access to a working version of P4 Server.

  • The server and port values for P4 Server.

  • The username for your P4 user.

  • The name of the workspace that contains the files you want to check out, edit, and commit.

  • (Optional) A working version of P4V, to check if a file has been added to a changelist.

Install P4 API for Ruby

The easiest way to install the P4 API for Ruby is to use the terminal and install the package with gem.

  1. Open the command prompt.

  2. Install P4 API for Ruby using the following command:

    gem install p4ruby

    If the P4 API for C/C++ is installed in a standard location, it is detected automatically.

    If detection fails, rerun the command and specify the API location:

    gem install p4ruby -- --with-p4api-dir=C:/p4api

  3. If the installation succeeds, P4 API for Ruby is installed with no errors.

  4. (Optional )To check P4 API for Ruby has been installed, run the following:

    ruby -rP4 -e "puts P4.identify"

    If successfully installed, the version of P4 API for Ruby is output to the terminal.

For more information on installing P4 API for Ruby, see Installing P4 API for Ruby.

Connect the API to P4 Server

Use the following script to connect to P4 Server and view the first 10 files in a given workspace.

Update the following credentials in the script:

  • p4.port - Add the server and port to connect to in the format: server:port

  • p4.user - A username for your P4 user.

  • p4.client - The name of the workspace you want to connect to.

Call the script something simple like connect_to_p4.rb

Copy
require 'P4'

def main
  p4 = P4.new

  # --- Tailor these to your environment ---
  p4.port   = "localhost:1666"      # server:port
  p4.user   = "P4UserName"          # username
  p4.client = "ruby_projects_main"  # workspace name

  begin
    p4.connect

    info = p4.run_info.first
    puts "Connected to: #{info['serverAddress']}"

    files = p4.run_have.first(10)
    # Displays up to the first 10 files in the workspace

    files.each do |f|
      puts " - #{f['depotFile']} ##{f['rev']}"
    end

  rescue P4Exception => e
    p4.errors.each do |err|
      puts "P4 error: #{err}"
    end

  ensure
    if p4.connected?
      p4.disconnect
      puts "Disconnected from the P4 Server."
    end
  end
end

main if __FILE__ == $PROGRAM_NAME

To run the script:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run ruby connect_to_p4.rb (If you have given the script a different name, use that name).

  3. Check the output.

You should see up to 10 files listed in your chosen workspace.

If you receive any errors when connecting to the P4 Server, see Troubleshooting.

Check out a file

The following script will:

  • Connect to P4 Server with your credentials (user and workspace).

  • Create a pending changelist with a simple description.

  • Open the target file for edit in that changelist.

  • Return a brief summary of what has been done.

    • This returns a changelist number. This number is needed when submitting the file.

  • Disconnect from the P4 Server cleanly.

Update the following credentials in the script:

  • P4PORT - Add the server and port to connect to in the format: server:port

  • P4USER - A username for your P4 user.

  • P4CLIENT - The name of the workspace you want to connect to.

  • DEPOT_FILE - Filepath to the file to edit. For example: //DemoDepot/ruby/Ascii_art/README.md

Call the script something simple like check_out_file.rb

Copy
require 'P4'
require 'time'

def main
  # --- Tailor these to your environment ---
  p4port     = "localhost:1666"
  p4user     = "P4UserName"
  p4client   = "ruby_projects_main"
  depot_file = "//DemoDepot/ruby/Ascii_art/README.md"

  p4 = P4.new
  p4.port   = p4port
  p4.user   = p4user
  p4.client = p4client

  begin
    p4.connect
    info = p4.run_info.first
    puts "Connected to #{info['serverAddress']} (workspace: #{p4client})"

    # 1) Create a pending changelist
    change = p4.fetch_change
    change["Description"] =
      "Edit #{depot_file} via P4Ruby (#{Time.now.strftime('%Y-%m-%d %H:%M:%S')})"

    saved = p4.save_change(change)
    # Example: ["Change 12345 created."]
    cl_number = saved.first.split[1].to_i
    puts "Created changelist #{cl_number}"

    # 2) Open the file for edit in that changelist
    p4.run_edit("-c", cl_number.to_s, depot_file)
    puts "Opened for edit: #{depot_file} (cl #{cl_number})"

    # 3) Show a short “opened” summary
    opened = p4.run_opened(depot_file)
    opened.each do |o|
      puts "#{o['depotFile']} (#{o['action']}) cl=#{o['change']} -> #{o['clientFile']}"
    end

    puts "Changelist number: #{cl_number}"
    puts "Make a note of this number. You will need it to submit the file."

  rescue P4Exception
    p4.errors.each do |e|
      puts "P4 error: #{e}"
    end

  ensure
    if p4.connected?
      p4.disconnect
      puts "Disconnected from the P4 Server."
    end
  end
end

main if __FILE__ == $PROGRAM_NAME

To run the script:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run ruby check_out_file.rb (If you have given the script a different name, use that name)

  3. Make a note of the changelist number. You will need this to commit the file.

Your chosen file is now available to edit.

If you have P4V, you will see a new changelist with your selected file.

Commit a file

The following script will:

  • Prompt you for the changelist number.

  • Connect to the P4 Server

  • Fetch the changelist to ensure it’s pending.

  • Show the current description, then prompt you to add any more detail for the changelist description.

  • Submit the changelist and prints the result.

  • Disconnect from P4 Server.

Update the following credentials in the script:

  • P4PORT - Add the server and port to connect to in the format: server:port

  • P4USER - A username for your P4 user.

  • P4CLIENT - The name of the workspace you want to connect to.

Call the script something simple like commit_file.rb

Copy
require 'P4'

def main
  # --- Tailor these values ---
  p4port   = "localhost:1666"
  p4user   = "P4UserName"
  p4client = "ruby_projects_main"

  # Get changelist number (argument or prompt)
  cl_number =
    if ARGV.length == 1
      ARGV[0]
    else
      print "Enter the changelist number to submit: "
      STDIN.gets&.strip
    end

  if cl_number.nil? || cl_number.empty?
    puts "No changelist number provided. Exiting."
    exit 1
  end

  p4 = P4.new
  p4.port   = p4port
  p4.user   = p4user
  p4.client = p4client

  begin
    p4.connect
    info = p4.run_info.first
    puts "Connected to #{info['serverAddress']} (workspace: #{p4client})"

    # Fetch the change to validate and optionally update description
    change = p4.fetch_change(cl_number)
    status = (change["Status"] || "").downcase

    if status != "pending"
      puts "Changelist #{cl_number} is not pending (status: #{change['Status']})."
      return
    end

    # Show current description
    puts "Current description:"
    puts "--------------------"
    puts change["Description"].to_s.rstrip
    puts "--------------------"

    print "Add a submit comment (leave blank to keep as-is): "
    user_note = STDIN.gets&.strip

    if user_note && !user_note.empty?
      base_desc = change["Description"].to_s.rstrip
      new_desc =
        if base_desc.empty?
          user_note
        else
          "#{base_desc}\n\n#{user_note}"
        end

      change["Description"] = new_desc
      p4.save_change(change)
      puts "Updated changelist description."
    end

    # Submit the changelist
    result = p4.run_submit("-c", cl_number)

    puts "Submit result:"
    result.each do |entry|
      puts "  #{entry}"
    end

    puts "Submitted changelist #{cl_number}"

  rescue P4Exception
    p4.errors.each do |e|
      puts "P4 error: #{e}"
    end

  ensure
    if p4.connected?
      p4.disconnect
      puts "Disconnected from the P4 Server."
    end
  end
end

main if __FILE__ == $PROGRAM_NAME
``

To run the script:

  1. Open a terminal and navigate to the folder containing the script.

  2. Run ruby commit_file.rb .

  3. When asked, enter the changelist number with the file you want to commit.

  4. (Optional) Enter a changelist description.

Your chosen file has now been committed. If you check P4V, you will no longer be able to see the pending changelist.

Next steps

View the documentation for P4 API for Ruby classes to see what other commands are available when using P4 API for Ruby.