summaryrefslogtreecommitdiffstats
path: root/toolkit/jetpack/sdk/system/child_process/subprocess.js
blob: e3454e95b54f7cc2e55068e2e909fa67963f9f5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict';

const { Ci, Cu } = require("chrome");

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Subprocess.jsm");
Cu.import("resource://gre/modules/Task.jsm");

const Runtime = require("sdk/system/runtime");
const Environment = require("sdk/system/environment").env;
const DEFAULT_ENVIRONMENT = [];
if (Runtime.OS == "Linux" && "DISPLAY" in Environment) {
  DEFAULT_ENVIRONMENT.push("DISPLAY=" + Environment.DISPLAY);
}

function awaitPromise(promise) {
  let value;
  let resolved = null;
  promise.then(val => {
    resolved = true;
    value = val;
  }, val => {
    resolved = false;
    value = val;
  });

  while (resolved === null)
    Services.tm.mainThread.processNextEvent(true);

  if (resolved === true)
    return value;
  throw value;
}

let readAllData = Task.async(function* (pipe, read, callback) {
  let string;
  while (string = yield read(pipe))
    callback(string);
});

let write = (pipe, data) => {
  let buffer = new Uint8Array(Array.from(data, c => c.charCodeAt(0)));
  return pipe.write(data);
};

var subprocess = {
  call: function(options) {
    var result;

    let procPromise = Task.spawn(function*() {
      let opts = {};

      if (options.mergeStderr) {
        opts.stderr = "stdout"
      } else if (options.stderr) {
        opts.stderr = "pipe";
      }

      if (options.command instanceof Ci.nsIFile) {
        opts.command = options.command.path;
      } else {
        opts.command = yield Subprocess.pathSearch(options.command);
      }

      if (options.workdir) {
        opts.workdir = options.workdir;
      }

      opts.arguments = options.arguments || [];


      // Set up environment

      let envVars = options.environment || DEFAULT_ENVIRONMENT;
      if (envVars.length) {
        let environment = {};
        for (let val of envVars) {
          let idx = val.indexOf("=");
          if (idx >= 0)
            environment[val.slice(0, idx)] = val.slice(idx + 1);
        }

        opts.environment = environment;
      }


      let proc = yield Subprocess.call(opts);

      Object.defineProperty(result, "pid", {
        value: proc.pid,
        enumerable: true,
        configurable: true,
      });


      let promises = [];

      // Set up IO handlers.

      let read = pipe => pipe.readString();
      if (options.charset === null) {
        read = pipe => {
          return pipe.read().then(buffer => {
            return String.fromCharCode(...buffer);
          });
        };
      }

      if (options.stdout)
        promises.push(readAllData(proc.stdout, read, options.stdout));

      if (options.stderr && proc.stderr)
        promises.push(readAllData(proc.stderr, read, options.stderr));

      // Process stdin

      if (typeof options.stdin === "string") {
        write(proc.stdin, options.stdin);
        proc.stdin.close();
      }


      // Handle process completion

      if (options.done)
        Promise.all(promises)
          .then(() => proc.wait())
          .then(options.done);

      return proc;
    });

    procPromise.catch(e => {
      if (options.done)
        options.done({exitCode: -1}, e);
      else
        Cu.reportError(e instanceof Error ? e : e.message || e);
    });

    if (typeof options.stdin === "function") {
      // Unfortunately, some callers (child_process.js) depend on this
      // being called synchronously.
      options.stdin({
        write(val) {
          procPromise.then(proc => {
            write(proc.stdin, val);
          });
        },

        close() {
          procPromise.then(proc => {
            proc.stdin.close();
          });
        },
      });
    }

    result = {
      get pid() {
        return awaitPromise(procPromise.then(proc => {
          return proc.pid;
        }));
      },

      wait() {
        return awaitPromise(procPromise.then(proc => {
          return proc.wait().then(({exitCode}) => exitCode);
        }));
      },

      kill(hard = false) {
        procPromise.then(proc => {
          proc.kill(hard ? 0 : undefined);
        });
      },
    };

    return result;
  },
};

module.exports = subprocess;