Specify global options for a Perforce command run using p4api

429 Views Asked by At

I am using the Perforce, a.k.a. Helix Core, C++ API to programmatically run a Perforce command. How do I specify a global option for the command?

For example, I want to programmatically run the clients command with several global options. If run from a command shell, it would look like the following.

p4 -z tag -F %client% clients -u mikef

The global options I want, -z and -F, are not ones that you can specify via environment variables, as far as I know. But even if you could, I cannot rely on the user to set them.

On a lark, I added the global options to the argument array provided to the ClientApi object. For example:

#include <p4/clientapi.h>
#include "CustomClientUser.h"  // A class I derived from ClientUser

// Connect to server.
StrBuf msg;
Error e;
ClientApi client;
client.SetProtocol( "tag", "" );
client.Init( &e );
if ( e.Test() )
{
  e.Fmt( &msg );
  fprintf( "%s\n", msg.Text() );
  return;
}

// Use my own client user.
CustomClientUser cu;

// Run the command.  Try adding global options at the beginning of the arg array.
char * argv[] = { "-z", "tag", "-u", "td27117" };
int argc = sizeof( argv ) / sizeof( char * );
client.SetArgv( argc, argv );
client.Run( "clients", &cu );

But, that did not work. The error output is what you would expect when you give it a command option it does not understand.

Usage: clients [ -t ] [ -u user ] [ -U ] [ [-e|-E] query -m max ] [ -a | -s serverID ] [ -S stream ]
Invalid option: -z.
1

There are 1 best solutions below

2
On BEST ANSWER

The global options are arguments to the client app, not the server. The Run() method is for sending commands/arguments to the server; if you send it the client-side args it won't know what to do with them.

To tell the client to set the "tag" protocol, do:

client.SetProtocol("tag", "");

Note that this must be called before you call Run() since it modifies the protocol that is used by Run().

If you want to see how the various global options are implemented, you can just look at the p4 source code.

Note that most of the global options correspond directly to ClientApi methods, which you can see in the header (clientapi.h) or in the documentation: https://www.perforce.com/manuals/v15.1/p4api/chapter.methods.html#clientapi