// Copyright 2016 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.windows; import java.io.PrintStream; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; /** * Mock subprocess to be used for testing Windows process management. Command line usage: * * * *

Registers are single characters. Each command line argument is interpreted as a single * operation. Example: * * * Ia10 Oa Oa Ea E-OVER X42 * * * Means: read 10 bytes from stdin, write them back twice to stdout and once to stderr, write * the string "OVER" to stderr then exit with exit code 42. */ public class MockSubprocess { private static Map registers = new HashMap<>(); private static void writeBytes(PrintStream stream, String arg) throws Exception { byte[] buf; switch (arg.charAt(1)) { case '-': // Immediate string buf = arg.substring(2).getBytes(Charset.forName("UTF-8")); break; case '$': // Environment variable buf = System.getenv(arg.substring(2)).getBytes(Charset.forName("UTF-8")); break; default: buf = registers.get(arg.charAt(1)); break; } stream.write(buf, 0, buf.length); } public static void main(String[] args) throws Exception { for (String arg : args) { switch (arg.charAt(0)) { case 'I': char register = arg.charAt(1); int length = Integer.parseInt(arg.substring(2)); byte[] buf = new byte[length]; registers.put(register, buf); System.in.read(buf, 0, length); break; case 'E': writeBytes(System.err, arg); break; case 'O': writeBytes(System.out, arg); break; case 'X': System.exit(Integer.parseInt(arg.substring(1))); } } } }