1<?php
2
3final class ArcanistCallConduitWorkflow
4  extends ArcanistArcWorkflow {
5
6  public function getWorkflowName() {
7    return 'call-conduit';
8  }
9
10  public function getWorkflowInformation() {
11    $help = pht(<<<EOTEXT
12Allows you to make a raw Conduit method call:
13
14  - Run this command from a working directory.
15  - Call parameters are required, and read as a JSON blob from stdin.
16  - Results are written to stdout as a JSON blob.
17
18This workflow is primarily useful for writing scripts which integrate
19with Phabricator. Examples:
20
21  $ echo '{}' | arc call-conduit -- conduit.ping
22  $ echo '{"phid":"PHID-FILE-xxxx"}' | arc call-conduit -- file.download
23EOTEXT
24      );
25
26    return $this->newWorkflowInformation()
27      ->setSynopsis(pht('Call Conduit API methods.'))
28      ->addExample('**call-conduit** -- __method__')
29      ->setHelp($help);
30  }
31
32  public function getWorkflowArguments() {
33    return array(
34      $this->newWorkflowArgument('method')
35        ->setWildcard(true),
36    );
37  }
38
39  public function runWorkflow() {
40    $method = $this->getArgument('method');
41    if (count($method) !== 1) {
42      throw new PhutilArgumentUsageException(
43        pht('Provide exactly one Conduit method name to call.'));
44    }
45    $method = head($method);
46
47    $params = $this->readStdin();
48    try {
49      $params = phutil_json_decode($params);
50    } catch (PhutilJSONParserException $ex) {
51      throw new ArcanistUsageException(
52        pht('Provide method parameters on stdin as a JSON blob.'));
53    }
54
55    $engine = $this->getConduitEngine();
56    $conduit_future = $engine->newFuture($method, $params);
57
58    $error = null;
59    $error_message = null;
60    try {
61      $result = $conduit_future->resolve();
62    } catch (ConduitClientException $ex) {
63      $error = $ex->getErrorCode();
64      $error_message = $ex->getMessage();
65      $result = null;
66    }
67
68    echo id(new PhutilJSON())->encodeFormatted(
69      array(
70        'error' => $error,
71        'errorMessage' => $error_message,
72        'response' => $result,
73      ));
74
75    return 0;
76  }
77
78}
79