|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +# Copyright 2013 The Flutter Authors. All rights reserved. |
| 4 | +# Use of this source code is governed by a BSD-style license that can be |
| 5 | +# found in the LICENSE file. |
| 6 | + |
| 7 | +"""Generates a shell or batch script to run a command.""" |
| 8 | + |
| 9 | +import argparse |
| 10 | +import os |
| 11 | +import string |
| 12 | + |
| 13 | + |
| 14 | +def main(): |
| 15 | + parser = argparse.ArgumentParser(description=__doc__) |
| 16 | + parser.add_argument('--output', required=True, help='Output file') |
| 17 | + parser.add_argument('--command', required=True, help='Command to run') |
| 18 | + parser.add_argument('--cwd', required=False, help='Working directory') |
| 19 | + parser.add_argument('rest', nargs='*', help='Arguments to pass to the command') |
| 20 | + |
| 21 | + # Rest of the arguments are passed to the command. |
| 22 | + args = parser.parse_args() |
| 23 | + |
| 24 | + out_path = os.path.dirname(args.output) |
| 25 | + if not os.path.exists(out_path): |
| 26 | + os.makedirs(out_path) |
| 27 | + |
| 28 | + script = string.Template( |
| 29 | + '''#!/bin/sh |
| 30 | +
|
| 31 | +set -e |
| 32 | +
|
| 33 | +# Set a trap to restore the working directory. |
| 34 | +trap "popd > /dev/null" EXIT |
| 35 | +pushd "$cwd" > /dev/null |
| 36 | +
|
| 37 | +$command $args |
| 38 | +''' |
| 39 | + ) |
| 40 | + |
| 41 | + params = { |
| 42 | + 'command': args.command, |
| 43 | + 'args': ' '.join(args.rest), |
| 44 | + 'cwd': args.cwd if args.cwd else '', |
| 45 | + } |
| 46 | + |
| 47 | + with open(args.output, 'w') as f: |
| 48 | + f.write(script.substitute(params)) |
| 49 | + |
| 50 | + # Make the script executable. |
| 51 | + os.chmod(args.output, 0o755) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == '__main__': |
| 55 | + main() |
0 commit comments