Coder Social home page Coder Social logo

p4api's Introduction


This project is no longer maintained


p4api

With p4api, you can execute Perforce commands according to 4 modes in your choice:

Async command Sync command
Marshal syntax cmd() cmdSync()
Raw syntax rawCmd() rawCmdSync()

Asynchronous command returns a promise wich will be resolved with the Perforce result while sync command is blocked until Perforce has returned a result.

Promise returned with Sync command can be canceled with cancel() method, killing launched p4 process.

Marshal syntax consists to use global -G option allowing to provide input and receive result as a JS object.
Raw syntax uses basic text format.
Note that only login command accepts input parameter (password) as a string in both Marshal and Raw modes.

If P4VC is installed, you will be able to launch any p4vc command with visual() method wich returns a promise wich is resolved when p4vc has closed.

All these method belong to class P4 provided by the module p4api: See detail here



Installation

Get the module from NPM

$ npm install p4api --save

Development

Use build action (npm or yarn) to build lib/p4api.js.

To test it, you need to have installed "Helix Core Apps" and "Helix Versioning Engine" (p4 & p4d).

P4 object

Contructor

import {P4} from "p4api"
const p4 = new P4({p4set:{}, binPath: '', debug: false})

where

  • p4set : a set of P4 variables to apply as context when executing p4 commands:
    • all P4 environnment variables like P4PORT, P4CHARSET, P4USER, P4CLIENT, ...
    • p4api specific option like:
      • P4API_TIMEOUT: timeout in ms for p4 commands process
  • binPath : a path prefix to add to the call for p4 and p4vc
  • debug : if true, display some debug info

Example:

const p4 = new P4({ 
    p4set: {
        P4PORT: "myP4Server:1666",
        P4CHARSET: "utf8",
        P4API_TIMEOUT: 5000},
    binPath: '/usr/sbin/'
})

ℹ️ INFO:
Old constructor syntax before V3.4 is still allowed. Ex : p4 = new P4({P4PORT: "myP4Server:1666"})

⚠️ WARNING:
P4CLIENT, P4PORT & P4USER will never be overloaded with variable set in a P4CONFIG file

Static Attributs

Name Description
Error Error instance
TimeoutError Error instance

Methods

Change environment variables

setOpts(opt) and addOpts(opt) allow you to set or merge environment variables.

import {P4} from "p4api"
const p4 = new P4({p4set: {P4PORT: "p4server:1666"}})

