minit.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # Copyright 2017 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. """Code that creates simple startup projects."""
  12. from pathlib import Path
  13. from enum import Enum
  14. import subprocess
  15. import shutil
  16. import sys
  17. import os
  18. import re
  19. from glob import glob
  20. from mesonbuild import mesonlib
  21. from mesonbuild.environment import detect_ninja
  22. from mesonbuild.templates.samplefactory import sameple_generator
  23. '''
  24. we currently have one meson template at this time.
  25. '''
  26. from mesonbuild.templates.mesontemplates import create_meson_build
  27. FORTRAN_SUFFIXES = {'.f', '.for', '.F', '.f90', '.F90'}
  28. LANG_SUFFIXES = {'.c', '.cc', '.cpp', '.cs', '.cu', '.d', '.m', '.mm', '.rs', '.java'} | FORTRAN_SUFFIXES
  29. LANG_SUPPORTED = {'c', 'cpp', 'cs', 'cuda', 'd', 'fortran', 'java', 'rust', 'objc', 'objcpp'}
  30. DEFAULT_PROJECT = 'executable'
  31. DEFAULT_VERSION = '0.1'
  32. class DEFAULT_TYPES(Enum):
  33. EXE = 'executable'
  34. LIB = 'library'
  35. INFO_MESSAGE = '''Sample project created. To build it run the
  36. following commands:
  37. meson builddir
  38. ninja -C builddir
  39. '''
  40. def create_sample(options) -> None:
  41. '''
  42. Based on what arguments are passed we check for a match in language
  43. then check for project type and create new Meson samples project.
  44. '''
  45. sample_gen = sameple_generator(options)
  46. if options.type == DEFAULT_TYPES['EXE'].value:
  47. sample_gen.create_executable()
  48. elif options.type == DEFAULT_TYPES['LIB'].value:
  49. sample_gen.create_library()
  50. else:
  51. raise RuntimeError('Unreachable code')
  52. print(INFO_MESSAGE)
  53. def autodetect_options(options, sample: bool = False) -> None:
  54. '''
  55. Here we autodetect options for args not passed in so don't have to
  56. think about it.
  57. '''
  58. if not options.name:
  59. options.name = Path().resolve().stem
  60. if not re.match('[a-zA-Z_][a-zA-Z0-9]*', options.name) and sample:
  61. raise SystemExit('Name of current directory "{}" is not usable as a sample project name.\n'
  62. 'Specify a project name with --name.'.format(options.name))
  63. print('Using "{}" (name of current directory) as project name.'
  64. .format(options.name))
  65. if not options.executable:
  66. options.executable = options.name
  67. print('Using "{}" (project name) as name of executable to build.'
  68. .format(options.executable))
  69. if sample:
  70. # The rest of the autodetection is not applicable to generating sample projects.
  71. return
  72. if not options.srcfiles:
  73. srcfiles = []
  74. for f in (f for f in Path().iterdir() if f.is_file()):
  75. if f.suffix in LANG_SUFFIXES:
  76. srcfiles.append(f)
  77. if not srcfiles:
  78. raise SystemExit('No recognizable source files found.\n'
  79. 'Run meson init in an empty directory to create a sample project.')
  80. options.srcfiles = srcfiles
  81. print("Detected source files: " + ' '.join(map(str, srcfiles)))
  82. options.srcfiles = [Path(f) for f in options.srcfiles]
  83. if not options.language:
  84. for f in options.srcfiles:
  85. if f.suffix == '.c':
  86. options.language = 'c'
  87. break
  88. if f.suffix in ('.cc', '.cpp'):
  89. options.language = 'cpp'
  90. break
  91. if f.suffix in '.cs':
  92. options.language = 'cs'
  93. break
  94. if f.suffix == '.cu':
  95. options.language = 'cuda'
  96. break
  97. if f.suffix == '.d':
  98. options.language = 'd'
  99. break
  100. if f.suffix in FORTRAN_SUFFIXES:
  101. options.language = 'fortran'
  102. break
  103. if f.suffix == '.rs':
  104. options.language = 'rust'
  105. break
  106. if f.suffix == '.m':
  107. options.language = 'objc'
  108. break
  109. if f.suffix == '.mm':
  110. options.language = 'objcpp'
  111. break
  112. if f.suffix == '.java':
  113. options.language = 'java'
  114. break
  115. if not options.language:
  116. raise SystemExit("Can't autodetect language, please specify it with -l.")
  117. print("Detected language: " + options.language)
  118. def add_arguments(parser):
  119. '''
  120. Here we add args for that the user can passed when making a new
  121. Meson project.
  122. '''
  123. parser.add_argument("srcfiles", metavar="sourcefile", nargs="*", help="source files. default: all recognized files in current directory")
  124. parser.add_argument('-C', default='.', dest='wd', help='directory to cd into before running')
  125. parser.add_argument("-n", "--name", help="project name. default: name of current directory")
  126. parser.add_argument("-e", "--executable", help="executable name. default: project name")
  127. parser.add_argument("-d", "--deps", help="dependencies, comma-separated")
  128. parser.add_argument("-l", "--language", choices=LANG_SUPPORTED, help="project language. default: autodetected based on source files")
  129. parser.add_argument("-b", "--build", action='store_true', help="build after generation")
  130. parser.add_argument("--builddir", default='build', help="directory for build")
  131. parser.add_argument("-f", "--force", action="store_true", help="force overwrite of existing files and directories.")
  132. parser.add_argument('--type', default=DEFAULT_PROJECT, choices=('executable', 'library'), help="project type. default: {} based project".format(DEFAULT_PROJECT))
  133. parser.add_argument('--version', default=DEFAULT_VERSION, help="project version. default: {}".format(DEFAULT_VERSION))
  134. def run(options) -> int:
  135. '''
  136. Here we generate the new Meson sample project.
  137. '''
  138. if not Path(options.wd).exists():
  139. sys.exit('Project source root directory not found. Run this command in source directory root.')
  140. os.chdir(options.wd)
  141. if not glob('*'):
  142. autodetect_options(options, sample=True)
  143. if not options.language:
  144. print('Defaulting to generating a C language project.')
  145. options.language = 'c'
  146. create_sample(options)
  147. else:
  148. autodetect_options(options)
  149. if Path('meson.build').is_file() and not options.force:
  150. raise SystemExit('meson.build already exists. Use --force to overwrite.')
  151. create_meson_build(options)
  152. if options.build:
  153. if Path(options.builddir).is_dir() and options.force:
  154. print('Build directory already exists, deleting it.')
  155. shutil.rmtree(options.builddir)
  156. print('Building...')
  157. cmd = mesonlib.meson_command + [options.builddir]
  158. ret = subprocess.run(cmd)
  159. if ret.returncode:
  160. raise SystemExit
  161. cmd = [detect_ninja(), '-C', options.builddir]
  162. ret = subprocess.run(cmd)
  163. if ret.returncode:
  164. raise SystemExit
  165. return 0