github.com/grumpyhome/grumpy@v0.3.1-0.20201208125205-7b775405bdf1/grumpy-tools-src/grumpy_tools/genmake.py (about)

     1  #!/usr/bin/env python
     2  
     3  # Copyright 2016 Google Inc. All Rights Reserved.
     4  #
     5  # Licensed under the Apache License, Version 2.0 (the "License");
     6  # you may not use this file except in compliance with the License.
     7  # You may obtain a copy of the License at
     8  #
     9  #     http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  
    17  """Generate a Makefile for Python targets in a GOPATH directory."""
    18  
    19  from __future__ import print_function
    20  
    21  import argparse
    22  import os
    23  import subprocess
    24  import sys
    25  
    26  
    27  parser = argparse.ArgumentParser()
    28  parser.add_argument('dir', help='GOPATH dir to scan for Python modules')
    29  parser.add_argument('-all_target', default='all',
    30                      help='make target that will build all modules')
    31  
    32  
    33  def _PrintRule(target, prereqs, rules):
    34    print('{}: {}'.format(target, ' '.join(prereqs)))
    35    if rules:
    36      print('\t@mkdir -p $(@D)')
    37      for rule in rules:
    38        print('\t@{}'.format(rule))
    39    print()
    40  
    41  
    42  def main(args):
    43    try:
    44      proc = subprocess.Popen('go env GOOS GOARCH', shell=True,
    45                              stdout=subprocess.PIPE)
    46    except OSError as e:
    47      print(str(e), file=sys.stderr)
    48      return 1
    49    out, _ = proc.communicate()
    50    if proc.returncode:
    51      print('go exited with status: {}'.format(proc.returncode), file=sys.stderr)
    52      return 1
    53    goos, goarch = out.split()
    54  
    55    if args.all_target:
    56      print('{}:\n'.format(args.all_target))
    57  
    58    gopath = os.path.normpath(args.dir)
    59    pkg_dir = os.path.join(gopath, 'pkg', '{}_{}'.format(goos, goarch))
    60    pydir = os.path.join(gopath, 'src', '__python__')
    61    for dirpath, _, filenames in os.walk(pydir):
    62      for filename in filenames:
    63        if not filename.endswith('.py'):
    64          continue
    65        basename = os.path.relpath(dirpath, pydir)
    66        if filename != '__init__.py':
    67          basename = os.path.normpath(
    68              os.path.join(basename, filename[:-3]))
    69        modname = basename.replace(os.sep, '.')
    70        ar_name = os.path.join(pkg_dir, '__python__', basename + '.a')
    71        go_file = os.path.join(pydir, basename, 'module.go')
    72        _PrintRule(go_file,
    73                   [os.path.join(dirpath, filename)],
    74                   ['grumpc -modname={} $< > $@'.format(modname)])
    75        recipe = (r"""pydeps -modname=%s $< | awk '{gsub(/\./, "/", $$0); """
    76                  r"""print "%s: %s/__python__/" $$0 ".a"}' > $@""")
    77        dep_file = os.path.join(pydir, basename, 'module.d')
    78        _PrintRule(dep_file, [os.path.join(dirpath, filename)],
    79                   [recipe % (modname, ar_name, pkg_dir)])
    80        go_package = '__python__/' + basename.replace(os.sep, '/')
    81        recipe = 'go tool compile -o $@ -p {} -complete -I {} -pack $<'
    82        _PrintRule(ar_name, [go_file], [recipe.format(go_package, pkg_dir)])
    83        if args.all_target:
    84          _PrintRule(args.all_target, [ar_name], [])
    85        print('-include {}\n'.format(dep_file))
    86  
    87  
    88  if __name__ == '__main__':
    89    sys.exit(main(parser.parse_args()))