p4.setOpts({env:{P4PORT: "newServer:1666"}})
p4.addOpts({env:{P4USER: "bob", P4CLIENT="bob_client"}}

Where:

  • opt is the option parameter injected in spawn() function

⚠️ WARNING:
In the most current case, use only the field env in opt.
Use other fields than env is not tested !

Marshal syntax commands

cmd(p4Cmd, [input]) and cmdSync(p4Cmd, [input]) allow to execute any p4 command using Marshal syntax (global p4 option -G).

import {P4} from "p4api"
const p4 = new P4({p4set: {P4PORT: "p4server:1666"}})

// Asynchro mode
p4.cmd(p4Cmd, input)
  .then(out => {
    // ...
  }
  .catch(err) {
    throw ("p4 not found");
  };

// Asynchro with async-await
try {
  let out = await p4.cmd(p4Cmd, input);
} catch (err) {
  throw ("p4 not found");
}


// Synchro mode
try {
  let out = p4.cmdSync(p4Cmd, input);
} catch (err) {
  throw ("p4 not found");
}

Where:

  • p4Cmd is the Perforce command (string) with options separated with space.
  • input is a optional string or object for input value (like password for login command or client object for client command).

p4.cmd() return a promise which is resolved with the marshalled result of the command as an object (out).
p4.cmdSync() return the marshal result of the command as an object (out).

out has the following structure:

  • prompt: string printed by perforce before the result (else empty string)
  • stat: if exists, list of all result with code=stat
  • info: if exists, list of all result with code=info
  • error: if exists, list of all result with code=error

Row syntax commands

rawCmd(p4Cmd, [input]) and rawCmdSync(p4Cmd, [input]) allow to execute any p4 command using text syntax. Arguments and result are similar to the last method except that the marshalled syntax is replaced with a raw text syntax. Both raw methods return result as the following structure:

  • text: success result string or empty string
  • error: error result string or empty string

Error handling

If p4 client can not be executed (perforce not installed, bad path variable, ...), cmd is rejected and cmdSync is throwed with a P4.Error Error instance.

When timeout is reached, cmd is rejected and cmdSync is throwed with a P4.TimeoutError Error instance with message like 'Timeout <timeout>ms reached'

import {P4} from "p4api";
let p4 = new P4({p4set: {{P4PORT: "p4server:1666", P4API_TIMEOUT: 5000}});

function P4Error(msg) {
  this.name = "p4 error";
  this.message = msg;
}

async function p4(cmd, input) {
  let out
  try {
    out = await p4.cmd(cmd, input)
  } catch (err) {
    if (err instanceof P4.TimeoutError) {
      // Time out error
      throw new Error("p4 timeout " + err.timeout + " ms");
    }
    if (err instanceof P4.Error) {
      // Time out error
      throw new Error("p4 execution error. Check perforce installation");
    }
    // Critical error : not expected
    throw new Error("I don't know what appends");
  }
  if (out.error !== undefined) {
    // p4 command error
    throw new P4Error(out.error);
  }
  return out;
}

Cancellation feature

A promise returned by p4.cmd() can be canceled with cancel() method, killing launched p4 process.

Examples

List of depots

import {P4} from "p4api";
let p4 = new P4({p4set: {{P4PORT: "p4server:1666"}});
    
p4.cmd("depots").then(function(out){console.log(out);});

Result is like:

    {
      "prompt": "",
      "stat": [
        {
          "code": "stat",
          "name": "CM",
          "time": "1314373478",
          "type": "local",
          "map": "/perforce/Data/CM/...",
          "desc": "Created by xxxx. ..."
        },
        {
          "code": "stat",
          "name": "depot",
          "time": "1314374519",
          "type": "local",
          "map": "/perforce/Data/depot/...",
          "desc": "Created by xxxx. ..."
        }
      ]
    }

Command Error

    ...
    p4.cmd("mistake")
    ...

Result is:

{
  "prompt": "",
  "error": [
    {
      "code": "error",
      "data": "Unknown command.  Try \"p4 help\" for info.\n",
      "severity": 3,
      "generic": 1
    }
  ]
}

Login (command with prompt and input)

    ...
    p4.cmd("login", "myGoodPasswd")
    ...

Result is like:

{
  "prompt": "Enter password: ↵",
  "info": [
    {
      "code": "info",
      "data": "Success:  Password verified.",
      "level": 5
    },
    {
      "code": "info",
      "data": "User toto logged in.",
      "level": 0
    }
  ]
}

Check Login (command with param)

    ...
    p4.cmd("login -s")
    ...

Result is like:

{
  "prompt": "",
  "stat": [
    {
      "code": "stat",
      "TicketExpiration": "85062",
      "user": "toto"
    }
  ]
}   

Clear viewpathes of the current Client

async function clearViewPathes() {
  let out = await p4.cmd("client -o")
  let client = out.stat[0]
  for (let i = 0;; i++) {
    if (client["View" + i] === undefined) break
    delete client["View" + i]
  }
  await p4.cmd("client -i", client)
  await p4.cmd("sync -f")
}

Cancellation

let p4Promise = p4.cmd("clients");
...
let   result = null;
if (DoNotNeedResult) {
  p4Promise.cancel();
} else {
  result = await p4Promise;
}

p4api's People

Contributors

dependabot[bot] avatar liambest avatar pierreduot avatar pisamad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

p4api's Issues

Add ability to remove -G option from command to get raw output

I would like to get a unified diff between two versions of a file, and the -G option prevents p4 diff2 -u //some/file#1 //some/file#2 from returning appropriate results.

It looks like this repo has worked around this by using the p4-oo package, but would be nice to have everything available in p4api.

Invalid marchalled error

This is concerning only P4.cmdSync() with input option and when length of an input is upper then 128 bytes.
Ex : P4.cmdSync ('label -i' , {Label:'myLabel', 'Description:'Bla .... Bla ..... (length >= 128)'})

P4 result is an error : 'Invalid marchalled'

Can't require p4api after install

% node --version
v8.11.2

% npm --version
5.6.0

% npm install p4api --save
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN perforce No description
npm WARN perforce No repository field.
npm WARN perforce No license field.

% node

let { P4 } = require('p4api')
Error: Cannot find module 'p4api'
at Function.Module._resolveFilename (module.js:547:15)
at Function.Module._load (module.js:474:25)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)

Do you have any suggestion about above usage?

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type object

I keep getting this error:

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type object
    at Function.from (buffer.js:219:9)
    at convertOut (C:\git\myproject\node_modules\p4api\lib\p4api.js:23971:87)
    at P4.cmdSync (C:\git\myproject\node_modules\p4api\lib\p4api.js:17952:840)
    at Perforce.getChangelist (C:\git\myproject\src\lib\perforce.js:124:27)
    at Args.parse (C:\git\myproject\src\lib\args.js:84:30)
    at start (C:\git\myproject\main.js:42:23)
    at App.checkP4Config (C:\git\myproject\main.js:71:10)
    at App.emit (events.js:205:15)

which really makes no sense because the command I am making is:

var cmd = "changes -m1 -s submitted C:/Perforce/...#have";
p4.cmdSync(cmd);

So, I'm clearly passing a string, which makes the error very confusing :(

Publish latest changes to npm

Hey there, is there any chance you could publish latest to npm? I was hoping to pull down my binary path change from December into a project.

Please specify a license for this project

Without a specific license for this project, it is difficult for others to use, legally. Could you please choose one and update the README and package.json file appropriately (and probably add a LICENSE.txt file as well). Thank you for writing this very useful library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.