Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
extract_template
(image_path: pathlib.Path, bbox: List)
Extract bounding box selection from image path. bbox: (top_row, left_col, bottom_row, right_col)
Extract bounding box selection from image path.
def extract_template(image_path: pathlib.Path, bbox: List) -> Image: """Extract bounding box selection from image path. bbox: (top_row, left_col, bottom_row, right_col) """ assert len(bbox) == 4 # Open image with PIL image = Image.open(image_path) # image.crop takes format (left, upper, right, lower) template = image.crop(swap_bbox_format(bbox)) return template
[ "def", "extract_template", "(", "image_path", ":", "pathlib", ".", "Path", ",", "bbox", ":", "List", ")", "->", "Image", ":", "assert", "len", "(", "bbox", ")", "==", "4", "# Open image with PIL", "image", "=", "Image", ".", "open", "(", "image_path", ")", "# image.crop takes format (left, upper, right, lower)", "template", "=", "image", ".", "crop", "(", "swap_bbox_format", "(", "bbox", ")", ")", "return", "template" ]
[ 54, 0 ]
[ 67, 19 ]
python
en
['en', 'en', 'en']
True
swap_bbox_format
(bbox_tuple)
Swap between (row0, col0, row1, col1) and (x0, y0, x1, y1) formats.
Swap between (row0, col0, row1, col1) and (x0, y0, x1, y1) formats.
def swap_bbox_format(bbox_tuple): """Swap between (row0, col0, row1, col1) and (x0, y0, x1, y1) formats.""" assert len(bbox_tuple) == 4 return (bbox_tuple[1], bbox_tuple[0], bbox_tuple[3], bbox_tuple[2])
[ "def", "swap_bbox_format", "(", "bbox_tuple", ")", ":", "assert", "len", "(", "bbox_tuple", ")", "==", "4", "return", "(", "bbox_tuple", "[", "1", "]", ",", "bbox_tuple", "[", "0", "]", ",", "bbox_tuple", "[", "3", "]", ",", "bbox_tuple", "[", "2", "]", ")" ]
[ 70, 0 ]
[ 73, 71 ]
python
en
['en', 'es', 'en']
True
QuoteShellArgument
(arg, flavor)
Quote a string such that it will be interpreted as a single argument by the shell.
Quote a string such that it will be interpreted as a single argument by the shell.
def QuoteShellArgument(arg, flavor): """Quote a string such that it will be interpreted as a single argument by the shell.""" # Rather than attempting to enumerate the bad shell characters, just # whitelist common OK ones and quote anything else. if re.match(r'^[a-zA-Z0-9_=.\\/-]+$', arg): return arg # No quoting necessary. if flavor == 'win': return gyp.msvs_emulation.QuoteForRspFile(arg) return "'" + arg.replace("'", "'" + '"\'"' + "'") + "'"
[ "def", "QuoteShellArgument", "(", "arg", ",", "flavor", ")", ":", "# Rather than attempting to enumerate the bad shell characters, just", "# whitelist common OK ones and quote anything else.", "if", "re", ".", "match", "(", "r'^[a-zA-Z0-9_=.\\\\/-]+$'", ",", "arg", ")", ":", "return", "arg", "# No quoting necessary.", "if", "flavor", "==", "'win'", ":", "return", "gyp", ".", "msvs_emulation", ".", "QuoteForRspFile", "(", "arg", ")", "return", "\"'\"", "+", "arg", ".", "replace", "(", "\"'\"", ",", "\"'\"", "+", "'\"\\'\"'", "+", "\"'\"", ")", "+", "\"'\"" ]
[ 72, 0 ]
[ 81, 58 ]
python
en
['en', 'en', 'en']
True
Define
(d, flavor)
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.
def Define(d, flavor): """Takes a preprocessor define and returns a -D parameter that's ninja- and shell-escaped.""" if flavor == 'win': # cl.exe replaces literal # characters with = in preprocesor definitions for # some reason. Octal-encode to work around that. d = d.replace('#', '\\%03o' % ord('#')) return QuoteShellArgument(ninja_syntax.escape('-D' + d), flavor)
[ "def", "Define", "(", "d", ",", "flavor", ")", ":", "if", "flavor", "==", "'win'", ":", "# cl.exe replaces literal # characters with = in preprocesor definitions for", "# some reason. Octal-encode to work around that.", "d", "=", "d", ".", "replace", "(", "'#'", ",", "'\\\\%03o'", "%", "ord", "(", "'#'", ")", ")", "return", "QuoteShellArgument", "(", "ninja_syntax", ".", "escape", "(", "'-D'", "+", "d", ")", ",", "flavor", ")" ]
[ 84, 0 ]
[ 91, 66 ]
python
en
['en', 'en', 'en']
True
AddArch
(output, arch)
Adds an arch string to an output path.
Adds an arch string to an output path.
def AddArch(output, arch): """Adds an arch string to an output path.""" output, extension = os.path.splitext(output) return '%s.%s%s' % (output, arch, extension)
[ "def", "AddArch", "(", "output", ",", "arch", ")", ":", "output", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "output", ")", "return", "'%s.%s%s'", "%", "(", "output", ",", "arch", ",", "extension", ")" ]
[ 94, 0 ]
[ 97, 46 ]
python
en
['en', 'en', 'en']
True
CalculateVariables
(default_variables, params)
Calculate additional variables for use in the build (called by gyp).
Calculate additional variables for use in the build (called by gyp).
def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" global generator_additional_non_configuration_keys global generator_additional_path_sections flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Ninja generator. import gyp.generator.xcode as xcode_generator generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) elif flavor == 'win': exts = gyp.MSVSUtil.TARGET_TYPE_EXT default_variables.setdefault('OS', 'win') default_variables['EXECUTABLE_SUFFIX'] = '.' + exts['executable'] default_variables['STATIC_LIB_PREFIX'] = '' default_variables['STATIC_LIB_SUFFIX'] = '.' + exts['static_library'] default_variables['SHARED_LIB_PREFIX'] = '' default_variables['SHARED_LIB_SUFFIX'] = '.' + exts['shared_library'] # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR', os.path.join('$!PRODUCT_DIR', 'lib')) default_variables.setdefault('LIB_DIR', os.path.join('$!PRODUCT_DIR', 'obj'))
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "global", "generator_additional_non_configuration_keys", "global", "generator_additional_path_sections", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'mac'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'mac'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.dylib'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "# Copy additional generator configuration data from Xcode, which is shared", "# by the Mac Ninja generator.", "import", "gyp", ".", "generator", ".", "xcode", "as", "xcode_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "global", "generator_extra_sources_for_rules", "generator_extra_sources_for_rules", "=", "getattr", "(", "xcode_generator", ",", "'generator_extra_sources_for_rules'", ",", "[", "]", ")", "elif", "flavor", "==", "'win'", ":", "exts", "=", "gyp", ".", "MSVSUtil", ".", "TARGET_TYPE_EXT", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'win'", ")", "default_variables", "[", "'EXECUTABLE_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'executable'", "]", "default_variables", "[", "'STATIC_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'STATIC_LIB_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'static_library'", "]", "default_variables", "[", "'SHARED_LIB_PREFIX'", "]", "=", "''", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", "=", "'.'", "+", "exts", "[", "'shared_library'", "]", "# Copy additional generator configuration data from VS, which is shared", "# by the Windows Ninja generator.", "import", "gyp", ".", "generator", ".", "msvs", "as", "msvs_generator", "generator_additional_non_configuration_keys", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "generator_additional_path_sections", "=", "getattr", "(", "msvs_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "gyp", ".", "msvs_emulation", ".", "CalculateCommonVariables", "(", "default_variables", ",", "params", ")", "else", ":", "operating_system", "=", "flavor", "if", "flavor", "==", "'android'", ":", "operating_system", "=", "'linux'", "# Keep this legacy behavior for now.", "default_variables", ".", "setdefault", "(", "'OS'", ",", "operating_system", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.so'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'lib'", ")", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "os", ".", "path", ".", "join", "(", "'$!PRODUCT_DIR'", ",", "'obj'", ")", ")" ]
[ 1593, 0 ]
[ 1643, 70 ]
python
en
['en', 'en', 'en']
True
ComputeOutputDir
(params)
Returns the path from the toplevel_dir to the build output directory.
Returns the path from the toplevel_dir to the build output directory.
def ComputeOutputDir(params): """Returns the path from the toplevel_dir to the build output directory.""" # generator_dir: relative path from pwd to where make puts build files. # Makes migrating from make to ninja easier, ninja doesn't put anything here. generator_dir = os.path.relpath(params['options'].generator_output or '.') # output_dir: relative path from generator_dir to the build directory. output_dir = params.get('generator_flags', {}).get('output_dir', 'out') # Relative path from source root to our output files. e.g. "out" return os.path.normpath(os.path.join(generator_dir, output_dir))
[ "def", "ComputeOutputDir", "(", "params", ")", ":", "# generator_dir: relative path from pwd to where make puts build files.", "# Makes migrating from make to ninja easier, ninja doesn't put anything here.", "generator_dir", "=", "os", ".", "path", ".", "relpath", "(", "params", "[", "'options'", "]", ".", "generator_output", "or", "'.'", ")", "# output_dir: relative path from generator_dir to the build directory.", "output_dir", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", ".", "get", "(", "'output_dir'", ",", "'out'", ")", "# Relative path from source root to our output files. e.g. \"out\"", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "generator_dir", ",", "output_dir", ")", ")" ]
[ 1645, 0 ]
[ 1655, 66 ]
python
en
['en', 'en', 'en']
True
CalculateGeneratorInputInfo
(params)
Called by __init__ to initialize generator values based on params.
Called by __init__ to initialize generator values based on params.
def CalculateGeneratorInputInfo(params): """Called by __init__ to initialize generator values based on params.""" # E.g. "out/gypfiles" toplevel = params['options'].toplevel_dir qualified_out_dir = os.path.normpath(os.path.join( toplevel, ComputeOutputDir(params), 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "# E.g. \"out/gypfiles\"", "toplevel", "=", "params", "[", "'options'", "]", ".", "toplevel_dir", "qualified_out_dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "toplevel", ",", "ComputeOutputDir", "(", "params", ")", ",", "'gypfiles'", ")", ")", "global", "generator_filelist_paths", "generator_filelist_paths", "=", "{", "'toplevel'", ":", "toplevel", ",", "'qualified_out_dir'", ":", "qualified_out_dir", ",", "}" ]
[ 1658, 0 ]
[ 1669, 3 ]
python
en
['en', 'en', 'en']
True
OpenOutput
(path, mode='w')
Open |path| for writing, creating directories if necessary.
Open |path| for writing, creating directories if necessary.
def OpenOutput(path, mode='w'): """Open |path| for writing, creating directories if necessary.""" gyp.common.EnsureDirExists(path) return open(path, mode)
[ "def", "OpenOutput", "(", "path", ",", "mode", "=", "'w'", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "path", ")", "return", "open", "(", "path", ",", "mode", ")" ]
[ 1672, 0 ]
[ 1675, 25 ]
python
en
['id', 'en', 'en']
True
GetDefaultConcurrentLinks
()
Returns a best-guess for a number of concurrent links.
Returns a best-guess for a number of concurrent links.
def GetDefaultConcurrentLinks(): """Returns a best-guess for a number of concurrent links.""" pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0)) if pool_size: return pool_size if sys.platform in ('win32', 'cygwin'): import ctypes class MEMORYSTATUSEX(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("sullAvailExtendedVirtual", ctypes.c_ulonglong), ] stat = MEMORYSTATUSEX() stat.dwLength = ctypes.sizeof(stat) ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)) # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM # on a 64 GB machine. mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32))) return min(mem_limit, hard_cap) elif sys.platform.startswith('linux'): if os.path.exists("/proc/meminfo"): with open("/proc/meminfo") as meminfo: memtotal_re = re.compile(r'^MemTotal:\s*(\d*)\s*kB') for line in meminfo: match = memtotal_re.match(line) if not match: continue # Allow 8Gb per link on Linux because Gold is quite memory hungry return max(1, int(match.group(1)) / (8 * (2 ** 20))) return 1 elif sys.platform == 'darwin': try: avail_bytes = int(subprocess.check_output(['sysctl', '-n', 'hw.memsize'])) # A static library debug build of Chromium's unit_tests takes ~2.7GB, so # 4GB per ld process allows for some more bloat. return max(1, avail_bytes / (4 * (2 ** 30))) # total / 4GB except: return 1 else: # TODO(scottmg): Implement this for other platforms. return 1
[ "def", "GetDefaultConcurrentLinks", "(", ")", ":", "pool_size", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "'GYP_LINK_CONCURRENCY'", ",", "0", ")", ")", "if", "pool_size", ":", "return", "pool_size", "if", "sys", ".", "platform", "in", "(", "'win32'", ",", "'cygwin'", ")", ":", "import", "ctypes", "class", "MEMORYSTATUSEX", "(", "ctypes", ".", "Structure", ")", ":", "_fields_", "=", "[", "(", "\"dwLength\"", ",", "ctypes", ".", "c_ulong", ")", ",", "(", "\"dwMemoryLoad\"", ",", "ctypes", ".", "c_ulong", ")", ",", "(", "\"ullTotalPhys\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"ullAvailPhys\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"ullTotalPageFile\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"ullAvailPageFile\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"ullTotalVirtual\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"ullAvailVirtual\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "(", "\"sullAvailExtendedVirtual\"", ",", "ctypes", ".", "c_ulonglong", ")", ",", "]", "stat", "=", "MEMORYSTATUSEX", "(", ")", "stat", ".", "dwLength", "=", "ctypes", ".", "sizeof", "(", "stat", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "GlobalMemoryStatusEx", "(", "ctypes", ".", "byref", "(", "stat", ")", ")", "# VS 2015 uses 20% more working set than VS 2013 and can consume all RAM", "# on a 64 GB machine.", "mem_limit", "=", "max", "(", "1", ",", "stat", ".", "ullTotalPhys", "/", "(", "5", "*", "(", "2", "**", "30", ")", ")", ")", "# total / 5GB", "hard_cap", "=", "max", "(", "1", ",", "int", "(", "os", ".", "environ", ".", "get", "(", "'GYP_LINK_CONCURRENCY_MAX'", ",", "2", "**", "32", ")", ")", ")", "return", "min", "(", "mem_limit", ",", "hard_cap", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "\"/proc/meminfo\"", ")", ":", "with", "open", "(", "\"/proc/meminfo\"", ")", "as", "meminfo", ":", "memtotal_re", "=", "re", ".", "compile", "(", "r'^MemTotal:\\s*(\\d*)\\s*kB'", ")", "for", "line", "in", "meminfo", ":", "match", "=", "memtotal_re", ".", "match", "(", "line", ")", "if", "not", "match", ":", "continue", "# Allow 8Gb per link on Linux because Gold is quite memory hungry", "return", "max", "(", "1", ",", "int", "(", "match", ".", "group", "(", "1", ")", ")", "/", "(", "8", "*", "(", "2", "**", "20", ")", ")", ")", "return", "1", "elif", "sys", ".", "platform", "==", "'darwin'", ":", "try", ":", "avail_bytes", "=", "int", "(", "subprocess", ".", "check_output", "(", "[", "'sysctl'", ",", "'-n'", ",", "'hw.memsize'", "]", ")", ")", "# A static library debug build of Chromium's unit_tests takes ~2.7GB, so", "# 4GB per ld process allows for some more bloat.", "return", "max", "(", "1", ",", "avail_bytes", "/", "(", "4", "*", "(", "2", "**", "30", ")", ")", ")", "# total / 4GB", "except", ":", "return", "1", "else", ":", "# TODO(scottmg): Implement this for other platforms.", "return", "1" ]
[ 1685, 0 ]
[ 1737, 12 ]
python
en
['en', 'en', 'en']
True
_GetWinLinkRuleNameSuffix
(embed_manifest)
Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.
Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.
def _GetWinLinkRuleNameSuffix(embed_manifest): """Returns the suffix used to select an appropriate linking rule depending on whether the manifest embedding is enabled.""" return '_embed' if embed_manifest else ''
[ "def", "_GetWinLinkRuleNameSuffix", "(", "embed_manifest", ")", ":", "return", "'_embed'", "if", "embed_manifest", "else", "''" ]
[ 1740, 0 ]
[ 1743, 43 ]
python
en
['en', 'en', 'en']
True
_AddWinLinkRules
(master_ninja, embed_manifest)
Adds link rules for Windows platform to |master_ninja|.
Adds link rules for Windows platform to |master_ninja|.
def _AddWinLinkRules(master_ninja, embed_manifest): """Adds link rules for Windows platform to |master_ninja|.""" def FullLinkCommand(ldcmd, out, binary_type): resource_name = { 'exe': '1', 'dll': '2', }[binary_type] return '%(python)s gyp-win-tool link-with-manifests $arch %(embed)s ' \ '%(out)s "%(ldcmd)s" %(resname)s $mt $rc "$intermediatemanifest" ' \ '$manifests' % { 'python': sys.executable, 'out': out, 'ldcmd': ldcmd, 'resname': resource_name, 'embed': embed_manifest } rule_name_suffix = _GetWinLinkRuleNameSuffix(embed_manifest) use_separate_mspdbsrv = ( int(os.environ.get('GYP_USE_SEPARATE_MSPDBSRV', '0')) != 0) dlldesc = 'LINK%s(DLL) $binary' % rule_name_suffix.upper() dllcmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo $implibflag /DLL /OUT:$binary ' '@$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) dllcmd = FullLinkCommand(dllcmd, '$binary', 'dll') master_ninja.rule('solink' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') master_ninja.rule('solink_module' + rule_name_suffix, description=dlldesc, command=dllcmd, rspfile='$binary.rsp', rspfile_content='$libs $in_newline $ldflags', restat=True, pool='link_pool') # Note that ldflags goes at the end so that it has the option of # overriding default settings earlier in the command line. exe_cmd = ('%s gyp-win-tool link-wrapper $arch %s ' '$ld /nologo /OUT:$binary @$binary.rsp' % (sys.executable, use_separate_mspdbsrv)) exe_cmd = FullLinkCommand(exe_cmd, '$binary', 'exe') master_ninja.rule('link' + rule_name_suffix, description='LINK%s $binary' % rule_name_suffix.upper(), command=exe_cmd, rspfile='$binary.rsp', rspfile_content='$in_newline $libs $ldflags', pool='link_pool')
[ "def", "_AddWinLinkRules", "(", "master_ninja", ",", "embed_manifest", ")", ":", "def", "FullLinkCommand", "(", "ldcmd", ",", "out", ",", "binary_type", ")", ":", "resource_name", "=", "{", "'exe'", ":", "'1'", ",", "'dll'", ":", "'2'", ",", "}", "[", "binary_type", "]", "return", "'%(python)s gyp-win-tool link-with-manifests $arch %(embed)s '", "'%(out)s \"%(ldcmd)s\" %(resname)s $mt $rc \"$intermediatemanifest\" '", "'$manifests'", "%", "{", "'python'", ":", "sys", ".", "executable", ",", "'out'", ":", "out", ",", "'ldcmd'", ":", "ldcmd", ",", "'resname'", ":", "resource_name", ",", "'embed'", ":", "embed_manifest", "}", "rule_name_suffix", "=", "_GetWinLinkRuleNameSuffix", "(", "embed_manifest", ")", "use_separate_mspdbsrv", "=", "(", "int", "(", "os", ".", "environ", ".", "get", "(", "'GYP_USE_SEPARATE_MSPDBSRV'", ",", "'0'", ")", ")", "!=", "0", ")", "dlldesc", "=", "'LINK%s(DLL) $binary'", "%", "rule_name_suffix", ".", "upper", "(", ")", "dllcmd", "=", "(", "'%s gyp-win-tool link-wrapper $arch %s '", "'$ld /nologo $implibflag /DLL /OUT:$binary '", "'@$binary.rsp'", "%", "(", "sys", ".", "executable", ",", "use_separate_mspdbsrv", ")", ")", "dllcmd", "=", "FullLinkCommand", "(", "dllcmd", ",", "'$binary'", ",", "'dll'", ")", "master_ninja", ".", "rule", "(", "'solink'", "+", "rule_name_suffix", ",", "description", "=", "dlldesc", ",", "command", "=", "dllcmd", ",", "rspfile", "=", "'$binary.rsp'", ",", "rspfile_content", "=", "'$libs $in_newline $ldflags'", ",", "restat", "=", "True", ",", "pool", "=", "'link_pool'", ")", "master_ninja", ".", "rule", "(", "'solink_module'", "+", "rule_name_suffix", ",", "description", "=", "dlldesc", ",", "command", "=", "dllcmd", ",", "rspfile", "=", "'$binary.rsp'", ",", "rspfile_content", "=", "'$libs $in_newline $ldflags'", ",", "restat", "=", "True", ",", "pool", "=", "'link_pool'", ")", "# Note that ldflags goes at the end so that it has the option of", "# overriding default settings earlier in the command line.", "exe_cmd", "=", "(", "'%s gyp-win-tool link-wrapper $arch %s '", "'$ld /nologo /OUT:$binary @$binary.rsp'", "%", "(", "sys", ".", "executable", ",", "use_separate_mspdbsrv", ")", ")", "exe_cmd", "=", "FullLinkCommand", "(", "exe_cmd", ",", "'$binary'", ",", "'exe'", ")", "master_ninja", ".", "rule", "(", "'link'", "+", "rule_name_suffix", ",", "description", "=", "'LINK%s $binary'", "%", "rule_name_suffix", ".", "upper", "(", ")", ",", "command", "=", "exe_cmd", ",", "rspfile", "=", "'$binary.rsp'", ",", "rspfile_content", "=", "'$in_newline $libs $ldflags'", ",", "pool", "=", "'link_pool'", ")" ]
[ 1746, 0 ]
[ 1792, 37 ]
python
en
['en', 'da', 'en']
True
Target.Linkable
(self)
Return true if this is a target that can be linked against.
Return true if this is a target that can be linked against.
def Linkable(self): """Return true if this is a target that can be linked against.""" return self.type in ('static_library', 'shared_library')
[ "def", "Linkable", "(", "self", ")", ":", "return", "self", ".", "type", "in", "(", "'static_library'", ",", "'shared_library'", ")" ]
[ 151, 2 ]
[ 153, 60 ]
python
en
['en', 'en', 'en']
True
Target.UsesToc
(self, flavor)
Return true if the target should produce a restat rule based on a TOC file.
Return true if the target should produce a restat rule based on a TOC file.
def UsesToc(self, flavor): """Return true if the target should produce a restat rule based on a TOC file.""" # For bundles, the .TOC should be produced for the binary, not for # FinalOutput(). But the naive approach would put the TOC file into the # bundle, so don't do this for bundles for now. if flavor == 'win' or self.bundle: return False return self.type in ('shared_library', 'loadable_module')
[ "def", "UsesToc", "(", "self", ",", "flavor", ")", ":", "# For bundles, the .TOC should be produced for the binary, not for", "# FinalOutput(). But the naive approach would put the TOC file into the", "# bundle, so don't do this for bundles for now.", "if", "flavor", "==", "'win'", "or", "self", ".", "bundle", ":", "return", "False", "return", "self", ".", "type", "in", "(", "'shared_library'", ",", "'loadable_module'", ")" ]
[ 155, 2 ]
[ 163, 61 ]
python
en
['en', 'en', 'en']
True
Target.PreActionInput
(self, flavor)
Return the path, if any, that should be used as a dependency of any dependent action step.
Return the path, if any, that should be used as a dependency of any dependent action step.
def PreActionInput(self, flavor): """Return the path, if any, that should be used as a dependency of any dependent action step.""" if self.UsesToc(flavor): return self.FinalOutput() + '.TOC' return self.FinalOutput() or self.preaction_stamp
[ "def", "PreActionInput", "(", "self", ",", "flavor", ")", ":", "if", "self", ".", "UsesToc", "(", "flavor", ")", ":", "return", "self", ".", "FinalOutput", "(", ")", "+", "'.TOC'", "return", "self", ".", "FinalOutput", "(", ")", "or", "self", ".", "preaction_stamp" ]
[ 165, 2 ]
[ 170, 53 ]
python
en
['en', 'en', 'en']
True
Target.PreCompileInput
(self)
Return the path, if any, that should be used as a dependency of any dependent compile step.
Return the path, if any, that should be used as a dependency of any dependent compile step.
def PreCompileInput(self): """Return the path, if any, that should be used as a dependency of any dependent compile step.""" return self.actions_stamp or self.precompile_stamp
[ "def", "PreCompileInput", "(", "self", ")", ":", "return", "self", ".", "actions_stamp", "or", "self", ".", "precompile_stamp" ]
[ 172, 2 ]
[ 175, 54 ]
python
en
['en', 'en', 'en']
True
Target.FinalOutput
(self)
Return the last output of the target, which depends on all prior steps.
Return the last output of the target, which depends on all prior steps.
def FinalOutput(self): """Return the last output of the target, which depends on all prior steps.""" return self.bundle or self.binary or self.actions_stamp
[ "def", "FinalOutput", "(", "self", ")", ":", "return", "self", ".", "bundle", "or", "self", ".", "binary", "or", "self", ".", "actions_stamp" ]
[ 177, 2 ]
[ 180, 59 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.__init__
(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None)
base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory
base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory
def __init__(self, hash_for_rules, target_outputs, base_dir, build_dir, output_file, toplevel_build, output_file_name, flavor, toplevel_dir=None): """ base_dir: path from source root to directory containing this gyp file, by gyp semantics, all input paths are relative to this build_dir: path from source root to build output toplevel_dir: path to the toplevel directory """ self.hash_for_rules = hash_for_rules self.target_outputs = target_outputs self.base_dir = base_dir self.build_dir = build_dir self.ninja = ninja_syntax.Writer(output_file) self.toplevel_build = toplevel_build self.output_file_name = output_file_name self.flavor = flavor self.abs_build_dir = None if toplevel_dir is not None: self.abs_build_dir = os.path.abspath(os.path.join(toplevel_dir, build_dir)) self.obj_ext = '.obj' if flavor == 'win' else '.o' if flavor == 'win': # See docstring of msvs_emulation.GenerateEnvironmentFiles(). self.win_env = {} for arch in ('x86', 'x64'): self.win_env[arch] = 'environment.' + arch # Relative path from build output dir to base dir. build_to_top = gyp.common.InvertRelativePath(build_dir, toplevel_dir) self.build_to_base = os.path.join(build_to_top, base_dir) # Relative path from base dir to build dir. base_to_top = gyp.common.InvertRelativePath(base_dir, toplevel_dir) self.base_to_build = os.path.join(base_to_top, build_dir)
[ "def", "__init__", "(", "self", ",", "hash_for_rules", ",", "target_outputs", ",", "base_dir", ",", "build_dir", ",", "output_file", ",", "toplevel_build", ",", "output_file_name", ",", "flavor", ",", "toplevel_dir", "=", "None", ")", ":", "self", ".", "hash_for_rules", "=", "hash_for_rules", "self", ".", "target_outputs", "=", "target_outputs", "self", ".", "base_dir", "=", "base_dir", "self", ".", "build_dir", "=", "build_dir", "self", ".", "ninja", "=", "ninja_syntax", ".", "Writer", "(", "output_file", ")", "self", ".", "toplevel_build", "=", "toplevel_build", "self", ".", "output_file_name", "=", "output_file_name", "self", ".", "flavor", "=", "flavor", "self", ".", "abs_build_dir", "=", "None", "if", "toplevel_dir", "is", "not", "None", ":", "self", ".", "abs_build_dir", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "toplevel_dir", ",", "build_dir", ")", ")", "self", ".", "obj_ext", "=", "'.obj'", "if", "flavor", "==", "'win'", "else", "'.o'", "if", "flavor", "==", "'win'", ":", "# See docstring of msvs_emulation.GenerateEnvironmentFiles().", "self", ".", "win_env", "=", "{", "}", "for", "arch", "in", "(", "'x86'", ",", "'x64'", ")", ":", "self", ".", "win_env", "[", "arch", "]", "=", "'environment.'", "+", "arch", "# Relative path from build output dir to base dir.", "build_to_top", "=", "gyp", ".", "common", ".", "InvertRelativePath", "(", "build_dir", ",", "toplevel_dir", ")", "self", ".", "build_to_base", "=", "os", ".", "path", ".", "join", "(", "build_to_top", ",", "base_dir", ")", "# Relative path from base dir to build dir.", "base_to_top", "=", "gyp", ".", "common", ".", "InvertRelativePath", "(", "base_dir", ",", "toplevel_dir", ")", "self", ".", "base_to_build", "=", "os", ".", "path", ".", "join", "(", "base_to_top", ",", "build_dir", ")" ]
[ 208, 2 ]
[ 243, 61 ]
python
en
['en', 'error', 'th']
False
NinjaWriter.ExpandSpecial
(self, path, product_dir=None)
Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir.
Expand specials like $!PRODUCT_DIR in |path|.
def ExpandSpecial(self, path, product_dir=None): """Expand specials like $!PRODUCT_DIR in |path|. If |product_dir| is None, assumes the cwd is already the product dir. Otherwise, |product_dir| is the relative path to the product dir. """ PRODUCT_DIR = '$!PRODUCT_DIR' if PRODUCT_DIR in path: if product_dir: path = path.replace(PRODUCT_DIR, product_dir) else: path = path.replace(PRODUCT_DIR + '/', '') path = path.replace(PRODUCT_DIR + '\\', '') path = path.replace(PRODUCT_DIR, '.') INTERMEDIATE_DIR = '$!INTERMEDIATE_DIR' if INTERMEDIATE_DIR in path: int_dir = self.GypPathToUniqueOutput('gen') # GypPathToUniqueOutput generates a path relative to the product dir, # so insert product_dir in front if it is provided. path = path.replace(INTERMEDIATE_DIR, os.path.join(product_dir or '', int_dir)) CONFIGURATION_NAME = '$|CONFIGURATION_NAME' path = path.replace(CONFIGURATION_NAME, self.config_name) return path
[ "def", "ExpandSpecial", "(", "self", ",", "path", ",", "product_dir", "=", "None", ")", ":", "PRODUCT_DIR", "=", "'$!PRODUCT_DIR'", "if", "PRODUCT_DIR", "in", "path", ":", "if", "product_dir", ":", "path", "=", "path", ".", "replace", "(", "PRODUCT_DIR", ",", "product_dir", ")", "else", ":", "path", "=", "path", ".", "replace", "(", "PRODUCT_DIR", "+", "'/'", ",", "''", ")", "path", "=", "path", ".", "replace", "(", "PRODUCT_DIR", "+", "'\\\\'", ",", "''", ")", "path", "=", "path", ".", "replace", "(", "PRODUCT_DIR", ",", "'.'", ")", "INTERMEDIATE_DIR", "=", "'$!INTERMEDIATE_DIR'", "if", "INTERMEDIATE_DIR", "in", "path", ":", "int_dir", "=", "self", ".", "GypPathToUniqueOutput", "(", "'gen'", ")", "# GypPathToUniqueOutput generates a path relative to the product dir,", "# so insert product_dir in front if it is provided.", "path", "=", "path", ".", "replace", "(", "INTERMEDIATE_DIR", ",", "os", ".", "path", ".", "join", "(", "product_dir", "or", "''", ",", "int_dir", ")", ")", "CONFIGURATION_NAME", "=", "'$|CONFIGURATION_NAME'", "path", "=", "path", ".", "replace", "(", "CONFIGURATION_NAME", ",", "self", ".", "config_name", ")", "return", "path" ]
[ 245, 2 ]
[ 273, 15 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GypPathToNinja
(self, path, env=None)
Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.
Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|.
def GypPathToNinja(self, path, env=None): """Translate a gyp path to a ninja path, optionally expanding environment variable references in |path| with |env|. See the above discourse on path conversions.""" if env: if self.flavor == 'mac': path = gyp.xcode_emulation.ExpandEnvVars(path, env) elif self.flavor == 'win': path = gyp.msvs_emulation.ExpandMacros(path, env) if path.startswith('$!'): expanded = self.ExpandSpecial(path) if self.flavor == 'win': expanded = os.path.normpath(expanded) return expanded if '$|' in path: path = self.ExpandSpecial(path) assert '$' not in path, path return os.path.normpath(os.path.join(self.build_to_base, path))
[ "def", "GypPathToNinja", "(", "self", ",", "path", ",", "env", "=", "None", ")", ":", "if", "env", ":", "if", "self", ".", "flavor", "==", "'mac'", ":", "path", "=", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "path", ",", "env", ")", "elif", "self", ".", "flavor", "==", "'win'", ":", "path", "=", "gyp", ".", "msvs_emulation", ".", "ExpandMacros", "(", "path", ",", "env", ")", "if", "path", ".", "startswith", "(", "'$!'", ")", ":", "expanded", "=", "self", ".", "ExpandSpecial", "(", "path", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "expanded", "=", "os", ".", "path", ".", "normpath", "(", "expanded", ")", "return", "expanded", "if", "'$|'", "in", "path", ":", "path", "=", "self", ".", "ExpandSpecial", "(", "path", ")", "assert", "'$'", "not", "in", "path", ",", "path", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "build_to_base", ",", "path", ")", ")" ]
[ 287, 2 ]
[ 305, 67 ]
python
en
['en', 'haw', 'en']
True
NinjaWriter.GypPathToUniqueOutput
(self, path, qualified=True)
Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.
Translate a gyp path to a ninja path for writing output.
def GypPathToUniqueOutput(self, path, qualified=True): """Translate a gyp path to a ninja path for writing output. If qualified is True, qualify the resulting filename with the name of the target. This is necessary when e.g. compiling the same path twice for two separate output targets. See the above discourse on path conversions.""" path = self.ExpandSpecial(path) assert not path.startswith('$'), path # Translate the path following this scheme: # Input: foo/bar.gyp, target targ, references baz/out.o # Output: obj/foo/baz/targ.out.o (if qualified) # obj/foo/baz/out.o (otherwise) # (and obj.host instead of obj for cross-compiles) # # Why this scheme and not some other one? # 1) for a given input, you can compute all derived outputs by matching # its path, even if the input is brought via a gyp file with '..'. # 2) simple files like libraries and stamps have a simple filename. obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset path_dir, path_basename = os.path.split(path) assert not os.path.isabs(path_dir), ( "'%s' can not be absolute path (see crbug.com/462153)." % path_dir) if qualified: path_basename = self.name + '.' + path_basename return os.path.normpath(os.path.join(obj, self.base_dir, path_dir, path_basename))
[ "def", "GypPathToUniqueOutput", "(", "self", ",", "path", ",", "qualified", "=", "True", ")", ":", "path", "=", "self", ".", "ExpandSpecial", "(", "path", ")", "assert", "not", "path", ".", "startswith", "(", "'$'", ")", ",", "path", "# Translate the path following this scheme:", "# Input: foo/bar.gyp, target targ, references baz/out.o", "# Output: obj/foo/baz/targ.out.o (if qualified)", "# obj/foo/baz/out.o (otherwise)", "# (and obj.host instead of obj for cross-compiles)", "#", "# Why this scheme and not some other one?", "# 1) for a given input, you can compute all derived outputs by matching", "# its path, even if the input is brought via a gyp file with '..'.", "# 2) simple files like libraries and stamps have a simple filename.", "obj", "=", "'obj'", "if", "self", ".", "toolset", "!=", "'target'", ":", "obj", "+=", "'.'", "+", "self", ".", "toolset", "path_dir", ",", "path_basename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "assert", "not", "os", ".", "path", ".", "isabs", "(", "path_dir", ")", ",", "(", "\"'%s' can not be absolute path (see crbug.com/462153).\"", "%", "path_dir", ")", "if", "qualified", ":", "path_basename", "=", "self", ".", "name", "+", "'.'", "+", "path_basename", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "obj", ",", "self", ".", "base_dir", ",", "path_dir", ",", "path_basename", ")", ")" ]
[ 307, 2 ]
[ 341, 56 ]
python
en
['en', 'haw', 'en']
True
NinjaWriter.WriteCollapsedDependencies
(self, name, targets, order_only=None)
Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.
Given a list of targets, return a path for a single file representing the result of building all the targets or None.
def WriteCollapsedDependencies(self, name, targets, order_only=None): """Given a list of targets, return a path for a single file representing the result of building all the targets or None. Uses a stamp file if necessary.""" assert targets == filter(None, targets), targets if len(targets) == 0: assert not order_only return None if len(targets) > 1 or order_only: stamp = self.GypPathToUniqueOutput(name + '.stamp') targets = self.ninja.build(stamp, 'stamp', targets, order_only=order_only) self.ninja.newline() return targets[0]
[ "def", "WriteCollapsedDependencies", "(", "self", ",", "name", ",", "targets", ",", "order_only", "=", "None", ")", ":", "assert", "targets", "==", "filter", "(", "None", ",", "targets", ")", ",", "targets", "if", "len", "(", "targets", ")", "==", "0", ":", "assert", "not", "order_only", "return", "None", "if", "len", "(", "targets", ")", ">", "1", "or", "order_only", ":", "stamp", "=", "self", ".", "GypPathToUniqueOutput", "(", "name", "+", "'.stamp'", ")", "targets", "=", "self", ".", "ninja", ".", "build", "(", "stamp", ",", "'stamp'", ",", "targets", ",", "order_only", "=", "order_only", ")", "self", ".", "ninja", ".", "newline", "(", ")", "return", "targets", "[", "0", "]" ]
[ 343, 2 ]
[ 357, 21 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteSpec
(self, spec, config_name, generator_flags)
The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).
The main entry point for NinjaWriter: write the build rules for a spec.
def WriteSpec(self, spec, config_name, generator_flags): """The main entry point for NinjaWriter: write the build rules for a spec. Returns a Target object, which represents the output paths for this spec. Returns None if there are no outputs (e.g. a settings-only 'none' type target).""" self.config_name = config_name self.name = spec['target_name'] self.toolset = spec['toolset'] config = spec['configurations'][config_name] self.target = Target(spec['type']) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) # Track if this target contains any C++ files, to decide if gcc or g++ # should be used for linking. self.uses_cpp = False self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) self.xcode_settings = self.msvs_settings = None if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) if self.flavor == 'win': self.msvs_settings = gyp.msvs_emulation.MsvsSettings(spec, generator_flags) arch = self.msvs_settings.GetArch(config_name) self.ninja.variable('arch', self.win_env[arch]) self.ninja.variable('cc', '$cl_' + arch) self.ninja.variable('cxx', '$cl_' + arch) self.ninja.variable('cc_host', '$cl_' + arch) self.ninja.variable('cxx_host', '$cl_' + arch) self.ninja.variable('asm', '$ml_' + arch) if self.flavor == 'mac': self.archs = self.xcode_settings.GetActiveArchs(config_name) if len(self.archs) > 1: self.arch_subninjas = dict( (arch, ninja_syntax.Writer( OpenOutput(os.path.join(self.toplevel_build, self._SubninjaNameForArch(arch)), 'w'))) for arch in self.archs) # Compute predepends for all rules. # actions_depends is the dependencies this target depends on before running # any of its action/rule/copy steps. # compile_depends is the dependencies this target depends on before running # any of its compile steps. actions_depends = [] compile_depends = [] # TODO(evan): it is rather confusing which things are lists and which # are strings. Fix these. if 'dependencies' in spec: for dep in spec['dependencies']: if dep in self.target_outputs: target = self.target_outputs[dep] actions_depends.append(target.PreActionInput(self.flavor)) compile_depends.append(target.PreCompileInput()) actions_depends = filter(None, actions_depends) compile_depends = filter(None, compile_depends) actions_depends = self.WriteCollapsedDependencies('actions_depends', actions_depends) compile_depends = self.WriteCollapsedDependencies('compile_depends', compile_depends) self.target.preaction_stamp = actions_depends self.target.precompile_stamp = compile_depends # Write out actions, rules, and copies. These must happen before we # compile any sources, so compute a list of predependencies for sources # while we do it. extra_sources = [] mac_bundle_depends = [] self.target.actions_stamp = self.WriteActionsRulesCopies( spec, extra_sources, actions_depends, mac_bundle_depends) # If we have actions/rules/copies, we depend directly on those, but # otherwise we depend on dependent target's actions/rules/copies etc. # We never need to explicitly depend on previous target's link steps, # because no compile ever depends on them. compile_depends_stamp = (self.target.actions_stamp or compile_depends) # Write out the compilation steps, if any. link_deps = [] sources = extra_sources + spec.get('sources', []) if sources: if self.flavor == 'mac' and len(self.archs) > 1: # Write subninja file containing compile and link commands scoped to # a single arch if a fat binary is being built. for arch in self.archs: self.ninja.subninja(self._SubninjaNameForArch(arch)) pch = None if self.flavor == 'win': gyp.msvs_emulation.VerifyMissingSources( sources, self.abs_build_dir, generator_flags, self.GypPathToNinja) pch = gyp.msvs_emulation.PrecompiledHeader( self.msvs_settings, config_name, self.GypPathToNinja, self.GypPathToUniqueOutput, self.obj_ext) else: pch = gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, self.GypPathToNinja, lambda path, lang: self.GypPathToUniqueOutput(path + '-' + lang)) link_deps = self.WriteSources( self.ninja, config_name, config, sources, compile_depends_stamp, pch, spec) # Some actions/rules output 'sources' that are already object files. obj_outputs = [f for f in sources if f.endswith(self.obj_ext)] if obj_outputs: if self.flavor != 'mac' or len(self.archs) == 1: link_deps += [self.GypPathToNinja(o) for o in obj_outputs] else: print "Warning: Actions/rules writing object files don't work with " \ "multiarch targets, dropping. (target %s)" % spec['target_name'] elif self.flavor == 'mac' and len(self.archs) > 1: link_deps = collections.defaultdict(list) compile_deps = self.target.actions_stamp or actions_depends if self.flavor == 'win' and self.target.type == 'static_library': self.target.component_objs = link_deps self.target.compile_deps = compile_deps # Write out a link step, if needed. output = None is_empty_bundle = not link_deps and not mac_bundle_depends if link_deps or self.target.actions_stamp or actions_depends: output = self.WriteTarget(spec, config_name, config, link_deps, compile_deps) if self.is_mac_bundle: mac_bundle_depends.append(output) # Bundle all of the above together, if needed. if self.is_mac_bundle: output = self.WriteMacBundle(spec, mac_bundle_depends, is_empty_bundle) if not output: return None assert self.target.FinalOutput(), output return self.target
[ "def", "WriteSpec", "(", "self", ",", "spec", ",", "config_name", ",", "generator_flags", ")", ":", "self", ".", "config_name", "=", "config_name", "self", ".", "name", "=", "spec", "[", "'target_name'", "]", "self", ".", "toolset", "=", "spec", "[", "'toolset'", "]", "config", "=", "spec", "[", "'configurations'", "]", "[", "config_name", "]", "self", ".", "target", "=", "Target", "(", "spec", "[", "'type'", "]", ")", "self", ".", "is_standalone_static_library", "=", "bool", "(", "spec", ".", "get", "(", "'standalone_static_library'", ",", "0", ")", ")", "# Track if this target contains any C++ files, to decide if gcc or g++", "# should be used for linking.", "self", ".", "uses_cpp", "=", "False", "self", ".", "is_mac_bundle", "=", "gyp", ".", "xcode_emulation", ".", "IsMacBundle", "(", "self", ".", "flavor", ",", "spec", ")", "self", ".", "xcode_settings", "=", "self", ".", "msvs_settings", "=", "None", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "xcode_settings", "=", "gyp", ".", "xcode_emulation", ".", "XcodeSettings", "(", "spec", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "self", ".", "msvs_settings", "=", "gyp", ".", "msvs_emulation", ".", "MsvsSettings", "(", "spec", ",", "generator_flags", ")", "arch", "=", "self", ".", "msvs_settings", ".", "GetArch", "(", "config_name", ")", "self", ".", "ninja", ".", "variable", "(", "'arch'", ",", "self", ".", "win_env", "[", "arch", "]", ")", "self", ".", "ninja", ".", "variable", "(", "'cc'", ",", "'$cl_'", "+", "arch", ")", "self", ".", "ninja", ".", "variable", "(", "'cxx'", ",", "'$cl_'", "+", "arch", ")", "self", ".", "ninja", ".", "variable", "(", "'cc_host'", ",", "'$cl_'", "+", "arch", ")", "self", ".", "ninja", ".", "variable", "(", "'cxx_host'", ",", "'$cl_'", "+", "arch", ")", "self", ".", "ninja", ".", "variable", "(", "'asm'", ",", "'$ml_'", "+", "arch", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "archs", "=", "self", ".", "xcode_settings", ".", "GetActiveArchs", "(", "config_name", ")", "if", "len", "(", "self", ".", "archs", ")", ">", "1", ":", "self", ".", "arch_subninjas", "=", "dict", "(", "(", "arch", ",", "ninja_syntax", ".", "Writer", "(", "OpenOutput", "(", "os", ".", "path", ".", "join", "(", "self", ".", "toplevel_build", ",", "self", ".", "_SubninjaNameForArch", "(", "arch", ")", ")", ",", "'w'", ")", ")", ")", "for", "arch", "in", "self", ".", "archs", ")", "# Compute predepends for all rules.", "# actions_depends is the dependencies this target depends on before running", "# any of its action/rule/copy steps.", "# compile_depends is the dependencies this target depends on before running", "# any of its compile steps.", "actions_depends", "=", "[", "]", "compile_depends", "=", "[", "]", "# TODO(evan): it is rather confusing which things are lists and which", "# are strings. Fix these.", "if", "'dependencies'", "in", "spec", ":", "for", "dep", "in", "spec", "[", "'dependencies'", "]", ":", "if", "dep", "in", "self", ".", "target_outputs", ":", "target", "=", "self", ".", "target_outputs", "[", "dep", "]", "actions_depends", ".", "append", "(", "target", ".", "PreActionInput", "(", "self", ".", "flavor", ")", ")", "compile_depends", ".", "append", "(", "target", ".", "PreCompileInput", "(", ")", ")", "actions_depends", "=", "filter", "(", "None", ",", "actions_depends", ")", "compile_depends", "=", "filter", "(", "None", ",", "compile_depends", ")", "actions_depends", "=", "self", ".", "WriteCollapsedDependencies", "(", "'actions_depends'", ",", "actions_depends", ")", "compile_depends", "=", "self", ".", "WriteCollapsedDependencies", "(", "'compile_depends'", ",", "compile_depends", ")", "self", ".", "target", ".", "preaction_stamp", "=", "actions_depends", "self", ".", "target", ".", "precompile_stamp", "=", "compile_depends", "# Write out actions, rules, and copies. These must happen before we", "# compile any sources, so compute a list of predependencies for sources", "# while we do it.", "extra_sources", "=", "[", "]", "mac_bundle_depends", "=", "[", "]", "self", ".", "target", ".", "actions_stamp", "=", "self", ".", "WriteActionsRulesCopies", "(", "spec", ",", "extra_sources", ",", "actions_depends", ",", "mac_bundle_depends", ")", "# If we have actions/rules/copies, we depend directly on those, but", "# otherwise we depend on dependent target's actions/rules/copies etc.", "# We never need to explicitly depend on previous target's link steps,", "# because no compile ever depends on them.", "compile_depends_stamp", "=", "(", "self", ".", "target", ".", "actions_stamp", "or", "compile_depends", ")", "# Write out the compilation steps, if any.", "link_deps", "=", "[", "]", "sources", "=", "extra_sources", "+", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", "if", "sources", ":", "if", "self", ".", "flavor", "==", "'mac'", "and", "len", "(", "self", ".", "archs", ")", ">", "1", ":", "# Write subninja file containing compile and link commands scoped to", "# a single arch if a fat binary is being built.", "for", "arch", "in", "self", ".", "archs", ":", "self", ".", "ninja", ".", "subninja", "(", "self", ".", "_SubninjaNameForArch", "(", "arch", ")", ")", "pch", "=", "None", "if", "self", ".", "flavor", "==", "'win'", ":", "gyp", ".", "msvs_emulation", ".", "VerifyMissingSources", "(", "sources", ",", "self", ".", "abs_build_dir", ",", "generator_flags", ",", "self", ".", "GypPathToNinja", ")", "pch", "=", "gyp", ".", "msvs_emulation", ".", "PrecompiledHeader", "(", "self", ".", "msvs_settings", ",", "config_name", ",", "self", ".", "GypPathToNinja", ",", "self", ".", "GypPathToUniqueOutput", ",", "self", ".", "obj_ext", ")", "else", ":", "pch", "=", "gyp", ".", "xcode_emulation", ".", "MacPrefixHeader", "(", "self", ".", "xcode_settings", ",", "self", ".", "GypPathToNinja", ",", "lambda", "path", ",", "lang", ":", "self", ".", "GypPathToUniqueOutput", "(", "path", "+", "'-'", "+", "lang", ")", ")", "link_deps", "=", "self", ".", "WriteSources", "(", "self", ".", "ninja", ",", "config_name", ",", "config", ",", "sources", ",", "compile_depends_stamp", ",", "pch", ",", "spec", ")", "# Some actions/rules output 'sources' that are already object files.", "obj_outputs", "=", "[", "f", "for", "f", "in", "sources", "if", "f", ".", "endswith", "(", "self", ".", "obj_ext", ")", "]", "if", "obj_outputs", ":", "if", "self", ".", "flavor", "!=", "'mac'", "or", "len", "(", "self", ".", "archs", ")", "==", "1", ":", "link_deps", "+=", "[", "self", ".", "GypPathToNinja", "(", "o", ")", "for", "o", "in", "obj_outputs", "]", "else", ":", "print", "\"Warning: Actions/rules writing object files don't work with \"", "\"multiarch targets, dropping. (target %s)\"", "%", "spec", "[", "'target_name'", "]", "elif", "self", ".", "flavor", "==", "'mac'", "and", "len", "(", "self", ".", "archs", ")", ">", "1", ":", "link_deps", "=", "collections", ".", "defaultdict", "(", "list", ")", "compile_deps", "=", "self", ".", "target", ".", "actions_stamp", "or", "actions_depends", "if", "self", ".", "flavor", "==", "'win'", "and", "self", ".", "target", ".", "type", "==", "'static_library'", ":", "self", ".", "target", ".", "component_objs", "=", "link_deps", "self", ".", "target", ".", "compile_deps", "=", "compile_deps", "# Write out a link step, if needed.", "output", "=", "None", "is_empty_bundle", "=", "not", "link_deps", "and", "not", "mac_bundle_depends", "if", "link_deps", "or", "self", ".", "target", ".", "actions_stamp", "or", "actions_depends", ":", "output", "=", "self", ".", "WriteTarget", "(", "spec", ",", "config_name", ",", "config", ",", "link_deps", ",", "compile_deps", ")", "if", "self", ".", "is_mac_bundle", ":", "mac_bundle_depends", ".", "append", "(", "output", ")", "# Bundle all of the above together, if needed.", "if", "self", ".", "is_mac_bundle", ":", "output", "=", "self", ".", "WriteMacBundle", "(", "spec", ",", "mac_bundle_depends", ",", "is_empty_bundle", ")", "if", "not", "output", ":", "return", "None", "assert", "self", ".", "target", ".", "FinalOutput", "(", ")", ",", "output", "return", "self", ".", "target" ]
[ 363, 2 ]
[ 501, 22 ]
python
en
['en', 'en', 'en']
True
NinjaWriter._WinIdlRule
(self, source, prebuild, outputs)
Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.
Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.
def _WinIdlRule(self, source, prebuild, outputs): """Handle the implicit VS .idl rule for one source file. Fills |outputs| with files that are generated.""" outdir, output, vars, flags = self.msvs_settings.GetIdlBuildData( source, self.config_name) outdir = self.GypPathToNinja(outdir) def fix_path(path, rel=None): path = os.path.join(outdir, path) dirname, basename = os.path.split(source) root, ext = os.path.splitext(basename) path = self.ExpandRuleVariables( path, root, dirname, source, ext, basename) if rel: path = os.path.relpath(path, rel) return path vars = [(name, fix_path(value, outdir)) for name, value in vars] output = [fix_path(p) for p in output] vars.append(('outdir', outdir)) vars.append(('idlflags', flags)) input = self.GypPathToNinja(source) self.ninja.build(output, 'idl', input, variables=vars, order_only=prebuild) outputs.extend(output)
[ "def", "_WinIdlRule", "(", "self", ",", "source", ",", "prebuild", ",", "outputs", ")", ":", "outdir", ",", "output", ",", "vars", ",", "flags", "=", "self", ".", "msvs_settings", ".", "GetIdlBuildData", "(", "source", ",", "self", ".", "config_name", ")", "outdir", "=", "self", ".", "GypPathToNinja", "(", "outdir", ")", "def", "fix_path", "(", "path", ",", "rel", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "path", ")", "dirname", ",", "basename", "=", "os", ".", "path", ".", "split", "(", "source", ")", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "path", "=", "self", ".", "ExpandRuleVariables", "(", "path", ",", "root", ",", "dirname", ",", "source", ",", "ext", ",", "basename", ")", "if", "rel", ":", "path", "=", "os", ".", "path", ".", "relpath", "(", "path", ",", "rel", ")", "return", "path", "vars", "=", "[", "(", "name", ",", "fix_path", "(", "value", ",", "outdir", ")", ")", "for", "name", ",", "value", "in", "vars", "]", "output", "=", "[", "fix_path", "(", "p", ")", "for", "p", "in", "output", "]", "vars", ".", "append", "(", "(", "'outdir'", ",", "outdir", ")", ")", "vars", ".", "append", "(", "(", "'idlflags'", ",", "flags", ")", ")", "input", "=", "self", ".", "GypPathToNinja", "(", "source", ")", "self", ".", "ninja", ".", "build", "(", "output", ",", "'idl'", ",", "input", ",", "variables", "=", "vars", ",", "order_only", "=", "prebuild", ")", "outputs", ".", "extend", "(", "output", ")" ]
[ 503, 2 ]
[ 525, 26 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteWinIdlFiles
(self, spec, prebuild)
Writes rules to match MSVS's implicit idl handling.
Writes rules to match MSVS's implicit idl handling.
def WriteWinIdlFiles(self, spec, prebuild): """Writes rules to match MSVS's implicit idl handling.""" assert self.flavor == 'win' if self.msvs_settings.HasExplicitIdlRulesOrActions(spec): return [] outputs = [] for source in filter(lambda x: x.endswith('.idl'), spec['sources']): self._WinIdlRule(source, prebuild, outputs) return outputs
[ "def", "WriteWinIdlFiles", "(", "self", ",", "spec", ",", "prebuild", ")", ":", "assert", "self", ".", "flavor", "==", "'win'", "if", "self", ".", "msvs_settings", ".", "HasExplicitIdlRulesOrActions", "(", "spec", ")", ":", "return", "[", "]", "outputs", "=", "[", "]", "for", "source", "in", "filter", "(", "lambda", "x", ":", "x", ".", "endswith", "(", "'.idl'", ")", ",", "spec", "[", "'sources'", "]", ")", ":", "self", ".", "_WinIdlRule", "(", "source", ",", "prebuild", ",", "outputs", ")", "return", "outputs" ]
[ 527, 2 ]
[ 535, 18 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteActionsRulesCopies
(self, spec, extra_sources, prebuild, mac_bundle_depends)
Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.
Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.
def WriteActionsRulesCopies(self, spec, extra_sources, prebuild, mac_bundle_depends): """Write out the Actions, Rules, and Copies steps. Return a path representing the outputs of these steps.""" outputs = [] if self.is_mac_bundle: mac_bundle_resources = spec.get('mac_bundle_resources', [])[:] else: mac_bundle_resources = [] extra_mac_bundle_resources = [] if 'actions' in spec: outputs += self.WriteActions(spec['actions'], extra_sources, prebuild, extra_mac_bundle_resources) if 'rules' in spec: outputs += self.WriteRules(spec['rules'], extra_sources, prebuild, mac_bundle_resources, extra_mac_bundle_resources) if 'copies' in spec: outputs += self.WriteCopies(spec['copies'], prebuild, mac_bundle_depends) if 'sources' in spec and self.flavor == 'win': outputs += self.WriteWinIdlFiles(spec, prebuild) stamp = self.WriteCollapsedDependencies('actions_rules_copies', outputs) if self.is_mac_bundle: xcassets = self.WriteMacBundleResources( extra_mac_bundle_resources + mac_bundle_resources, mac_bundle_depends) partial_info_plist = self.WriteMacXCassets(xcassets, mac_bundle_depends) self.WriteMacInfoPlist(partial_info_plist, mac_bundle_depends) return stamp
[ "def", "WriteActionsRulesCopies", "(", "self", ",", "spec", ",", "extra_sources", ",", "prebuild", ",", "mac_bundle_depends", ")", ":", "outputs", "=", "[", "]", "if", "self", ".", "is_mac_bundle", ":", "mac_bundle_resources", "=", "spec", ".", "get", "(", "'mac_bundle_resources'", ",", "[", "]", ")", "[", ":", "]", "else", ":", "mac_bundle_resources", "=", "[", "]", "extra_mac_bundle_resources", "=", "[", "]", "if", "'actions'", "in", "spec", ":", "outputs", "+=", "self", ".", "WriteActions", "(", "spec", "[", "'actions'", "]", ",", "extra_sources", ",", "prebuild", ",", "extra_mac_bundle_resources", ")", "if", "'rules'", "in", "spec", ":", "outputs", "+=", "self", ".", "WriteRules", "(", "spec", "[", "'rules'", "]", ",", "extra_sources", ",", "prebuild", ",", "mac_bundle_resources", ",", "extra_mac_bundle_resources", ")", "if", "'copies'", "in", "spec", ":", "outputs", "+=", "self", ".", "WriteCopies", "(", "spec", "[", "'copies'", "]", ",", "prebuild", ",", "mac_bundle_depends", ")", "if", "'sources'", "in", "spec", "and", "self", ".", "flavor", "==", "'win'", ":", "outputs", "+=", "self", ".", "WriteWinIdlFiles", "(", "spec", ",", "prebuild", ")", "stamp", "=", "self", ".", "WriteCollapsedDependencies", "(", "'actions_rules_copies'", ",", "outputs", ")", "if", "self", ".", "is_mac_bundle", ":", "xcassets", "=", "self", ".", "WriteMacBundleResources", "(", "extra_mac_bundle_resources", "+", "mac_bundle_resources", ",", "mac_bundle_depends", ")", "partial_info_plist", "=", "self", ".", "WriteMacXCassets", "(", "xcassets", ",", "mac_bundle_depends", ")", "self", ".", "WriteMacInfoPlist", "(", "partial_info_plist", ",", "mac_bundle_depends", ")", "return", "stamp" ]
[ 537, 2 ]
[ 569, 16 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GenerateDescription
(self, verb, message, fallback)
Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback.
Generate and return a description of a build step.
def GenerateDescription(self, verb, message, fallback): """Generate and return a description of a build step. |verb| is the short summary, e.g. ACTION or RULE. |message| is a hand-written description, or None if not available. |fallback| is the gyp-level name of the step, usable as a fallback. """ if self.toolset != 'target': verb += '(%s)' % self.toolset if message: return '%s %s' % (verb, self.ExpandSpecial(message)) else: return '%s %s: %s' % (verb, self.name, fallback)
[ "def", "GenerateDescription", "(", "self", ",", "verb", ",", "message", ",", "fallback", ")", ":", "if", "self", ".", "toolset", "!=", "'target'", ":", "verb", "+=", "'(%s)'", "%", "self", ".", "toolset", "if", "message", ":", "return", "'%s %s'", "%", "(", "verb", ",", "self", ".", "ExpandSpecial", "(", "message", ")", ")", "else", ":", "return", "'%s %s: %s'", "%", "(", "verb", ",", "self", ".", "name", ",", "fallback", ")" ]
[ 571, 2 ]
[ 583, 54 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteMacBundleResources
(self, resources, bundle_depends)
Writes ninja edges for 'mac_bundle_resources'.
Writes ninja edges for 'mac_bundle_resources'.
def WriteMacBundleResources(self, resources, bundle_depends): """Writes ninja edges for 'mac_bundle_resources'.""" xcassets = [] for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(self.GypPathToNinja, resources)): output = self.ExpandSpecial(output) if os.path.splitext(output)[-1] != '.xcassets': isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(output, 'mac_tool', res, variables=[('mactool_cmd', 'copy-bundle-resource'), \ ('binary', isBinary)]) bundle_depends.append(output) else: xcassets.append(res) return xcassets
[ "def", "WriteMacBundleResources", "(", "self", ",", "resources", ",", "bundle_depends", ")", ":", "xcassets", "=", "[", "]", "for", "output", ",", "res", "in", "gyp", ".", "xcode_emulation", ".", "GetMacBundleResources", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "self", ".", "xcode_settings", ",", "map", "(", "self", ".", "GypPathToNinja", ",", "resources", ")", ")", ":", "output", "=", "self", ".", "ExpandSpecial", "(", "output", ")", "if", "os", ".", "path", ".", "splitext", "(", "output", ")", "[", "-", "1", "]", "!=", "'.xcassets'", ":", "isBinary", "=", "self", ".", "xcode_settings", ".", "IsBinaryOutputFormat", "(", "self", ".", "config_name", ")", "self", ".", "ninja", ".", "build", "(", "output", ",", "'mac_tool'", ",", "res", ",", "variables", "=", "[", "(", "'mactool_cmd'", ",", "'copy-bundle-resource'", ")", ",", "(", "'binary'", ",", "isBinary", ")", "]", ")", "bundle_depends", ".", "append", "(", "output", ")", "else", ":", "xcassets", ".", "append", "(", "res", ")", "return", "xcassets" ]
[ 764, 2 ]
[ 779, 19 ]
python
en
['nn', 'jv', 'en']
False
NinjaWriter.WriteMacXCassets
(self, xcassets, bundle_depends)
Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.
Writes ninja edges for 'mac_bundle_resources' .xcassets files.
def WriteMacXCassets(self, xcassets, bundle_depends): """Writes ninja edges for 'mac_bundle_resources' .xcassets files. This add an invocation of 'actool' via the 'mac_tool.py' helper script. It assumes that the assets catalogs define at least one imageset and thus an Assets.car file will be generated in the application resources directory. If this is not the case, then the build will probably be done at each invocation of ninja.""" if not xcassets: return extra_arguments = {} settings_to_arg = { 'XCASSETS_APP_ICON': 'app-icon', 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] for settings_key, arg_name in settings_to_arg.iteritems(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value partial_info_plist = None if extra_arguments: partial_info_plist = self.GypPathToUniqueOutput( 'assetcatalog_generated_info.plist') extra_arguments['output-partial-info-plist'] = partial_info_plist outputs = [] outputs.append( os.path.join( self.xcode_settings.GetBundleResourceFolder(), 'Assets.car')) if partial_info_plist: outputs.append(partial_info_plist) keys = QuoteShellArgument(json.dumps(extra_arguments), self.flavor) extra_env = self.xcode_settings.GetPerTargetSettings() env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) bundle_depends.extend(self.ninja.build( outputs, 'compile_xcassets', xcassets, variables=[('env', env), ('keys', keys)])) return partial_info_plist
[ "def", "WriteMacXCassets", "(", "self", ",", "xcassets", ",", "bundle_depends", ")", ":", "if", "not", "xcassets", ":", "return", "extra_arguments", "=", "{", "}", "settings_to_arg", "=", "{", "'XCASSETS_APP_ICON'", ":", "'app-icon'", ",", "'XCASSETS_LAUNCH_IMAGE'", ":", "'launch-image'", ",", "}", "settings", "=", "self", ".", "xcode_settings", ".", "xcode_settings", "[", "self", ".", "config_name", "]", "for", "settings_key", ",", "arg_name", "in", "settings_to_arg", ".", "iteritems", "(", ")", ":", "value", "=", "settings", ".", "get", "(", "settings_key", ")", "if", "value", ":", "extra_arguments", "[", "arg_name", "]", "=", "value", "partial_info_plist", "=", "None", "if", "extra_arguments", ":", "partial_info_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "'assetcatalog_generated_info.plist'", ")", "extra_arguments", "[", "'output-partial-info-plist'", "]", "=", "partial_info_plist", "outputs", "=", "[", "]", "outputs", ".", "append", "(", "os", ".", "path", ".", "join", "(", "self", ".", "xcode_settings", ".", "GetBundleResourceFolder", "(", ")", ",", "'Assets.car'", ")", ")", "if", "partial_info_plist", ":", "outputs", ".", "append", "(", "partial_info_plist", ")", "keys", "=", "QuoteShellArgument", "(", "json", ".", "dumps", "(", "extra_arguments", ")", ",", "self", ".", "flavor", ")", "extra_env", "=", "self", ".", "xcode_settings", ".", "GetPerTargetSettings", "(", ")", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "extra_env", ")", "env", "=", "self", ".", "ComputeExportEnvString", "(", "env", ")", "bundle_depends", ".", "extend", "(", "self", ".", "ninja", ".", "build", "(", "outputs", ",", "'compile_xcassets'", ",", "xcassets", ",", "variables", "=", "[", "(", "'env'", ",", "env", ")", ",", "(", "'keys'", ",", "keys", ")", "]", ")", ")", "return", "partial_info_plist" ]
[ 781, 2 ]
[ 825, 29 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteMacInfoPlist
(self, partial_info_plist, bundle_depends)
Write build rules for bundle Info.plist files.
Write build rules for bundle Info.plist files.
def WriteMacInfoPlist(self, partial_info_plist, bundle_depends): """Write build rules for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, self.GypPathToNinja) if not info_plist: return out = self.ExpandSpecial(out) if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = self.GypPathToUniqueOutput( os.path.basename(info_plist)) defines = ' '.join([Define(d, self.flavor) for d in defines]) info_plist = self.ninja.build( intermediate_plist, 'preprocess_infoplist', info_plist, variables=[('defines',defines)]) env = self.GetSortedXcodeEnv(additional_settings=extra_env) env = self.ComputeExportEnvString(env) if partial_info_plist: intermediate_plist = self.GypPathToUniqueOutput('merged_info.plist') info_plist = self.ninja.build( intermediate_plist, 'merge_infoplist', [partial_info_plist, info_plist]) keys = self.xcode_settings.GetExtraPlistItems(self.config_name) keys = QuoteShellArgument(json.dumps(keys), self.flavor) isBinary = self.xcode_settings.IsBinaryOutputFormat(self.config_name) self.ninja.build(out, 'copy_infoplist', info_plist, variables=[('env', env), ('keys', keys), ('binary', isBinary)]) bundle_depends.append(out)
[ "def", "WriteMacInfoPlist", "(", "self", ",", "partial_info_plist", ",", "bundle_depends", ")", ":", "info_plist", ",", "out", ",", "defines", ",", "extra_env", "=", "gyp", ".", "xcode_emulation", ".", "GetMacInfoPlist", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "self", ".", "xcode_settings", ",", "self", ".", "GypPathToNinja", ")", "if", "not", "info_plist", ":", "return", "out", "=", "self", ".", "ExpandSpecial", "(", "out", ")", "if", "defines", ":", "# Create an intermediate file to store preprocessed results.", "intermediate_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "os", ".", "path", ".", "basename", "(", "info_plist", ")", ")", "defines", "=", "' '", ".", "join", "(", "[", "Define", "(", "d", ",", "self", ".", "flavor", ")", "for", "d", "in", "defines", "]", ")", "info_plist", "=", "self", ".", "ninja", ".", "build", "(", "intermediate_plist", ",", "'preprocess_infoplist'", ",", "info_plist", ",", "variables", "=", "[", "(", "'defines'", ",", "defines", ")", "]", ")", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "extra_env", ")", "env", "=", "self", ".", "ComputeExportEnvString", "(", "env", ")", "if", "partial_info_plist", ":", "intermediate_plist", "=", "self", ".", "GypPathToUniqueOutput", "(", "'merged_info.plist'", ")", "info_plist", "=", "self", ".", "ninja", ".", "build", "(", "intermediate_plist", ",", "'merge_infoplist'", ",", "[", "partial_info_plist", ",", "info_plist", "]", ")", "keys", "=", "self", ".", "xcode_settings", ".", "GetExtraPlistItems", "(", "self", ".", "config_name", ")", "keys", "=", "QuoteShellArgument", "(", "json", ".", "dumps", "(", "keys", ")", ",", "self", ".", "flavor", ")", "isBinary", "=", "self", ".", "xcode_settings", ".", "IsBinaryOutputFormat", "(", "self", ".", "config_name", ")", "self", ".", "ninja", ".", "build", "(", "out", ",", "'copy_infoplist'", ",", "info_plist", ",", "variables", "=", "[", "(", "'env'", ",", "env", ")", ",", "(", "'keys'", ",", "keys", ")", ",", "(", "'binary'", ",", "isBinary", ")", "]", ")", "bundle_depends", ".", "append", "(", "out", ")" ]
[ 827, 2 ]
[ 859, 30 ]
python
en
['en', 'fr', 'en']
True
NinjaWriter.WriteSources
(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec)
Write build rules to compile all of |sources|.
Write build rules to compile all of |sources|.
def WriteSources(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec): """Write build rules to compile all of |sources|.""" if self.toolset == 'host': self.ninja.variable('ar', '$ar_host') self.ninja.variable('cc', '$cc_host') self.ninja.variable('cxx', '$cxx_host') self.ninja.variable('ld', '$ld_host') self.ninja.variable('ldxx', '$ldxx_host') self.ninja.variable('nm', '$nm_host') self.ninja.variable('readelf', '$readelf_host') if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteSourcesForArch( self.ninja, config_name, config, sources, predepends, precompiled_header, spec) else: return dict((arch, self.WriteSourcesForArch( self.arch_subninjas[arch], config_name, config, sources, predepends, precompiled_header, spec, arch=arch)) for arch in self.archs)
[ "def", "WriteSources", "(", "self", ",", "ninja_file", ",", "config_name", ",", "config", ",", "sources", ",", "predepends", ",", "precompiled_header", ",", "spec", ")", ":", "if", "self", ".", "toolset", "==", "'host'", ":", "self", ".", "ninja", ".", "variable", "(", "'ar'", ",", "'$ar_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'cc'", ",", "'$cc_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'cxx'", ",", "'$cxx_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'ld'", ",", "'$ld_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'ldxx'", ",", "'$ldxx_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'nm'", ",", "'$nm_host'", ")", "self", ".", "ninja", ".", "variable", "(", "'readelf'", ",", "'$readelf_host'", ")", "if", "self", ".", "flavor", "!=", "'mac'", "or", "len", "(", "self", ".", "archs", ")", "==", "1", ":", "return", "self", ".", "WriteSourcesForArch", "(", "self", ".", "ninja", ",", "config_name", ",", "config", ",", "sources", ",", "predepends", ",", "precompiled_header", ",", "spec", ")", "else", ":", "return", "dict", "(", "(", "arch", ",", "self", ".", "WriteSourcesForArch", "(", "self", ".", "arch_subninjas", "[", "arch", "]", ",", "config_name", ",", "config", ",", "sources", ",", "predepends", ",", "precompiled_header", ",", "spec", ",", "arch", "=", "arch", ")", ")", "for", "arch", "in", "self", ".", "archs", ")" ]
[ 861, 2 ]
[ 881, 33 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteSourcesForArch
(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None)
Write build rules to compile all of |sources|.
Write build rules to compile all of |sources|.
def WriteSourcesForArch(self, ninja_file, config_name, config, sources, predepends, precompiled_header, spec, arch=None): """Write build rules to compile all of |sources|.""" extra_defines = [] if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(config_name, arch=arch) cflags_c = self.xcode_settings.GetCflagsC(config_name) cflags_cc = self.xcode_settings.GetCflagsCC(config_name) cflags_objc = ['$cflags_c'] + \ self.xcode_settings.GetCflagsObjC(config_name) cflags_objcc = ['$cflags_cc'] + \ self.xcode_settings.GetCflagsObjCC(config_name) elif self.flavor == 'win': asmflags = self.msvs_settings.GetAsmflags(config_name) cflags = self.msvs_settings.GetCflags(config_name) cflags_c = self.msvs_settings.GetCflagsC(config_name) cflags_cc = self.msvs_settings.GetCflagsCC(config_name) extra_defines = self.msvs_settings.GetComputedDefines(config_name) # See comment at cc_command for why there's two .pdb files. pdbpath_c = pdbpath_cc = self.msvs_settings.GetCompilerPdbName( config_name, self.ExpandSpecial) if not pdbpath_c: obj = 'obj' if self.toolset != 'target': obj += '.' + self.toolset pdbpath = os.path.normpath(os.path.join(obj, self.base_dir, self.name)) pdbpath_c = pdbpath + '.c.pdb' pdbpath_cc = pdbpath + '.cc.pdb' self.WriteVariableList(ninja_file, 'pdbname_c', [pdbpath_c]) self.WriteVariableList(ninja_file, 'pdbname_cc', [pdbpath_cc]) self.WriteVariableList(ninja_file, 'pchprefix', [self.name]) else: cflags = config.get('cflags', []) cflags_c = config.get('cflags_c', []) cflags_cc = config.get('cflags_cc', []) # Respect environment variables related to build, but target-specific # flags can still override them. if self.toolset == 'target': cflags_c = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CFLAGS', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS', '').split() + os.environ.get('CXXFLAGS', '').split() + cflags_cc) elif self.toolset == 'host': cflags_c = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CFLAGS_host', '').split() + cflags_c) cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() + os.environ.get('CXXFLAGS_host', '').split() + cflags_cc) defines = config.get('defines', []) + extra_defines self.WriteVariableList(ninja_file, 'defines', [Define(d, self.flavor) for d in defines]) if self.flavor == 'win': self.WriteVariableList(ninja_file, 'asmflags', map(self.ExpandSpecial, asmflags)) self.WriteVariableList(ninja_file, 'rcflags', [QuoteShellArgument(self.ExpandSpecial(f), self.flavor) for f in self.msvs_settings.GetRcflags(config_name, self.GypPathToNinja)]) include_dirs = config.get('include_dirs', []) env = self.GetToolchainEnv() if self.flavor == 'win': include_dirs = self.msvs_settings.AdjustIncludeDirs(include_dirs, config_name) self.WriteVariableList(ninja_file, 'includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in include_dirs]) if self.flavor == 'win': midl_include_dirs = config.get('midl_include_dirs', []) midl_include_dirs = self.msvs_settings.AdjustMidlIncludeDirs( midl_include_dirs, config_name) self.WriteVariableList(ninja_file, 'midl_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in midl_include_dirs]) pch_commands = precompiled_header.GetPchBuildCommands(arch) if self.flavor == 'mac': # Most targets use no precompiled headers, so only write these if needed. for ext, var in [('c', 'cflags_pch_c'), ('cc', 'cflags_pch_cc'), ('m', 'cflags_pch_objc'), ('mm', 'cflags_pch_objcc')]: include = precompiled_header.GetInclude(ext, arch) if include: ninja_file.variable(var, include) arflags = config.get('arflags', []) self.WriteVariableList(ninja_file, 'cflags', map(self.ExpandSpecial, cflags)) self.WriteVariableList(ninja_file, 'cflags_c', map(self.ExpandSpecial, cflags_c)) self.WriteVariableList(ninja_file, 'cflags_cc', map(self.ExpandSpecial, cflags_cc)) if self.flavor == 'mac': self.WriteVariableList(ninja_file, 'cflags_objc', map(self.ExpandSpecial, cflags_objc)) self.WriteVariableList(ninja_file, 'cflags_objcc', map(self.ExpandSpecial, cflags_objcc)) self.WriteVariableList(ninja_file, 'arflags', map(self.ExpandSpecial, arflags)) ninja_file.newline() outputs = [] has_rc_source = False for source in sources: filename, ext = os.path.splitext(source) ext = ext[1:] obj_ext = self.obj_ext if ext in ('cc', 'cpp', 'cxx'): command = 'cxx' self.uses_cpp = True elif ext == 'c' or (ext == 'S' and self.flavor != 'win'): command = 'cc' elif ext == 's' and self.flavor != 'win': # Doesn't generate .o.d files. command = 'cc_s' elif (self.flavor == 'win' and ext == 'asm' and not self.msvs_settings.HasExplicitAsmRules(spec)): command = 'asm' # Add the _asm suffix as msvs is capable of handling .cc and # .asm files of the same name without collision. obj_ext = '_asm.obj' elif self.flavor == 'mac' and ext == 'm': command = 'objc' elif self.flavor == 'mac' and ext == 'mm': command = 'objcxx' self.uses_cpp = True elif self.flavor == 'win' and ext == 'rc': command = 'rc' obj_ext = '.res' has_rc_source = True else: # Ignore unhandled extensions. continue input = self.GypPathToNinja(source) output = self.GypPathToUniqueOutput(filename + obj_ext) if arch is not None: output = AddArch(output, arch) implicit = precompiled_header.GetObjDependencies([input], [output], arch) variables = [] if self.flavor == 'win': variables, output, implicit = precompiled_header.GetFlagsModifications( input, output, implicit, command, cflags_c, cflags_cc, self.ExpandSpecial) ninja_file.build(output, command, input, implicit=[gch for _, _, gch in implicit], order_only=predepends, variables=variables) outputs.append(output) if has_rc_source: resource_include_dirs = config.get('resource_include_dirs', include_dirs) self.WriteVariableList(ninja_file, 'resource_includes', [QuoteShellArgument('-I' + self.GypPathToNinja(i, env), self.flavor) for i in resource_include_dirs]) self.WritePchTargets(ninja_file, pch_commands) ninja_file.newline() return outputs
[ "def", "WriteSourcesForArch", "(", "self", ",", "ninja_file", ",", "config_name", ",", "config", ",", "sources", ",", "predepends", ",", "precompiled_header", ",", "spec", ",", "arch", "=", "None", ")", ":", "extra_defines", "=", "[", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "cflags", "=", "self", ".", "xcode_settings", ".", "GetCflags", "(", "config_name", ",", "arch", "=", "arch", ")", "cflags_c", "=", "self", ".", "xcode_settings", ".", "GetCflagsC", "(", "config_name", ")", "cflags_cc", "=", "self", ".", "xcode_settings", ".", "GetCflagsCC", "(", "config_name", ")", "cflags_objc", "=", "[", "'$cflags_c'", "]", "+", "self", ".", "xcode_settings", ".", "GetCflagsObjC", "(", "config_name", ")", "cflags_objcc", "=", "[", "'$cflags_cc'", "]", "+", "self", ".", "xcode_settings", ".", "GetCflagsObjCC", "(", "config_name", ")", "elif", "self", ".", "flavor", "==", "'win'", ":", "asmflags", "=", "self", ".", "msvs_settings", ".", "GetAsmflags", "(", "config_name", ")", "cflags", "=", "self", ".", "msvs_settings", ".", "GetCflags", "(", "config_name", ")", "cflags_c", "=", "self", ".", "msvs_settings", ".", "GetCflagsC", "(", "config_name", ")", "cflags_cc", "=", "self", ".", "msvs_settings", ".", "GetCflagsCC", "(", "config_name", ")", "extra_defines", "=", "self", ".", "msvs_settings", ".", "GetComputedDefines", "(", "config_name", ")", "# See comment at cc_command for why there's two .pdb files.", "pdbpath_c", "=", "pdbpath_cc", "=", "self", ".", "msvs_settings", ".", "GetCompilerPdbName", "(", "config_name", ",", "self", ".", "ExpandSpecial", ")", "if", "not", "pdbpath_c", ":", "obj", "=", "'obj'", "if", "self", ".", "toolset", "!=", "'target'", ":", "obj", "+=", "'.'", "+", "self", ".", "toolset", "pdbpath", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "obj", ",", "self", ".", "base_dir", ",", "self", ".", "name", ")", ")", "pdbpath_c", "=", "pdbpath", "+", "'.c.pdb'", "pdbpath_cc", "=", "pdbpath", "+", "'.cc.pdb'", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'pdbname_c'", ",", "[", "pdbpath_c", "]", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'pdbname_cc'", ",", "[", "pdbpath_cc", "]", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'pchprefix'", ",", "[", "self", ".", "name", "]", ")", "else", ":", "cflags", "=", "config", ".", "get", "(", "'cflags'", ",", "[", "]", ")", "cflags_c", "=", "config", ".", "get", "(", "'cflags_c'", ",", "[", "]", ")", "cflags_cc", "=", "config", ".", "get", "(", "'cflags_cc'", ",", "[", "]", ")", "# Respect environment variables related to build, but target-specific", "# flags can still override them.", "if", "self", ".", "toolset", "==", "'target'", ":", "cflags_c", "=", "(", "os", ".", "environ", ".", "get", "(", "'CPPFLAGS'", ",", "''", ")", ".", "split", "(", ")", "+", "os", ".", "environ", ".", "get", "(", "'CFLAGS'", ",", "''", ")", ".", "split", "(", ")", "+", "cflags_c", ")", "cflags_cc", "=", "(", "os", ".", "environ", ".", "get", "(", "'CPPFLAGS'", ",", "''", ")", ".", "split", "(", ")", "+", "os", ".", "environ", ".", "get", "(", "'CXXFLAGS'", ",", "''", ")", ".", "split", "(", ")", "+", "cflags_cc", ")", "elif", "self", ".", "toolset", "==", "'host'", ":", "cflags_c", "=", "(", "os", ".", "environ", ".", "get", "(", "'CPPFLAGS_host'", ",", "''", ")", ".", "split", "(", ")", "+", "os", ".", "environ", ".", "get", "(", "'CFLAGS_host'", ",", "''", ")", ".", "split", "(", ")", "+", "cflags_c", ")", "cflags_cc", "=", "(", "os", ".", "environ", ".", "get", "(", "'CPPFLAGS_host'", ",", "''", ")", ".", "split", "(", ")", "+", "os", ".", "environ", ".", "get", "(", "'CXXFLAGS_host'", ",", "''", ")", ".", "split", "(", ")", "+", "cflags_cc", ")", "defines", "=", "config", ".", "get", "(", "'defines'", ",", "[", "]", ")", "+", "extra_defines", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'defines'", ",", "[", "Define", "(", "d", ",", "self", ".", "flavor", ")", "for", "d", "in", "defines", "]", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'asmflags'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "asmflags", ")", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'rcflags'", ",", "[", "QuoteShellArgument", "(", "self", ".", "ExpandSpecial", "(", "f", ")", ",", "self", ".", "flavor", ")", "for", "f", "in", "self", ".", "msvs_settings", ".", "GetRcflags", "(", "config_name", ",", "self", ".", "GypPathToNinja", ")", "]", ")", "include_dirs", "=", "config", ".", "get", "(", "'include_dirs'", ",", "[", "]", ")", "env", "=", "self", ".", "GetToolchainEnv", "(", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "include_dirs", "=", "self", ".", "msvs_settings", ".", "AdjustIncludeDirs", "(", "include_dirs", ",", "config_name", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'includes'", ",", "[", "QuoteShellArgument", "(", "'-I'", "+", "self", ".", "GypPathToNinja", "(", "i", ",", "env", ")", ",", "self", ".", "flavor", ")", "for", "i", "in", "include_dirs", "]", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "midl_include_dirs", "=", "config", ".", "get", "(", "'midl_include_dirs'", ",", "[", "]", ")", "midl_include_dirs", "=", "self", ".", "msvs_settings", ".", "AdjustMidlIncludeDirs", "(", "midl_include_dirs", ",", "config_name", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'midl_includes'", ",", "[", "QuoteShellArgument", "(", "'-I'", "+", "self", ".", "GypPathToNinja", "(", "i", ",", "env", ")", ",", "self", ".", "flavor", ")", "for", "i", "in", "midl_include_dirs", "]", ")", "pch_commands", "=", "precompiled_header", ".", "GetPchBuildCommands", "(", "arch", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "# Most targets use no precompiled headers, so only write these if needed.", "for", "ext", ",", "var", "in", "[", "(", "'c'", ",", "'cflags_pch_c'", ")", ",", "(", "'cc'", ",", "'cflags_pch_cc'", ")", ",", "(", "'m'", ",", "'cflags_pch_objc'", ")", ",", "(", "'mm'", ",", "'cflags_pch_objcc'", ")", "]", ":", "include", "=", "precompiled_header", ".", "GetInclude", "(", "ext", ",", "arch", ")", "if", "include", ":", "ninja_file", ".", "variable", "(", "var", ",", "include", ")", "arflags", "=", "config", ".", "get", "(", "'arflags'", ",", "[", "]", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'cflags'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "cflags", ")", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'cflags_c'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "cflags_c", ")", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'cflags_cc'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "cflags_cc", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'cflags_objc'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "cflags_objc", ")", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'cflags_objcc'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "cflags_objcc", ")", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'arflags'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "arflags", ")", ")", "ninja_file", ".", "newline", "(", ")", "outputs", "=", "[", "]", "has_rc_source", "=", "False", "for", "source", "in", "sources", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "source", ")", "ext", "=", "ext", "[", "1", ":", "]", "obj_ext", "=", "self", ".", "obj_ext", "if", "ext", "in", "(", "'cc'", ",", "'cpp'", ",", "'cxx'", ")", ":", "command", "=", "'cxx'", "self", ".", "uses_cpp", "=", "True", "elif", "ext", "==", "'c'", "or", "(", "ext", "==", "'S'", "and", "self", ".", "flavor", "!=", "'win'", ")", ":", "command", "=", "'cc'", "elif", "ext", "==", "'s'", "and", "self", ".", "flavor", "!=", "'win'", ":", "# Doesn't generate .o.d files.", "command", "=", "'cc_s'", "elif", "(", "self", ".", "flavor", "==", "'win'", "and", "ext", "==", "'asm'", "and", "not", "self", ".", "msvs_settings", ".", "HasExplicitAsmRules", "(", "spec", ")", ")", ":", "command", "=", "'asm'", "# Add the _asm suffix as msvs is capable of handling .cc and", "# .asm files of the same name without collision.", "obj_ext", "=", "'_asm.obj'", "elif", "self", ".", "flavor", "==", "'mac'", "and", "ext", "==", "'m'", ":", "command", "=", "'objc'", "elif", "self", ".", "flavor", "==", "'mac'", "and", "ext", "==", "'mm'", ":", "command", "=", "'objcxx'", "self", ".", "uses_cpp", "=", "True", "elif", "self", ".", "flavor", "==", "'win'", "and", "ext", "==", "'rc'", ":", "command", "=", "'rc'", "obj_ext", "=", "'.res'", "has_rc_source", "=", "True", "else", ":", "# Ignore unhandled extensions.", "continue", "input", "=", "self", ".", "GypPathToNinja", "(", "source", ")", "output", "=", "self", ".", "GypPathToUniqueOutput", "(", "filename", "+", "obj_ext", ")", "if", "arch", "is", "not", "None", ":", "output", "=", "AddArch", "(", "output", ",", "arch", ")", "implicit", "=", "precompiled_header", ".", "GetObjDependencies", "(", "[", "input", "]", ",", "[", "output", "]", ",", "arch", ")", "variables", "=", "[", "]", "if", "self", ".", "flavor", "==", "'win'", ":", "variables", ",", "output", ",", "implicit", "=", "precompiled_header", ".", "GetFlagsModifications", "(", "input", ",", "output", ",", "implicit", ",", "command", ",", "cflags_c", ",", "cflags_cc", ",", "self", ".", "ExpandSpecial", ")", "ninja_file", ".", "build", "(", "output", ",", "command", ",", "input", ",", "implicit", "=", "[", "gch", "for", "_", ",", "_", ",", "gch", "in", "implicit", "]", ",", "order_only", "=", "predepends", ",", "variables", "=", "variables", ")", "outputs", ".", "append", "(", "output", ")", "if", "has_rc_source", ":", "resource_include_dirs", "=", "config", ".", "get", "(", "'resource_include_dirs'", ",", "include_dirs", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'resource_includes'", ",", "[", "QuoteShellArgument", "(", "'-I'", "+", "self", ".", "GypPathToNinja", "(", "i", ",", "env", ")", ",", "self", ".", "flavor", ")", "for", "i", "in", "resource_include_dirs", "]", ")", "self", ".", "WritePchTargets", "(", "ninja_file", ",", "pch_commands", ")", "ninja_file", ".", "newline", "(", ")", "return", "outputs" ]
[ 883, 2 ]
[ 1041, 18 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WritePchTargets
(self, ninja_file, pch_commands)
Writes ninja rules to compile prefix headers.
Writes ninja rules to compile prefix headers.
def WritePchTargets(self, ninja_file, pch_commands): """Writes ninja rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: var_name = { 'c': 'cflags_pch_c', 'cc': 'cflags_pch_cc', 'm': 'cflags_pch_objc', 'mm': 'cflags_pch_objcc', }[lang] map = { 'c': 'cc', 'cc': 'cxx', 'm': 'objc', 'mm': 'objcxx', } cmd = map.get(lang) ninja_file.build(gch, cmd, input, variables=[(var_name, lang_flag)])
[ "def", "WritePchTargets", "(", "self", ",", "ninja_file", ",", "pch_commands", ")", ":", "if", "not", "pch_commands", ":", "return", "for", "gch", ",", "lang_flag", ",", "lang", ",", "input", "in", "pch_commands", ":", "var_name", "=", "{", "'c'", ":", "'cflags_pch_c'", ",", "'cc'", ":", "'cflags_pch_cc'", ",", "'m'", ":", "'cflags_pch_objc'", ",", "'mm'", ":", "'cflags_pch_objcc'", ",", "}", "[", "lang", "]", "map", "=", "{", "'c'", ":", "'cc'", ",", "'cc'", ":", "'cxx'", ",", "'m'", ":", "'objc'", ",", "'mm'", ":", "'objcxx'", ",", "}", "cmd", "=", "map", ".", "get", "(", "lang", ")", "ninja_file", ".", "build", "(", "gch", ",", "cmd", ",", "input", ",", "variables", "=", "[", "(", "var_name", ",", "lang_flag", ")", "]", ")" ]
[ 1043, 2 ]
[ 1058, 74 ]
python
en
['en', 'et', 'en']
True
NinjaWriter.WriteLink
(self, spec, config_name, config, link_deps)
Write out a link step. Fills out target.binary.
Write out a link step. Fills out target.binary.
def WriteLink(self, spec, config_name, config, link_deps): """Write out a link step. Fills out target.binary. """ if self.flavor != 'mac' or len(self.archs) == 1: return self.WriteLinkForArch( self.ninja, spec, config_name, config, link_deps) else: output = self.ComputeOutput(spec) inputs = [self.WriteLinkForArch(self.arch_subninjas[arch], spec, config_name, config, link_deps[arch], arch=arch) for arch in self.archs] extra_bindings = [] build_output = output if not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) # TODO(yyanagisawa): more work needed to fix: # https://code.google.com/p/gyp/issues/detail?id=411 if (spec['type'] in ('shared_library', 'loadable_module') and not self.is_mac_bundle): extra_bindings.append(('lib', output)) self.ninja.build([output, output + '.TOC'], 'solipo', inputs, variables=extra_bindings) else: self.ninja.build(build_output, 'lipo', inputs, variables=extra_bindings) return output
[ "def", "WriteLink", "(", "self", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", ")", ":", "if", "self", ".", "flavor", "!=", "'mac'", "or", "len", "(", "self", ".", "archs", ")", "==", "1", ":", "return", "self", ".", "WriteLinkForArch", "(", "self", ".", "ninja", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", ")", "else", ":", "output", "=", "self", ".", "ComputeOutput", "(", "spec", ")", "inputs", "=", "[", "self", ".", "WriteLinkForArch", "(", "self", ".", "arch_subninjas", "[", "arch", "]", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", "[", "arch", "]", ",", "arch", "=", "arch", ")", "for", "arch", "in", "self", ".", "archs", "]", "extra_bindings", "=", "[", "]", "build_output", "=", "output", "if", "not", "self", ".", "is_mac_bundle", ":", "self", ".", "AppendPostbuildVariable", "(", "extra_bindings", ",", "spec", ",", "output", ",", "output", ")", "# TODO(yyanagisawa): more work needed to fix:", "# https://code.google.com/p/gyp/issues/detail?id=411", "if", "(", "spec", "[", "'type'", "]", "in", "(", "'shared_library'", ",", "'loadable_module'", ")", "and", "not", "self", ".", "is_mac_bundle", ")", ":", "extra_bindings", ".", "append", "(", "(", "'lib'", ",", "output", ")", ")", "self", ".", "ninja", ".", "build", "(", "[", "output", ",", "output", "+", "'.TOC'", "]", ",", "'solipo'", ",", "inputs", ",", "variables", "=", "extra_bindings", ")", "else", ":", "self", ".", "ninja", ".", "build", "(", "build_output", ",", "'lipo'", ",", "inputs", ",", "variables", "=", "extra_bindings", ")", "return", "output" ]
[ 1060, 2 ]
[ 1085, 19 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteLinkForArch
(self, ninja_file, spec, config_name, config, link_deps, arch=None)
Write out a link step. Fills out target.binary.
Write out a link step. Fills out target.binary.
def WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() order_deps = set() if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if (self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name)): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self.ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self.AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. env_ldflags = os.environ.get('LDFLAGS', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self.ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self.GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self.GypPathToUniqueOutput( self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = \ self.msvs_settings.GetLdflags(config_name, self.GypPathToNinja, self.ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self.WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self.WriteVariableList( ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = _GetWinLinkRuleNameSuffix( self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self.GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self.WriteVariableList(ninja_file, 'ldflags', map(self.ExpandSpecial, ldflags)) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + QuoteShellArgument(self.GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [QuoteShellArgument('-L' + self.GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self.ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self.WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append( ('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if ('/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name)): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName( config_name, self.ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(solibs))) ninja_file.build(output, command + command_suffix, link_deps, implicit=list(implicit_deps), order_only=list(order_deps), variables=extra_bindings) return linked_binary
[ "def", "WriteLinkForArch", "(", "self", ",", "ninja_file", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", ",", "arch", "=", "None", ")", ":", "command", "=", "{", "'executable'", ":", "'link'", ",", "'loadable_module'", ":", "'solink_module'", ",", "'shared_library'", ":", "'solink'", ",", "}", "[", "spec", "[", "'type'", "]", "]", "command_suffix", "=", "''", "implicit_deps", "=", "set", "(", ")", "solibs", "=", "set", "(", ")", "order_deps", "=", "set", "(", ")", "if", "'dependencies'", "in", "spec", ":", "# Two kinds of dependencies:", "# - Linkable dependencies (like a .a or a .so): add them to the link line.", "# - Non-linkable dependencies (like a rule that generates a file", "# and writes a stamp file): add them to implicit_deps", "extra_link_deps", "=", "set", "(", ")", "for", "dep", "in", "spec", "[", "'dependencies'", "]", ":", "target", "=", "self", ".", "target_outputs", ".", "get", "(", "dep", ")", "if", "not", "target", ":", "continue", "linkable", "=", "target", ".", "Linkable", "(", ")", "if", "linkable", ":", "new_deps", "=", "[", "]", "if", "(", "self", ".", "flavor", "==", "'win'", "and", "target", ".", "component_objs", "and", "self", ".", "msvs_settings", ".", "IsUseLibraryDependencyInputs", "(", "config_name", ")", ")", ":", "new_deps", "=", "target", ".", "component_objs", "if", "target", ".", "compile_deps", ":", "order_deps", ".", "add", "(", "target", ".", "compile_deps", ")", "elif", "self", ".", "flavor", "==", "'win'", "and", "target", ".", "import_lib", ":", "new_deps", "=", "[", "target", ".", "import_lib", "]", "elif", "target", ".", "UsesToc", "(", "self", ".", "flavor", ")", ":", "solibs", ".", "add", "(", "target", ".", "binary", ")", "implicit_deps", ".", "add", "(", "target", ".", "binary", "+", "'.TOC'", ")", "else", ":", "new_deps", "=", "[", "target", ".", "binary", "]", "for", "new_dep", "in", "new_deps", ":", "if", "new_dep", "not", "in", "extra_link_deps", ":", "extra_link_deps", ".", "add", "(", "new_dep", ")", "link_deps", ".", "append", "(", "new_dep", ")", "final_output", "=", "target", ".", "FinalOutput", "(", ")", "if", "not", "linkable", "or", "final_output", "!=", "target", ".", "binary", ":", "implicit_deps", ".", "add", "(", "final_output", ")", "extra_bindings", "=", "[", "]", "if", "self", ".", "uses_cpp", "and", "self", ".", "flavor", "!=", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'ld'", ",", "'$ldxx'", ")", ")", "output", "=", "self", ".", "ComputeOutput", "(", "spec", ",", "arch", ")", "if", "arch", "is", "None", "and", "not", "self", ".", "is_mac_bundle", ":", "self", ".", "AppendPostbuildVariable", "(", "extra_bindings", ",", "spec", ",", "output", ",", "output", ")", "is_executable", "=", "spec", "[", "'type'", "]", "==", "'executable'", "# The ldflags config key is not used on mac or win. On those platforms", "# linker flags are set via xcode_settings and msvs_settings, respectively.", "env_ldflags", "=", "os", ".", "environ", ".", "get", "(", "'LDFLAGS'", ",", "''", ")", ".", "split", "(", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "ldflags", "=", "self", ".", "xcode_settings", ".", "GetLdflags", "(", "config_name", ",", "self", ".", "ExpandSpecial", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", ",", "self", ".", "GypPathToNinja", ",", "arch", ")", "ldflags", "=", "env_ldflags", "+", "ldflags", "elif", "self", ".", "flavor", "==", "'win'", ":", "manifest_base_name", "=", "self", ".", "GypPathToUniqueOutput", "(", "self", ".", "ComputeOutputFileName", "(", "spec", ")", ")", "ldflags", ",", "intermediate_manifest", ",", "manifest_files", "=", "self", ".", "msvs_settings", ".", "GetLdflags", "(", "config_name", ",", "self", ".", "GypPathToNinja", ",", "self", ".", "ExpandSpecial", ",", "manifest_base_name", ",", "output", ",", "is_executable", ",", "self", ".", "toplevel_build", ")", "ldflags", "=", "env_ldflags", "+", "ldflags", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'manifests'", ",", "manifest_files", ")", "implicit_deps", "=", "implicit_deps", ".", "union", "(", "manifest_files", ")", "if", "intermediate_manifest", ":", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'intermediatemanifest'", ",", "[", "intermediate_manifest", "]", ")", "command_suffix", "=", "_GetWinLinkRuleNameSuffix", "(", "self", ".", "msvs_settings", ".", "IsEmbedManifest", "(", "config_name", ")", ")", "def_file", "=", "self", ".", "msvs_settings", ".", "GetDefFile", "(", "self", ".", "GypPathToNinja", ")", "if", "def_file", ":", "implicit_deps", ".", "add", "(", "def_file", ")", "else", ":", "# Respect environment variables related to build, but target-specific", "# flags can still override them.", "ldflags", "=", "env_ldflags", "+", "config", ".", "get", "(", "'ldflags'", ",", "[", "]", ")", "if", "is_executable", "and", "len", "(", "solibs", ")", ":", "rpath", "=", "'lib/'", "if", "self", ".", "toolset", "!=", "'target'", ":", "rpath", "+=", "self", ".", "toolset", "ldflags", ".", "append", "(", "r'-Wl,-rpath=\\$$ORIGIN/%s'", "%", "rpath", ")", "ldflags", ".", "append", "(", "'-Wl,-rpath-link=%s'", "%", "rpath", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'ldflags'", ",", "map", "(", "self", ".", "ExpandSpecial", ",", "ldflags", ")", ")", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "library_dirs", "=", "[", "self", ".", "msvs_settings", ".", "ConvertVSMacros", "(", "l", ",", "config_name", ")", "for", "l", "in", "library_dirs", "]", "library_dirs", "=", "[", "'/LIBPATH:'", "+", "QuoteShellArgument", "(", "self", ".", "GypPathToNinja", "(", "l", ")", ",", "self", ".", "flavor", ")", "for", "l", "in", "library_dirs", "]", "else", ":", "library_dirs", "=", "[", "QuoteShellArgument", "(", "'-L'", "+", "self", ".", "GypPathToNinja", "(", "l", ")", ",", "self", ".", "flavor", ")", "for", "l", "in", "library_dirs", "]", "libraries", "=", "gyp", ".", "common", ".", "uniquer", "(", "map", "(", "self", ".", "ExpandSpecial", ",", "spec", ".", "get", "(", "'libraries'", ",", "[", "]", ")", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "libraries", "=", "self", ".", "xcode_settings", ".", "AdjustLibraries", "(", "libraries", ",", "config_name", ")", "elif", "self", ".", "flavor", "==", "'win'", ":", "libraries", "=", "self", ".", "msvs_settings", ".", "AdjustLibraries", "(", "libraries", ")", "self", ".", "WriteVariableList", "(", "ninja_file", ",", "'libs'", ",", "library_dirs", "+", "libraries", ")", "linked_binary", "=", "output", "if", "command", "in", "(", "'solink'", ",", "'solink_module'", ")", ":", "extra_bindings", ".", "append", "(", "(", "'soname'", ",", "os", ".", "path", ".", "split", "(", "output", ")", "[", "1", "]", ")", ")", "extra_bindings", ".", "append", "(", "(", "'lib'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "output", ")", ")", ")", "if", "self", ".", "flavor", "!=", "'win'", ":", "link_file_list", "=", "output", "if", "self", ".", "is_mac_bundle", ":", "# 'Dependency Framework.framework/Versions/A/Dependency Framework' ->", "# 'Dependency Framework.framework.rsp'", "link_file_list", "=", "self", ".", "xcode_settings", ".", "GetWrapperName", "(", ")", "if", "arch", ":", "link_file_list", "+=", "'.'", "+", "arch", "link_file_list", "+=", "'.rsp'", "# If an rspfile contains spaces, ninja surrounds the filename with", "# quotes around it and then passes it to open(), creating a file with", "# quotes in its name (and when looking for the rsp file, the name", "# makes it through bash which strips the quotes) :-/", "link_file_list", "=", "link_file_list", ".", "replace", "(", "' '", ",", "'_'", ")", "extra_bindings", ".", "append", "(", "(", "'link_file_list'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "link_file_list", ")", ")", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'binary'", ",", "output", ")", ")", "if", "(", "'/NOENTRY'", "not", "in", "ldflags", "and", "not", "self", ".", "msvs_settings", ".", "GetNoImportLibrary", "(", "config_name", ")", ")", ":", "self", ".", "target", ".", "import_lib", "=", "output", "+", "'.lib'", "extra_bindings", ".", "append", "(", "(", "'implibflag'", ",", "'/IMPLIB:%s'", "%", "self", ".", "target", ".", "import_lib", ")", ")", "pdbname", "=", "self", ".", "msvs_settings", ".", "GetPDBName", "(", "config_name", ",", "self", ".", "ExpandSpecial", ",", "output", "+", "'.pdb'", ")", "output", "=", "[", "output", ",", "self", ".", "target", ".", "import_lib", "]", "if", "pdbname", ":", "output", ".", "append", "(", "pdbname", ")", "elif", "not", "self", ".", "is_mac_bundle", ":", "output", "=", "[", "output", ",", "output", "+", "'.TOC'", "]", "else", ":", "command", "=", "command", "+", "'_notoc'", "elif", "self", ".", "flavor", "==", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'binary'", ",", "output", ")", ")", "pdbname", "=", "self", ".", "msvs_settings", ".", "GetPDBName", "(", "config_name", ",", "self", ".", "ExpandSpecial", ",", "output", "+", "'.pdb'", ")", "if", "pdbname", ":", "output", "=", "[", "output", ",", "pdbname", "]", "if", "len", "(", "solibs", ")", ":", "extra_bindings", ".", "append", "(", "(", "'solibs'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "solibs", ")", ")", ")", "ninja_file", ".", "build", "(", "output", ",", "command", "+", "command_suffix", ",", "link_deps", ",", "implicit", "=", "list", "(", "implicit_deps", ")", ",", "order_only", "=", "list", "(", "order_deps", ")", ",", "variables", "=", "extra_bindings", ")", "return", "linked_binary" ]
[ 1087, 2 ]
[ 1260, 24 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetToolchainEnv
(self, additional_settings=None)
Returns the variables toolchain would set for build steps.
Returns the variables toolchain would set for build steps.
def GetToolchainEnv(self, additional_settings=None): """Returns the variables toolchain would set for build steps.""" env = self.GetSortedXcodeEnv(additional_settings=additional_settings) if self.flavor == 'win': env = self.GetMsvsToolchainEnv( additional_settings=additional_settings) return env
[ "def", "GetToolchainEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "additional_settings", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "env", "=", "self", ".", "GetMsvsToolchainEnv", "(", "additional_settings", "=", "additional_settings", ")", "return", "env" ]
[ 1332, 2 ]
[ 1338, 14 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetMsvsToolchainEnv
(self, additional_settings=None)
Returns the variables Visual Studio would set for build steps.
Returns the variables Visual Studio would set for build steps.
def GetMsvsToolchainEnv(self, additional_settings=None): """Returns the variables Visual Studio would set for build steps.""" return self.msvs_settings.GetVSMacroEnv('$!PRODUCT_DIR', config=self.config_name)
[ "def", "GetMsvsToolchainEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "return", "self", ".", "msvs_settings", ".", "GetVSMacroEnv", "(", "'$!PRODUCT_DIR'", ",", "config", "=", "self", ".", "config_name", ")" ]
[ 1340, 2 ]
[ 1343, 69 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetSortedXcodeEnv
(self, additional_settings=None)
Returns the variables Xcode would set for build steps.
Returns the variables Xcode would set for build steps.
def GetSortedXcodeEnv(self, additional_settings=None): """Returns the variables Xcode would set for build steps.""" assert self.abs_build_dir abs_build_dir = self.abs_build_dir return gyp.xcode_emulation.GetSortedXcodeEnv( self.xcode_settings, abs_build_dir, os.path.join(abs_build_dir, self.build_to_base), self.config_name, additional_settings)
[ "def", "GetSortedXcodeEnv", "(", "self", ",", "additional_settings", "=", "None", ")", ":", "assert", "self", ".", "abs_build_dir", "abs_build_dir", "=", "self", ".", "abs_build_dir", "return", "gyp", ".", "xcode_emulation", ".", "GetSortedXcodeEnv", "(", "self", ".", "xcode_settings", ",", "abs_build_dir", ",", "os", ".", "path", ".", "join", "(", "abs_build_dir", ",", "self", ".", "build_to_base", ")", ",", "self", ".", "config_name", ",", "additional_settings", ")" ]
[ 1345, 2 ]
[ 1352, 28 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetSortedXcodePostbuildEnv
(self)
Returns the variables Xcode would set for postbuild steps.
Returns the variables Xcode would set for postbuild steps.
def GetSortedXcodePostbuildEnv(self): """Returns the variables Xcode would set for postbuild steps.""" postbuild_settings = {} # CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack. # TODO(thakis): It would be nice to have some general mechanism instead. strip_save_file = self.xcode_settings.GetPerTargetSetting( 'CHROMIUM_STRIP_SAVE_FILE') if strip_save_file: postbuild_settings['CHROMIUM_STRIP_SAVE_FILE'] = strip_save_file return self.GetSortedXcodeEnv(additional_settings=postbuild_settings)
[ "def", "GetSortedXcodePostbuildEnv", "(", "self", ")", ":", "postbuild_settings", "=", "{", "}", "# CHROMIUM_STRIP_SAVE_FILE is a chromium-specific hack.", "# TODO(thakis): It would be nice to have some general mechanism instead.", "strip_save_file", "=", "self", ".", "xcode_settings", ".", "GetPerTargetSetting", "(", "'CHROMIUM_STRIP_SAVE_FILE'", ")", "if", "strip_save_file", ":", "postbuild_settings", "[", "'CHROMIUM_STRIP_SAVE_FILE'", "]", "=", "strip_save_file", "return", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "postbuild_settings", ")" ]
[ 1354, 2 ]
[ 1363, 73 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.AppendPostbuildVariable
(self, variables, spec, output, binary, is_command_start=False)
Adds a 'postbuild' variable if there is a postbuild for |output|.
Adds a 'postbuild' variable if there is a postbuild for |output|.
def AppendPostbuildVariable(self, variables, spec, output, binary, is_command_start=False): """Adds a 'postbuild' variable if there is a postbuild for |output|.""" postbuild = self.GetPostbuildCommand(spec, output, binary, is_command_start) if postbuild: variables.append(('postbuilds', postbuild))
[ "def", "AppendPostbuildVariable", "(", "self", ",", "variables", ",", "spec", ",", "output", ",", "binary", ",", "is_command_start", "=", "False", ")", ":", "postbuild", "=", "self", ".", "GetPostbuildCommand", "(", "spec", ",", "output", ",", "binary", ",", "is_command_start", ")", "if", "postbuild", ":", "variables", ".", "append", "(", "(", "'postbuilds'", ",", "postbuild", ")", ")" ]
[ 1365, 2 ]
[ 1370, 49 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.GetPostbuildCommand
(self, spec, output, output_binary, is_command_start)
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.
def GetPostbuildCommand(self, spec, output, output_binary, is_command_start): """Returns a shell command that runs all the postbuilds, and removes |output| if any of them fails. If |is_command_start| is False, then the returned string will start with ' && '.""" if not self.xcode_settings or spec['type'] == 'none' or not output: return '' output = QuoteShellArgument(output, self.flavor) postbuilds = gyp.xcode_emulation.GetSpecPostbuildCommands(spec, quiet=True) if output_binary is not None: postbuilds = self.xcode_settings.AddImplicitPostbuilds( self.config_name, os.path.normpath(os.path.join(self.base_to_build, output)), QuoteShellArgument( os.path.normpath(os.path.join(self.base_to_build, output_binary)), self.flavor), postbuilds, quiet=True) if not postbuilds: return '' # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList( ['cd', self.build_to_base])) env = self.ComputeExportEnvString(self.GetSortedXcodePostbuildEnv()) # G will be non-null if any postbuild fails. Run all postbuilds in a # subshell. commands = env + ' (' + \ ' && '.join([ninja_syntax.escape(command) for command in postbuilds]) command_string = (commands + '); G=$$?; ' # Remove the final output if any postbuild failed. '((exit $$G) || rm -rf %s) ' % output + '&& exit $$G)') if is_command_start: return '(' + command_string + ' && ' else: return '$ && (' + command_string
[ "def", "GetPostbuildCommand", "(", "self", ",", "spec", ",", "output", ",", "output_binary", ",", "is_command_start", ")", ":", "if", "not", "self", ".", "xcode_settings", "or", "spec", "[", "'type'", "]", "==", "'none'", "or", "not", "output", ":", "return", "''", "output", "=", "QuoteShellArgument", "(", "output", ",", "self", ".", "flavor", ")", "postbuilds", "=", "gyp", ".", "xcode_emulation", ".", "GetSpecPostbuildCommands", "(", "spec", ",", "quiet", "=", "True", ")", "if", "output_binary", "is", "not", "None", ":", "postbuilds", "=", "self", ".", "xcode_settings", ".", "AddImplicitPostbuilds", "(", "self", ".", "config_name", ",", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "base_to_build", ",", "output", ")", ")", ",", "QuoteShellArgument", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "base_to_build", ",", "output_binary", ")", ")", ",", "self", ".", "flavor", ")", ",", "postbuilds", ",", "quiet", "=", "True", ")", "if", "not", "postbuilds", ":", "return", "''", "# Postbuilds expect to be run in the gyp file's directory, so insert an", "# implicit postbuild to cd to there.", "postbuilds", ".", "insert", "(", "0", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "'cd'", ",", "self", ".", "build_to_base", "]", ")", ")", "env", "=", "self", ".", "ComputeExportEnvString", "(", "self", ".", "GetSortedXcodePostbuildEnv", "(", ")", ")", "# G will be non-null if any postbuild fails. Run all postbuilds in a", "# subshell.", "commands", "=", "env", "+", "' ('", "+", "' && '", ".", "join", "(", "[", "ninja_syntax", ".", "escape", "(", "command", ")", "for", "command", "in", "postbuilds", "]", ")", "command_string", "=", "(", "commands", "+", "'); G=$$?; '", "# Remove the final output if any postbuild failed.", "'((exit $$G) || rm -rf %s) '", "%", "output", "+", "'&& exit $$G)'", ")", "if", "is_command_start", ":", "return", "'('", "+", "command_string", "+", "' && '", "else", ":", "return", "'$ && ('", "+", "command_string" ]
[ 1372, 2 ]
[ 1406, 38 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeExportEnvString
(self, env)
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.
def ComputeExportEnvString(self, env): """Given an environment, returns a string looking like 'export FOO=foo; export BAR="${FOO} bar;' that exports |env| to the shell.""" export_str = [] for k, v in env: export_str.append('export %s=%s;' % (k, ninja_syntax.escape(gyp.common.EncodePOSIXShellArgument(v)))) return ' '.join(export_str)
[ "def", "ComputeExportEnvString", "(", "self", ",", "env", ")", ":", "export_str", "=", "[", "]", "for", "k", ",", "v", "in", "env", ":", "export_str", ".", "append", "(", "'export %s=%s;'", "%", "(", "k", ",", "ninja_syntax", ".", "escape", "(", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "v", ")", ")", ")", ")", "return", "' '", ".", "join", "(", "export_str", ")" ]
[ 1408, 2 ]
[ 1416, 31 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeMacBundleOutput
(self)
Return the 'output' (full output path) to a bundle output directory.
Return the 'output' (full output path) to a bundle output directory.
def ComputeMacBundleOutput(self): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return self.ExpandSpecial( os.path.join(path, self.xcode_settings.GetWrapperName()))
[ "def", "ComputeMacBundleOutput", "(", "self", ")", ":", "assert", "self", ".", "is_mac_bundle", "path", "=", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", "return", "self", ".", "ExpandSpecial", "(", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "xcode_settings", ".", "GetWrapperName", "(", ")", ")", ")" ]
[ 1418, 2 ]
[ 1423, 65 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeOutputFileName
(self, spec, type=None)
Compute the filename of the final output for the current target.
Compute the filename of the final output for the current target.
def ComputeOutputFileName(self, spec, type=None): """Compute the filename of the final output for the current target.""" if not type: type = spec['type'] default_variables = copy.copy(generator_default_variables) CalculateVariables(default_variables, {'flavor': self.flavor}) # Compute filename prefix: the product prefix, or a default for # the product type. DEFAULT_PREFIX = { 'loadable_module': default_variables['SHARED_LIB_PREFIX'], 'shared_library': default_variables['SHARED_LIB_PREFIX'], 'static_library': default_variables['STATIC_LIB_PREFIX'], 'executable': default_variables['EXECUTABLE_PREFIX'], } prefix = spec.get('product_prefix', DEFAULT_PREFIX.get(type, '')) # Compute filename extension: the product extension, or a default # for the product type. DEFAULT_EXTENSION = { 'loadable_module': default_variables['SHARED_LIB_SUFFIX'], 'shared_library': default_variables['SHARED_LIB_SUFFIX'], 'static_library': default_variables['STATIC_LIB_SUFFIX'], 'executable': default_variables['EXECUTABLE_SUFFIX'], } extension = spec.get('product_extension') if extension: extension = '.' + extension else: extension = DEFAULT_EXTENSION.get(type, '') if 'product_name' in spec: # If we were given an explicit name, use that. target = spec['product_name'] else: # Otherwise, derive a name from the target name. target = spec['target_name'] if prefix == 'lib': # Snip out an extra 'lib' from libs if appropriate. target = StripPrefix(target, 'lib') if type in ('static_library', 'loadable_module', 'shared_library', 'executable'): return '%s%s%s' % (prefix, target, extension) elif type == 'none': return '%s.stamp' % target else: raise Exception('Unhandled output type %s' % type)
[ "def", "ComputeOutputFileName", "(", "self", ",", "spec", ",", "type", "=", "None", ")", ":", "if", "not", "type", ":", "type", "=", "spec", "[", "'type'", "]", "default_variables", "=", "copy", ".", "copy", "(", "generator_default_variables", ")", "CalculateVariables", "(", "default_variables", ",", "{", "'flavor'", ":", "self", ".", "flavor", "}", ")", "# Compute filename prefix: the product prefix, or a default for", "# the product type.", "DEFAULT_PREFIX", "=", "{", "'loadable_module'", ":", "default_variables", "[", "'SHARED_LIB_PREFIX'", "]", ",", "'shared_library'", ":", "default_variables", "[", "'SHARED_LIB_PREFIX'", "]", ",", "'static_library'", ":", "default_variables", "[", "'STATIC_LIB_PREFIX'", "]", ",", "'executable'", ":", "default_variables", "[", "'EXECUTABLE_PREFIX'", "]", ",", "}", "prefix", "=", "spec", ".", "get", "(", "'product_prefix'", ",", "DEFAULT_PREFIX", ".", "get", "(", "type", ",", "''", ")", ")", "# Compute filename extension: the product extension, or a default", "# for the product type.", "DEFAULT_EXTENSION", "=", "{", "'loadable_module'", ":", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", ",", "'shared_library'", ":", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", ",", "'static_library'", ":", "default_variables", "[", "'STATIC_LIB_SUFFIX'", "]", ",", "'executable'", ":", "default_variables", "[", "'EXECUTABLE_SUFFIX'", "]", ",", "}", "extension", "=", "spec", ".", "get", "(", "'product_extension'", ")", "if", "extension", ":", "extension", "=", "'.'", "+", "extension", "else", ":", "extension", "=", "DEFAULT_EXTENSION", ".", "get", "(", "type", ",", "''", ")", "if", "'product_name'", "in", "spec", ":", "# If we were given an explicit name, use that.", "target", "=", "spec", "[", "'product_name'", "]", "else", ":", "# Otherwise, derive a name from the target name.", "target", "=", "spec", "[", "'target_name'", "]", "if", "prefix", "==", "'lib'", ":", "# Snip out an extra 'lib' from libs if appropriate.", "target", "=", "StripPrefix", "(", "target", ",", "'lib'", ")", "if", "type", "in", "(", "'static_library'", ",", "'loadable_module'", ",", "'shared_library'", ",", "'executable'", ")", ":", "return", "'%s%s%s'", "%", "(", "prefix", ",", "target", ",", "extension", ")", "elif", "type", "==", "'none'", ":", "return", "'%s.stamp'", "%", "target", "else", ":", "raise", "Exception", "(", "'Unhandled output type %s'", "%", "type", ")" ]
[ 1425, 2 ]
[ 1473, 56 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.ComputeOutput
(self, spec, arch=None)
Compute the path for the final output of the spec.
Compute the path for the final output of the spec.
def ComputeOutput(self, spec, arch=None): """Compute the path for the final output of the spec.""" type = spec['type'] if self.flavor == 'win': override = self.msvs_settings.GetOutputName(self.config_name, self.ExpandSpecial) if override: return override if arch is None and self.flavor == 'mac' and type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): filename = self.xcode_settings.GetExecutablePath() else: filename = self.ComputeOutputFileName(spec, type) if arch is None and 'product_dir' in spec: path = os.path.join(spec['product_dir'], filename) return self.ExpandSpecial(path) # Some products go into the output root, libraries go into shared library # dir, and everything else goes into the normal place. type_in_output_root = ['executable', 'loadable_module'] if self.flavor == 'mac' and self.toolset == 'target': type_in_output_root += ['shared_library', 'static_library'] elif self.flavor == 'win' and self.toolset == 'target': type_in_output_root += ['shared_library'] if arch is not None: # Make sure partial executables don't end up in a bundle or the regular # output directory. archdir = 'arch' if self.toolset != 'target': archdir = os.path.join('arch', '%s' % self.toolset) return os.path.join(archdir, AddArch(filename, arch)) elif type in type_in_output_root or self.is_standalone_static_library: return filename elif type == 'shared_library': libdir = 'lib' if self.toolset != 'target': libdir = os.path.join('lib', '%s' % self.toolset) return os.path.join(libdir, filename) else: return self.GypPathToUniqueOutput(filename, qualified=False)
[ "def", "ComputeOutput", "(", "self", ",", "spec", ",", "arch", "=", "None", ")", ":", "type", "=", "spec", "[", "'type'", "]", "if", "self", ".", "flavor", "==", "'win'", ":", "override", "=", "self", ".", "msvs_settings", ".", "GetOutputName", "(", "self", ".", "config_name", ",", "self", ".", "ExpandSpecial", ")", "if", "override", ":", "return", "override", "if", "arch", "is", "None", "and", "self", ".", "flavor", "==", "'mac'", "and", "type", "in", "(", "'static_library'", ",", "'executable'", ",", "'shared_library'", ",", "'loadable_module'", ")", ":", "filename", "=", "self", ".", "xcode_settings", ".", "GetExecutablePath", "(", ")", "else", ":", "filename", "=", "self", ".", "ComputeOutputFileName", "(", "spec", ",", "type", ")", "if", "arch", "is", "None", "and", "'product_dir'", "in", "spec", ":", "path", "=", "os", ".", "path", ".", "join", "(", "spec", "[", "'product_dir'", "]", ",", "filename", ")", "return", "self", ".", "ExpandSpecial", "(", "path", ")", "# Some products go into the output root, libraries go into shared library", "# dir, and everything else goes into the normal place.", "type_in_output_root", "=", "[", "'executable'", ",", "'loadable_module'", "]", "if", "self", ".", "flavor", "==", "'mac'", "and", "self", ".", "toolset", "==", "'target'", ":", "type_in_output_root", "+=", "[", "'shared_library'", ",", "'static_library'", "]", "elif", "self", ".", "flavor", "==", "'win'", "and", "self", ".", "toolset", "==", "'target'", ":", "type_in_output_root", "+=", "[", "'shared_library'", "]", "if", "arch", "is", "not", "None", ":", "# Make sure partial executables don't end up in a bundle or the regular", "# output directory.", "archdir", "=", "'arch'", "if", "self", ".", "toolset", "!=", "'target'", ":", "archdir", "=", "os", ".", "path", ".", "join", "(", "'arch'", ",", "'%s'", "%", "self", ".", "toolset", ")", "return", "os", ".", "path", ".", "join", "(", "archdir", ",", "AddArch", "(", "filename", ",", "arch", ")", ")", "elif", "type", "in", "type_in_output_root", "or", "self", ".", "is_standalone_static_library", ":", "return", "filename", "elif", "type", "==", "'shared_library'", ":", "libdir", "=", "'lib'", "if", "self", ".", "toolset", "!=", "'target'", ":", "libdir", "=", "os", ".", "path", ".", "join", "(", "'lib'", ",", "'%s'", "%", "self", ".", "toolset", ")", "return", "os", ".", "path", ".", "join", "(", "libdir", ",", "filename", ")", "else", ":", "return", "self", ".", "GypPathToUniqueOutput", "(", "filename", ",", "qualified", "=", "False", ")" ]
[ 1475, 2 ]
[ 1518, 66 ]
python
en
['en', 'en', 'en']
True
NinjaWriter.WriteNewNinjaRule
(self, name, args, description, is_cygwin, env, pool, depfile=None)
Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.
Write out a new ninja "rule" statement for a given command.
def WriteNewNinjaRule(self, name, args, description, is_cygwin, env, pool, depfile=None): """Write out a new ninja "rule" statement for a given command. Returns the name of the new rule, and a copy of |args| with variables expanded.""" if self.flavor == 'win': args = [self.msvs_settings.ConvertVSMacros( arg, self.base_to_build, config=self.config_name) for arg in args] description = self.msvs_settings.ConvertVSMacros( description, config=self.config_name) elif self.flavor == 'mac': # |env| is an empty list on non-mac. args = [gyp.xcode_emulation.ExpandEnvVars(arg, env) for arg in args] description = gyp.xcode_emulation.ExpandEnvVars(description, env) # TODO: we shouldn't need to qualify names; we do it because # currently the ninja rule namespace is global, but it really # should be scoped to the subninja. rule_name = self.name if self.toolset == 'target': rule_name += '.' + self.toolset rule_name += '.' + name rule_name = re.sub('[^a-zA-Z0-9_]', '_', rule_name) # Remove variable references, but not if they refer to the magic rule # variables. This is not quite right, as it also protects these for # actions, not just for rules where they are valid. Good enough. protect = [ '${root}', '${dirname}', '${source}', '${ext}', '${name}' ] protect = '(?!' + '|'.join(map(re.escape, protect)) + ')' description = re.sub(protect + r'\$', '_', description) # gyp dictates that commands are run from the base directory. # cd into the directory before running, and adjust paths in # the arguments to point to the proper locations. rspfile = None rspfile_content = None args = [self.ExpandSpecial(arg, self.base_to_build) for arg in args] if self.flavor == 'win': rspfile = rule_name + '.$unique_name.rsp' # The cygwin case handles this inside the bash sub-shell. run_in = '' if is_cygwin else ' ' + self.build_to_base if is_cygwin: rspfile_content = self.msvs_settings.BuildCygwinBashCommandLine( args, self.build_to_base) else: rspfile_content = gyp.msvs_emulation.EncodeRspFileList(args) command = ('%s gyp-win-tool action-wrapper $arch ' % sys.executable + rspfile + run_in) else: env = self.ComputeExportEnvString(env) command = gyp.common.EncodePOSIXShellList(args) command = 'cd %s; ' % self.build_to_base + env + command # GYP rules/actions express being no-ops by not touching their outputs. # Avoid executing downstream dependencies in this case by specifying # restat=1 to ninja. self.ninja.rule(rule_name, command, description, depfile=depfile, restat=True, pool=pool, rspfile=rspfile, rspfile_content=rspfile_content) self.ninja.newline() return rule_name, args
[ "def", "WriteNewNinjaRule", "(", "self", ",", "name", ",", "args", ",", "description", ",", "is_cygwin", ",", "env", ",", "pool", ",", "depfile", "=", "None", ")", ":", "if", "self", ".", "flavor", "==", "'win'", ":", "args", "=", "[", "self", ".", "msvs_settings", ".", "ConvertVSMacros", "(", "arg", ",", "self", ".", "base_to_build", ",", "config", "=", "self", ".", "config_name", ")", "for", "arg", "in", "args", "]", "description", "=", "self", ".", "msvs_settings", ".", "ConvertVSMacros", "(", "description", ",", "config", "=", "self", ".", "config_name", ")", "elif", "self", ".", "flavor", "==", "'mac'", ":", "# |env| is an empty list on non-mac.", "args", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "arg", ",", "env", ")", "for", "arg", "in", "args", "]", "description", "=", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "description", ",", "env", ")", "# TODO: we shouldn't need to qualify names; we do it because", "# currently the ninja rule namespace is global, but it really", "# should be scoped to the subninja.", "rule_name", "=", "self", ".", "name", "if", "self", ".", "toolset", "==", "'target'", ":", "rule_name", "+=", "'.'", "+", "self", ".", "toolset", "rule_name", "+=", "'.'", "+", "name", "rule_name", "=", "re", ".", "sub", "(", "'[^a-zA-Z0-9_]'", ",", "'_'", ",", "rule_name", ")", "# Remove variable references, but not if they refer to the magic rule", "# variables. This is not quite right, as it also protects these for", "# actions, not just for rules where they are valid. Good enough.", "protect", "=", "[", "'${root}'", ",", "'${dirname}'", ",", "'${source}'", ",", "'${ext}'", ",", "'${name}'", "]", "protect", "=", "'(?!'", "+", "'|'", ".", "join", "(", "map", "(", "re", ".", "escape", ",", "protect", ")", ")", "+", "')'", "description", "=", "re", ".", "sub", "(", "protect", "+", "r'\\$'", ",", "'_'", ",", "description", ")", "# gyp dictates that commands are run from the base directory.", "# cd into the directory before running, and adjust paths in", "# the arguments to point to the proper locations.", "rspfile", "=", "None", "rspfile_content", "=", "None", "args", "=", "[", "self", ".", "ExpandSpecial", "(", "arg", ",", "self", ".", "base_to_build", ")", "for", "arg", "in", "args", "]", "if", "self", ".", "flavor", "==", "'win'", ":", "rspfile", "=", "rule_name", "+", "'.$unique_name.rsp'", "# The cygwin case handles this inside the bash sub-shell.", "run_in", "=", "''", "if", "is_cygwin", "else", "' '", "+", "self", ".", "build_to_base", "if", "is_cygwin", ":", "rspfile_content", "=", "self", ".", "msvs_settings", ".", "BuildCygwinBashCommandLine", "(", "args", ",", "self", ".", "build_to_base", ")", "else", ":", "rspfile_content", "=", "gyp", ".", "msvs_emulation", ".", "EncodeRspFileList", "(", "args", ")", "command", "=", "(", "'%s gyp-win-tool action-wrapper $arch '", "%", "sys", ".", "executable", "+", "rspfile", "+", "run_in", ")", "else", ":", "env", "=", "self", ".", "ComputeExportEnvString", "(", "env", ")", "command", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "args", ")", "command", "=", "'cd %s; '", "%", "self", ".", "build_to_base", "+", "env", "+", "command", "# GYP rules/actions express being no-ops by not touching their outputs.", "# Avoid executing downstream dependencies in this case by specifying", "# restat=1 to ninja.", "self", ".", "ninja", ".", "rule", "(", "rule_name", ",", "command", ",", "description", ",", "depfile", "=", "depfile", ",", "restat", "=", "True", ",", "pool", "=", "pool", ",", "rspfile", "=", "rspfile", ",", "rspfile_content", "=", "rspfile_content", ")", "self", ".", "ninja", ".", "newline", "(", ")", "return", "rule_name", ",", "args" ]
[ 1526, 2 ]
[ 1590, 26 ]
python
en
['en', 'en', 'en']
True
test_anonymizer__is_parent_class_recognized
()
What does this test and why? The method Anonymizer._is_parent_class_recognized() should return the name of the parent class if it is or is a subclass of one of the classes_to_check. If not, it should return None. It should do so regardless of the parameter used to pass in the object definition (object_, object_class, object_config). It should also return the first matching class in classes_to_check, even if a later class also matches.
What does this test and why? The method Anonymizer._is_parent_class_recognized() should return the name of the parent class if it is or is a subclass of one of the classes_to_check. If not, it should return None. It should do so regardless of the parameter used to pass in the object definition (object_, object_class, object_config). It should also return the first matching class in classes_to_check, even if a later class also matches.
def test_anonymizer__is_parent_class_recognized(): """ What does this test and why? The method Anonymizer._is_parent_class_recognized() should return the name of the parent class if it is or is a subclass of one of the classes_to_check. If not, it should return None. It should do so regardless of the parameter used to pass in the object definition (object_, object_class, object_config). It should also return the first matching class in classes_to_check, even if a later class also matches. """ anonymizer = Anonymizer() # classes_to_check in order of inheritance hierarchy classes_to_check = [TestClass, BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_class=MyCustomTestClass ) == "TestClass" ) assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_class=SomeOtherClass ) is None ) classes_to_check = [BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_class=TestClass ) == "BaseTestClass" ) # classes_to_check in order of inheritance hierarchy my_custom_test_class = MyCustomTestClass() test_class = TestClass() some_other_class = SomeOtherClass() classes_to_check = [TestClass, BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_=my_custom_test_class ) == "TestClass" ) assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_=some_other_class ) is None ) classes_to_check = [BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_=test_class ) == "BaseTestClass" ) # classes_to_check in order of inheritance hierarchy my_custom_test_class_config = { "class_name": "MyCustomTestClass", "module_name": "tests.core.usage_statistics.test_anonymizer", } test_class_config = { "class_name": "TestClass", "module_name": "tests.core.usage_statistics.test_anonymizer", } some_other_class_config = { "class_name": "SomeOtherClass", "module_name": "tests.core.usage_statistics.test_anonymizer", } classes_to_check = [TestClass, BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_config=my_custom_test_class_config ) == "TestClass" ) assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_config=some_other_class_config ) is None ) classes_to_check = [BaseTestClass] assert ( anonymizer._is_parent_class_recognized( classes_to_check=classes_to_check, object_config=test_class_config ) == "BaseTestClass" )
[ "def", "test_anonymizer__is_parent_class_recognized", "(", ")", ":", "anonymizer", "=", "Anonymizer", "(", ")", "# classes_to_check in order of inheritance hierarchy", "classes_to_check", "=", "[", "TestClass", ",", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_class", "=", "MyCustomTestClass", ")", "==", "\"TestClass\"", ")", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_class", "=", "SomeOtherClass", ")", "is", "None", ")", "classes_to_check", "=", "[", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_class", "=", "TestClass", ")", "==", "\"BaseTestClass\"", ")", "# classes_to_check in order of inheritance hierarchy", "my_custom_test_class", "=", "MyCustomTestClass", "(", ")", "test_class", "=", "TestClass", "(", ")", "some_other_class", "=", "SomeOtherClass", "(", ")", "classes_to_check", "=", "[", "TestClass", ",", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_", "=", "my_custom_test_class", ")", "==", "\"TestClass\"", ")", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_", "=", "some_other_class", ")", "is", "None", ")", "classes_to_check", "=", "[", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_", "=", "test_class", ")", "==", "\"BaseTestClass\"", ")", "# classes_to_check in order of inheritance hierarchy", "my_custom_test_class_config", "=", "{", "\"class_name\"", ":", "\"MyCustomTestClass\"", ",", "\"module_name\"", ":", "\"tests.core.usage_statistics.test_anonymizer\"", ",", "}", "test_class_config", "=", "{", "\"class_name\"", ":", "\"TestClass\"", ",", "\"module_name\"", ":", "\"tests.core.usage_statistics.test_anonymizer\"", ",", "}", "some_other_class_config", "=", "{", "\"class_name\"", ":", "\"SomeOtherClass\"", ",", "\"module_name\"", ":", "\"tests.core.usage_statistics.test_anonymizer\"", ",", "}", "classes_to_check", "=", "[", "TestClass", ",", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_config", "=", "my_custom_test_class_config", ")", "==", "\"TestClass\"", ")", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_config", "=", "some_other_class_config", ")", "is", "None", ")", "classes_to_check", "=", "[", "BaseTestClass", "]", "assert", "(", "anonymizer", ".", "_is_parent_class_recognized", "(", "classes_to_check", "=", "classes_to_check", ",", "object_config", "=", "test_class_config", ")", "==", "\"BaseTestClass\"", ")" ]
[ 66, 0 ]
[ 152, 5 ]
python
en
['en', 'error', 'th']
False
build_docs
( context: DataContext, usage_stats_event: str, site_names: Optional[List[str]] = None, view: Optional[bool] = True, assume_yes: Optional[bool] = False, )
Build documentation in a context
Build documentation in a context
def build_docs( context: DataContext, usage_stats_event: str, site_names: Optional[List[str]] = None, view: Optional[bool] = True, assume_yes: Optional[bool] = False, ): """Build documentation in a context""" logger.debug("Starting cli.datasource.build_docs") index_page_locator_infos: Dict[str, str] = context.build_data_docs( site_names=site_names, dry_run=True ) msg: str = "\nThe following Data Docs sites will be built:\n\n" for site_name, index_page_locator_info in index_page_locator_infos.items(): msg += " - <cyan>{}:</cyan> ".format(site_name) msg += "{}\n".format(index_page_locator_info) cli_message(msg) if not assume_yes: toolkit.confirm_proceed_or_exit( data_context=context, usage_stats_event=usage_stats_event ) cli_message("\nBuilding Data Docs...\n") context.build_data_docs(site_names=site_names) cli_message("Done building Data Docs") if view and site_names: for site_to_open in site_names: context.open_data_docs(site_name=site_to_open, only_if_exists=True)
[ "def", "build_docs", "(", "context", ":", "DataContext", ",", "usage_stats_event", ":", "str", ",", "site_names", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "view", ":", "Optional", "[", "bool", "]", "=", "True", ",", "assume_yes", ":", "Optional", "[", "bool", "]", "=", "False", ",", ")", ":", "logger", ".", "debug", "(", "\"Starting cli.datasource.build_docs\"", ")", "index_page_locator_infos", ":", "Dict", "[", "str", ",", "str", "]", "=", "context", ".", "build_data_docs", "(", "site_names", "=", "site_names", ",", "dry_run", "=", "True", ")", "msg", ":", "str", "=", "\"\\nThe following Data Docs sites will be built:\\n\\n\"", "for", "site_name", ",", "index_page_locator_info", "in", "index_page_locator_infos", ".", "items", "(", ")", ":", "msg", "+=", "\" - <cyan>{}:</cyan> \"", ".", "format", "(", "site_name", ")", "msg", "+=", "\"{}\\n\"", ".", "format", "(", "index_page_locator_info", ")", "cli_message", "(", "msg", ")", "if", "not", "assume_yes", ":", "toolkit", ".", "confirm_proceed_or_exit", "(", "data_context", "=", "context", ",", "usage_stats_event", "=", "usage_stats_event", ")", "cli_message", "(", "\"\\nBuilding Data Docs...\\n\"", ")", "context", ".", "build_data_docs", "(", "site_names", "=", "site_names", ")", "cli_message", "(", "\"Done building Data Docs\"", ")", "if", "view", "and", "site_names", ":", "for", "site_to_open", "in", "site_names", ":", "context", ".", "open_data_docs", "(", "site_name", "=", "site_to_open", ",", "only_if_exists", "=", "True", ")" ]
[ 8, 0 ]
[ 40, 79 ]
python
en
['en', 'en', 'en']
True
ExpectColumnDistinctValuesToContainSet.validate_configuration
(self, configuration: Optional[ExpectationConfiguration])
Validating that user has inputted a value set and that configuration has been initialized
Validating that user has inputted a value set and that configuration has been initialized
def validate_configuration(self, configuration: Optional[ExpectationConfiguration]): """Validating that user has inputted a value set and that configuration has been initialized""" super().validate_configuration(configuration) try: assert "value_set" in configuration.kwargs, "value_set is required" assert isinstance( configuration.kwargs["value_set"], (list, set, dict) ), "value_set must be a list or a set" if isinstance(configuration.kwargs["value_set"], dict): assert ( "$PARAMETER" in configuration.kwargs["value_set"] ), 'Evaluation Parameter dict for value_set kwarg must have "$PARAMETER" key' except AssertionError as e: raise InvalidExpectationConfigurationError(str(e)) return True
[ "def", "validate_configuration", "(", "self", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", ")", ":", "super", "(", ")", ".", "validate_configuration", "(", "configuration", ")", "try", ":", "assert", "\"value_set\"", "in", "configuration", ".", "kwargs", ",", "\"value_set is required\"", "assert", "isinstance", "(", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ",", "(", "list", ",", "set", ",", "dict", ")", ")", ",", "\"value_set must be a list or a set\"", "if", "isinstance", "(", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ",", "dict", ")", ":", "assert", "(", "\"$PARAMETER\"", "in", "configuration", ".", "kwargs", "[", "\"value_set\"", "]", ")", ",", "'Evaluation Parameter dict for value_set kwarg must have \"$PARAMETER\" key'", "except", "AssertionError", "as", "e", ":", "raise", "InvalidExpectationConfigurationError", "(", "str", "(", "e", ")", ")", "return", "True" ]
[ 47, 4 ]
[ 62, 19 ]
python
en
['en', 'en', 'en']
True
_AddTool
(tool)
Adds a tool to the four dictionaries used to process settings. This only defines the tool. Each setting also needs to be added. Args: tool: The _Tool object to be added.
Adds a tool to the four dictionaries used to process settings.
def _AddTool(tool): """Adds a tool to the four dictionaries used to process settings. This only defines the tool. Each setting also needs to be added. Args: tool: The _Tool object to be added. """ _msvs_validators[tool.msvs_name] = {} _msbuild_validators[tool.msbuild_name] = {} _msvs_to_msbuild_converters[tool.msvs_name] = {} _msbuild_name_of_tool[tool.msvs_name] = tool.msbuild_name
[ "def", "_AddTool", "(", "tool", ")", ":", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "=", "{", "}", "_msbuild_validators", "[", "tool", ".", "msbuild_name", "]", "=", "{", "}", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "=", "{", "}", "_msbuild_name_of_tool", "[", "tool", ".", "msvs_name", "]", "=", "tool", ".", "msbuild_name" ]
[ 47, 0 ]
[ 58, 59 ]
python
en
['en', 'en', 'en']
True
_GetMSBuildToolSettings
(msbuild_settings, tool)
Returns an MSBuild tool dictionary. Creates it if needed.
Returns an MSBuild tool dictionary. Creates it if needed.
def _GetMSBuildToolSettings(msbuild_settings, tool): """Returns an MSBuild tool dictionary. Creates it if needed.""" return msbuild_settings.setdefault(tool.msbuild_name, {})
[ "def", "_GetMSBuildToolSettings", "(", "msbuild_settings", ",", "tool", ")", ":", "return", "msbuild_settings", ".", "setdefault", "(", "tool", ".", "msbuild_name", ",", "{", "}", ")" ]
[ 61, 0 ]
[ 63, 59 ]
python
en
['en', 'en', 'en']
True
_Same
(tool, name, setting_type)
Defines a setting that has the same name in MSVS and MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that has the same name in MSVS and MSBuild.
def _Same(tool, name, setting_type): """Defines a setting that has the same name in MSVS and MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ _Renamed(tool, name, name, setting_type)
[ "def", "_Same", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "_Renamed", "(", "tool", ",", "name", ",", "name", ",", "setting_type", ")" ]
[ 232, 0 ]
[ 240, 42 ]
python
en
['en', 'en', 'en']
True
_Renamed
(tool, msvs_name, msbuild_name, setting_type)
Defines a setting for which the name has changed. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting. msbuild_name: the name of the MSBuild setting. setting_type: the type of this setting.
Defines a setting for which the name has changed.
def _Renamed(tool, msvs_name, msbuild_name, setting_type): """Defines a setting for which the name has changed. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting. msbuild_name: the name of the MSBuild setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): msbuild_tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) msbuild_tool_settings[msbuild_name] = setting_type.ConvertToMSBuild(value) _msvs_validators[tool.msvs_name][msvs_name] = setting_type.ValidateMSVS _msbuild_validators[tool.msbuild_name][msbuild_name] = ( setting_type.ValidateMSBuild) _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate
[ "def", "_Renamed", "(", "tool", ",", "msvs_name", ",", "msbuild_name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "msbuild_tool_settings", "=", "_GetMSBuildToolSettings", "(", "msbuild_settings", ",", "tool", ")", "msbuild_tool_settings", "[", "msbuild_name", "]", "=", "setting_type", ".", "ConvertToMSBuild", "(", "value", ")", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "msvs_name", "]", "=", "setting_type", ".", "ValidateMSVS", "_msbuild_validators", "[", "tool", ".", "msbuild_name", "]", "[", "msbuild_name", "]", "=", "(", "setting_type", ".", "ValidateMSBuild", ")", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "msvs_name", "]", "=", "_Translate" ]
[ 243, 0 ]
[ 260, 69 ]
python
en
['en', 'en', 'en']
True
_MovedAndRenamed
(tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type)
Defines a setting that may have moved to a new section. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_settings_name: the MSVS name of the setting. msbuild_tool_name: the name of the MSBuild tool to place the setting under. msbuild_settings_name: the MSBuild name of the setting. setting_type: the type of this setting.
Defines a setting that may have moved to a new section.
def _MovedAndRenamed(tool, msvs_settings_name, msbuild_tool_name, msbuild_settings_name, setting_type): """Defines a setting that may have moved to a new section. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_settings_name: the MSVS name of the setting. msbuild_tool_name: the name of the MSBuild tool to place the setting under. msbuild_settings_name: the MSBuild name of the setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): tool_settings = msbuild_settings.setdefault(msbuild_tool_name, {}) tool_settings[msbuild_settings_name] = setting_type.ConvertToMSBuild(value) _msvs_validators[tool.msvs_name][msvs_settings_name] = ( setting_type.ValidateMSVS) validator = setting_type.ValidateMSBuild _msbuild_validators[msbuild_tool_name][msbuild_settings_name] = validator _msvs_to_msbuild_converters[tool.msvs_name][msvs_settings_name] = _Translate
[ "def", "_MovedAndRenamed", "(", "tool", ",", "msvs_settings_name", ",", "msbuild_tool_name", ",", "msbuild_settings_name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "tool_settings", "=", "msbuild_settings", ".", "setdefault", "(", "msbuild_tool_name", ",", "{", "}", ")", "tool_settings", "[", "msbuild_settings_name", "]", "=", "setting_type", ".", "ConvertToMSBuild", "(", "value", ")", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "msvs_settings_name", "]", "=", "(", "setting_type", ".", "ValidateMSVS", ")", "validator", "=", "setting_type", ".", "ValidateMSBuild", "_msbuild_validators", "[", "msbuild_tool_name", "]", "[", "msbuild_settings_name", "]", "=", "validator", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "msvs_settings_name", "]", "=", "_Translate" ]
[ 268, 0 ]
[ 288, 78 ]
python
en
['en', 'en', 'en']
True
_MSVSOnly
(tool, name, setting_type)
Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that is only found in MSVS.
def _MSVSOnly(tool, name, setting_type): """Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(unused_value, unused_msbuild_settings): # Since this is for MSVS only settings, no translation will happen. pass _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
[ "def", "_MSVSOnly", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "unused_value", ",", "unused_msbuild_settings", ")", ":", "# Since this is for MSVS only settings, no translation will happen.", "pass", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "name", "]", "=", "setting_type", ".", "ValidateMSVS", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "name", "]", "=", "_Translate" ]
[ 291, 0 ]
[ 305, 64 ]
python
en
['en', 'en', 'en']
True
_MSBuildOnly
(tool, name, setting_type)
Defines a setting that is only found in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that is only found in MSBuild.
def _MSBuildOnly(tool, name, setting_type): """Defines a setting that is only found in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(value, msbuild_settings): # Let msbuild-only properties get translated as-is from msvs_settings. tool_settings = msbuild_settings.setdefault(tool.msbuild_name, {}) tool_settings[name] = value _msbuild_validators[tool.msbuild_name][name] = setting_type.ValidateMSBuild _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
[ "def", "_MSBuildOnly", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "# Let msbuild-only properties get translated as-is from msvs_settings.", "tool_settings", "=", "msbuild_settings", ".", "setdefault", "(", "tool", ".", "msbuild_name", ",", "{", "}", ")", "tool_settings", "[", "name", "]", "=", "value", "_msbuild_validators", "[", "tool", ".", "msbuild_name", "]", "[", "name", "]", "=", "setting_type", ".", "ValidateMSBuild", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "name", "]", "=", "_Translate" ]
[ 308, 0 ]
[ 323, 64 ]
python
en
['en', 'en', 'en']
True
_ConvertedToAdditionalOption
(tool, msvs_name, flag)
Defines a setting that's handled via a command line option in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting that if 'true' becomes a flag flag: the flag to insert at the end of the AdditionalOptions
Defines a setting that's handled via a command line option in MSBuild.
def _ConvertedToAdditionalOption(tool, msvs_name, flag): """Defines a setting that's handled via a command line option in MSBuild. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. msvs_name: the name of the MSVS setting that if 'true' becomes a flag flag: the flag to insert at the end of the AdditionalOptions """ def _Translate(value, msbuild_settings): if value == 'true': tool_settings = _GetMSBuildToolSettings(msbuild_settings, tool) if 'AdditionalOptions' in tool_settings: new_flags = '%s %s' % (tool_settings['AdditionalOptions'], flag) else: new_flags = flag tool_settings['AdditionalOptions'] = new_flags _msvs_validators[tool.msvs_name][msvs_name] = _boolean.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][msvs_name] = _Translate
[ "def", "_ConvertedToAdditionalOption", "(", "tool", ",", "msvs_name", ",", "flag", ")", ":", "def", "_Translate", "(", "value", ",", "msbuild_settings", ")", ":", "if", "value", "==", "'true'", ":", "tool_settings", "=", "_GetMSBuildToolSettings", "(", "msbuild_settings", ",", "tool", ")", "if", "'AdditionalOptions'", "in", "tool_settings", ":", "new_flags", "=", "'%s %s'", "%", "(", "tool_settings", "[", "'AdditionalOptions'", "]", ",", "flag", ")", "else", ":", "new_flags", "=", "flag", "tool_settings", "[", "'AdditionalOptions'", "]", "=", "new_flags", "_msvs_validators", "[", "tool", ".", "msvs_name", "]", "[", "msvs_name", "]", "=", "_boolean", ".", "ValidateMSVS", "_msvs_to_msbuild_converters", "[", "tool", ".", "msvs_name", "]", "[", "msvs_name", "]", "=", "_Translate" ]
[ 326, 0 ]
[ 344, 69 ]
python
en
['en', 'en', 'en']
True
_ValidateExclusionSetting
(setting, settings, error_msg, stderr=sys.stderr)
Verify that 'setting' is valid if it is generated from an exclusion list. If the setting appears to be generated from an exclusion list, the root name is checked. Args: setting: A string that is the setting name to validate settings: A dictionary where the keys are valid settings error_msg: The message to emit in the event of error stderr: The stream receiving the error messages.
Verify that 'setting' is valid if it is generated from an exclusion list.
def _ValidateExclusionSetting(setting, settings, error_msg, stderr=sys.stderr): """Verify that 'setting' is valid if it is generated from an exclusion list. If the setting appears to be generated from an exclusion list, the root name is checked. Args: setting: A string that is the setting name to validate settings: A dictionary where the keys are valid settings error_msg: The message to emit in the event of error stderr: The stream receiving the error messages. """ # This may be unrecognized because it's an exclusion list. If the # setting name has the _excluded suffix, then check the root name. unrecognized = True m = re.match(_EXCLUDED_SUFFIX_RE, setting) if m: root_setting = m.group(1) unrecognized = root_setting not in settings if unrecognized: # We don't know this setting. Give a warning. print >> stderr, error_msg
[ "def", "_ValidateExclusionSetting", "(", "setting", ",", "settings", ",", "error_msg", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "# This may be unrecognized because it's an exclusion list. If the", "# setting name has the _excluded suffix, then check the root name.", "unrecognized", "=", "True", "m", "=", "re", ".", "match", "(", "_EXCLUDED_SUFFIX_RE", ",", "setting", ")", "if", "m", ":", "root_setting", "=", "m", ".", "group", "(", "1", ")", "unrecognized", "=", "root_setting", "not", "in", "settings", "if", "unrecognized", ":", "# We don't know this setting. Give a warning.", "print", ">>", "stderr", ",", "error_msg" ]
[ 380, 0 ]
[ 402, 30 ]
python
en
['en', 'en', 'en']
True
FixVCMacroSlashes
(s)
Replace macros which have excessive following slashes. These macros are known to have a built-in trailing slash. Furthermore, many scripts hiccup on processing paths with extra slashes in the middle. This list is probably not exhaustive. Add as needed.
Replace macros which have excessive following slashes.
def FixVCMacroSlashes(s): """Replace macros which have excessive following slashes. These macros are known to have a built-in trailing slash. Furthermore, many scripts hiccup on processing paths with extra slashes in the middle. This list is probably not exhaustive. Add as needed. """ if '$' in s: s = fix_vc_macro_slashes_regex.sub(r'\1', s) return s
[ "def", "FixVCMacroSlashes", "(", "s", ")", ":", "if", "'$'", "in", "s", ":", "s", "=", "fix_vc_macro_slashes_regex", ".", "sub", "(", "r'\\1'", ",", "s", ")", "return", "s" ]
[ 405, 0 ]
[ 415, 10 ]
python
en
['en', 'en', 'en']
True
ConvertVCMacrosToMSBuild
(s)
Convert the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed.
Convert the MSVS macros found in the string to the MSBuild equivalent.
def ConvertVCMacrosToMSBuild(s): """Convert the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed. """ if '$' in s: replace_map = { '$(ConfigurationName)': '$(Configuration)', '$(InputDir)': '%(RelativeDir)', '$(InputExt)': '%(Extension)', '$(InputFileName)': '%(Filename)%(Extension)', '$(InputName)': '%(Filename)', '$(InputPath)': '%(Identity)', '$(ParentName)': '$(ProjectFileName)', '$(PlatformName)': '$(Platform)', '$(SafeInputName)': '%(Filename)', } for old, new in replace_map.iteritems(): s = s.replace(old, new) s = FixVCMacroSlashes(s) return s
[ "def", "ConvertVCMacrosToMSBuild", "(", "s", ")", ":", "if", "'$'", "in", "s", ":", "replace_map", "=", "{", "'$(ConfigurationName)'", ":", "'$(Configuration)'", ",", "'$(InputDir)'", ":", "'%(RelativeDir)'", ",", "'$(InputExt)'", ":", "'%(Extension)'", ",", "'$(InputFileName)'", ":", "'%(Filename)%(Extension)'", ",", "'$(InputName)'", ":", "'%(Filename)'", ",", "'$(InputPath)'", ":", "'%(Identity)'", ",", "'$(ParentName)'", ":", "'$(ProjectFileName)'", ",", "'$(PlatformName)'", ":", "'$(Platform)'", ",", "'$(SafeInputName)'", ":", "'%(Filename)'", ",", "}", "for", "old", ",", "new", "in", "replace_map", ".", "iteritems", "(", ")", ":", "s", "=", "s", ".", "replace", "(", "old", ",", "new", ")", "s", "=", "FixVCMacroSlashes", "(", "s", ")", "return", "s" ]
[ 418, 0 ]
[ 438, 10 ]
python
en
['en', 'en', 'en']
True
ConvertToMSBuildSettings
(msvs_settings, stderr=sys.stderr)
Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+). Args: msvs_settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. Returns: A dictionary of MSBuild settings. The key is either the MSBuild tool name or the empty string (for the global settings). The values are themselves dictionaries of settings and their values.
Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+).
def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): """Converts MSVS settings (VS2008 and earlier) to MSBuild settings (VS2010+). Args: msvs_settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. Returns: A dictionary of MSBuild settings. The key is either the MSBuild tool name or the empty string (for the global settings). The values are themselves dictionaries of settings and their values. """ msbuild_settings = {} for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems(): if msvs_tool_name in _msvs_to_msbuild_converters: msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name] for msvs_setting, msvs_value in msvs_tool_settings.iteritems(): if msvs_setting in msvs_tool: # Invoke the translation function. try: msvs_tool[msvs_setting](msvs_value, msbuild_settings) except ValueError, e: print >> stderr, ('Warning: while converting %s/%s to MSBuild, ' '%s' % (msvs_tool_name, msvs_setting, e)) else: _ValidateExclusionSetting(msvs_setting, msvs_tool, ('Warning: unrecognized setting %s/%s ' 'while converting to MSBuild.' % (msvs_tool_name, msvs_setting)), stderr) else: print >> stderr, ('Warning: unrecognized tool %s while converting to ' 'MSBuild.' % msvs_tool_name) return msbuild_settings
[ "def", "ConvertToMSBuildSettings", "(", "msvs_settings", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "msbuild_settings", "=", "{", "}", "for", "msvs_tool_name", ",", "msvs_tool_settings", "in", "msvs_settings", ".", "iteritems", "(", ")", ":", "if", "msvs_tool_name", "in", "_msvs_to_msbuild_converters", ":", "msvs_tool", "=", "_msvs_to_msbuild_converters", "[", "msvs_tool_name", "]", "for", "msvs_setting", ",", "msvs_value", "in", "msvs_tool_settings", ".", "iteritems", "(", ")", ":", "if", "msvs_setting", "in", "msvs_tool", ":", "# Invoke the translation function.", "try", ":", "msvs_tool", "[", "msvs_setting", "]", "(", "msvs_value", ",", "msbuild_settings", ")", "except", "ValueError", ",", "e", ":", "print", ">>", "stderr", ",", "(", "'Warning: while converting %s/%s to MSBuild, '", "'%s'", "%", "(", "msvs_tool_name", ",", "msvs_setting", ",", "e", ")", ")", "else", ":", "_ValidateExclusionSetting", "(", "msvs_setting", ",", "msvs_tool", ",", "(", "'Warning: unrecognized setting %s/%s '", "'while converting to MSBuild.'", "%", "(", "msvs_tool_name", ",", "msvs_setting", ")", ")", ",", "stderr", ")", "else", ":", "print", ">>", "stderr", ",", "(", "'Warning: unrecognized tool %s while converting to '", "'MSBuild.'", "%", "msvs_tool_name", ")", "return", "msbuild_settings" ]
[ 441, 0 ]
[ 476, 25 ]
python
en
['en', 'en', 'en']
True
ValidateMSVSSettings
(settings, stderr=sys.stderr)
Validates that the names of the settings are valid for MSVS. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages.
Validates that the names of the settings are valid for MSVS.
def ValidateMSVSSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSVS. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msvs_validators, settings, stderr)
[ "def", "ValidateMSVSSettings", "(", "settings", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "_ValidateSettings", "(", "_msvs_validators", ",", "settings", ",", "stderr", ")" ]
[ 479, 0 ]
[ 487, 55 ]
python
en
['en', 'en', 'en']
True
ValidateMSBuildSettings
(settings, stderr=sys.stderr)
Validates that the names of the settings are valid for MSBuild. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages.
Validates that the names of the settings are valid for MSBuild.
def ValidateMSBuildSettings(settings, stderr=sys.stderr): """Validates that the names of the settings are valid for MSBuild. Args: settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ _ValidateSettings(_msbuild_validators, settings, stderr)
[ "def", "ValidateMSBuildSettings", "(", "settings", ",", "stderr", "=", "sys", ".", "stderr", ")", ":", "_ValidateSettings", "(", "_msbuild_validators", ",", "settings", ",", "stderr", ")" ]
[ 490, 0 ]
[ 498, 58 ]
python
en
['en', 'en', 'en']
True
_ValidateSettings
(validators, settings, stderr)
Validates that the settings are valid for MSBuild or MSVS. We currently only validate the names of the settings, not their values. Args: validators: A dictionary of tools and their validators. settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages.
Validates that the settings are valid for MSBuild or MSVS.
def _ValidateSettings(validators, settings, stderr): """Validates that the settings are valid for MSBuild or MSVS. We currently only validate the names of the settings, not their values. Args: validators: A dictionary of tools and their validators. settings: A dictionary. The key is the tool name. The values are themselves dictionaries of settings and their values. stderr: The stream receiving the error messages. """ for tool_name in settings: if tool_name in validators: tool_validators = validators[tool_name] for setting, value in settings[tool_name].iteritems(): if setting in tool_validators: try: tool_validators[setting](value) except ValueError, e: print >> stderr, ('Warning: for %s/%s, %s' % (tool_name, setting, e)) else: _ValidateExclusionSetting(setting, tool_validators, ('Warning: unrecognized setting %s/%s' % (tool_name, setting)), stderr) else: print >> stderr, ('Warning: unrecognized tool %s' % tool_name)
[ "def", "_ValidateSettings", "(", "validators", ",", "settings", ",", "stderr", ")", ":", "for", "tool_name", "in", "settings", ":", "if", "tool_name", "in", "validators", ":", "tool_validators", "=", "validators", "[", "tool_name", "]", "for", "setting", ",", "value", "in", "settings", "[", "tool_name", "]", ".", "iteritems", "(", ")", ":", "if", "setting", "in", "tool_validators", ":", "try", ":", "tool_validators", "[", "setting", "]", "(", "value", ")", "except", "ValueError", ",", "e", ":", "print", ">>", "stderr", ",", "(", "'Warning: for %s/%s, %s'", "%", "(", "tool_name", ",", "setting", ",", "e", ")", ")", "else", ":", "_ValidateExclusionSetting", "(", "setting", ",", "tool_validators", ",", "(", "'Warning: unrecognized setting %s/%s'", "%", "(", "tool_name", ",", "setting", ")", ")", ",", "stderr", ")", "else", ":", "print", ">>", "stderr", ",", "(", "'Warning: unrecognized tool %s'", "%", "tool_name", ")" ]
[ 501, 0 ]
[ 530, 68 ]
python
en
['en', 'en', 'en']
True
_Type.ValidateMSVS
(self, value)
Verifies that the value is legal for MSVS. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSVS.
Verifies that the value is legal for MSVS.
def ValidateMSVS(self, value): """Verifies that the value is legal for MSVS. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSVS. """
[ "def", "ValidateMSVS", "(", "self", ",", "value", ")", ":" ]
[ 69, 2 ]
[ 77, 7 ]
python
en
['en', 'en', 'en']
True
_Type.ValidateMSBuild
(self, value)
Verifies that the value is legal for MSBuild. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSBuild.
Verifies that the value is legal for MSBuild.
def ValidateMSBuild(self, value): """Verifies that the value is legal for MSBuild. Args: value: the value to check for this type. Raises: ValueError if value is not valid for MSBuild. """
[ "def", "ValidateMSBuild", "(", "self", ",", "value", ")", ":" ]
[ 79, 2 ]
[ 87, 7 ]
python
en
['en', 'en', 'en']
True
_Type.ConvertToMSBuild
(self, value)
Returns the MSBuild equivalent of the MSVS value given. Args: value: the MSVS value to convert. Returns: the MSBuild equivalent. Raises: ValueError if value is not valid.
Returns the MSBuild equivalent of the MSVS value given.
def ConvertToMSBuild(self, value): """Returns the MSBuild equivalent of the MSVS value given. Args: value: the MSVS value to convert. Returns: the MSBuild equivalent. Raises: ValueError if value is not valid. """ return value
[ "def", "ConvertToMSBuild", "(", "self", ",", "value", ")", ":", "return", "value" ]
[ 89, 2 ]
[ 101, 16 ]
python
en
['en', 'en', 'en']
True
Azure.default_function_name
(self, code_package: Benchmark)
Functionapp names must be globally unique in Azure.
Functionapp names must be globally unique in Azure.
def default_function_name(self, code_package: Benchmark) -> str: """ Functionapp names must be globally unique in Azure. """ func_name = ( "{}-{}-{}".format( code_package.benchmark, code_package.language_name, self.config.resources_id, ) .replace(".", "-") .replace("_", "-") ) return func_name
[ "def", "default_function_name", "(", "self", ",", "code_package", ":", "Benchmark", ")", "->", "str", ":", "func_name", "=", "(", "\"{}-{}-{}\"", ".", "format", "(", "code_package", ".", "benchmark", ",", "code_package", ".", "language_name", ",", "self", ".", "config", ".", "resources_id", ",", ")", ".", "replace", "(", "\".\"", ",", "\"-\"", ")", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ")", "return", "func_name" ]
[ 239, 4 ]
[ 250, 24 ]
python
en
['en', 'error', 'th']
False
IRAmbassador.handle_ip_allow_deny
(self, allow: bool, principals: List[str])
Handle IP Allow/Deny. "allow" here states whether this is an allow rule (True) or a deny rule (False); "principals" is a list of IP addresses or CIDR ranges to allow or deny. Only one of ip_allow or ip_deny can be set, so it's an error to call this twice (even if "allow" is the same for both calls). :param allow: True for an ALLOW rule, False for a DENY rule :param principals: list of IP addresses or CIDR ranges to match
Handle IP Allow/Deny. "allow" here states whether this is an allow rule (True) or a deny rule (False); "principals" is a list of IP addresses or CIDR ranges to allow or deny.
def handle_ip_allow_deny(self, allow: bool, principals: List[str]) -> None: """ Handle IP Allow/Deny. "allow" here states whether this is an allow rule (True) or a deny rule (False); "principals" is a list of IP addresses or CIDR ranges to allow or deny. Only one of ip_allow or ip_deny can be set, so it's an error to call this twice (even if "allow" is the same for both calls). :param allow: True for an ALLOW rule, False for a DENY rule :param principals: list of IP addresses or CIDR ranges to match """ if self.get('ip_allow_deny') is not None: self.post_error("ip_allow and ip_deny may not both be set") return ipa = IRIPAllowDeny(self.ir, self.ir.aconf, rkey=self.rkey, parent=self, action="ALLOW" if allow else "DENY", principals=principals) if ipa: self['ip_allow_deny'] = ipa
[ "def", "handle_ip_allow_deny", "(", "self", ",", "allow", ":", "bool", ",", "principals", ":", "List", "[", "str", "]", ")", "->", "None", ":", "if", "self", ".", "get", "(", "'ip_allow_deny'", ")", "is", "not", "None", ":", "self", ".", "post_error", "(", "\"ip_allow and ip_deny may not both be set\"", ")", "return", "ipa", "=", "IRIPAllowDeny", "(", "self", ".", "ir", ",", "self", ".", "ir", ".", "aconf", ",", "rkey", "=", "self", ".", "rkey", ",", "parent", "=", "self", ",", "action", "=", "\"ALLOW\"", "if", "allow", "else", "\"DENY\"", ",", "principals", "=", "principals", ")", "if", "ipa", ":", "self", "[", "'ip_allow_deny'", "]", "=", "ipa" ]
[ 459, 4 ]
[ 482, 39 ]
python
en
['en', 'error', 'th']
False
TrioToken.run_sync_soon
(self, sync_fn, *args, idempotent=False)
Schedule a call to ``sync_fn(*args)`` to occur in the context of a Trio task. This is safe to call from the main thread, from other threads, and from signal handlers. This is the fundamental primitive used to re-enter the Trio run loop from outside of it. The call will happen "soon", but there's no guarantee about exactly when, and no mechanism provided for finding out when it's happened. If you need this, you'll have to build your own. The call is effectively run as part of a system task (see :func:`~trio.lowlevel.spawn_system_task`). In particular this means that: * :exc:`KeyboardInterrupt` protection is *enabled* by default; if you want ``sync_fn`` to be interruptible by control-C, then you need to use :func:`~trio.lowlevel.disable_ki_protection` explicitly. * If ``sync_fn`` raises an exception, then it's converted into a :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. You should be careful that ``sync_fn`` doesn't crash. All calls with ``idempotent=False`` are processed in strict first-in first-out order. If ``idempotent=True``, then ``sync_fn`` and ``args`` must be hashable, and Trio will make a best-effort attempt to discard any call submission which is equal to an already-pending call. Trio will process these in first-in first-out order. Any ordering guarantees apply separately to ``idempotent=False`` and ``idempotent=True`` calls; there's no rule for how calls in the different categories are ordered with respect to each other. :raises trio.RunFinishedError: if the associated call to :func:`trio.run` has already exited. (Any call that *doesn't* raise this error is guaranteed to be fully processed before :func:`trio.run` exits.)
Schedule a call to ``sync_fn(*args)`` to occur in the context of a Trio task.
def run_sync_soon(self, sync_fn, *args, idempotent=False): """Schedule a call to ``sync_fn(*args)`` to occur in the context of a Trio task. This is safe to call from the main thread, from other threads, and from signal handlers. This is the fundamental primitive used to re-enter the Trio run loop from outside of it. The call will happen "soon", but there's no guarantee about exactly when, and no mechanism provided for finding out when it's happened. If you need this, you'll have to build your own. The call is effectively run as part of a system task (see :func:`~trio.lowlevel.spawn_system_task`). In particular this means that: * :exc:`KeyboardInterrupt` protection is *enabled* by default; if you want ``sync_fn`` to be interruptible by control-C, then you need to use :func:`~trio.lowlevel.disable_ki_protection` explicitly. * If ``sync_fn`` raises an exception, then it's converted into a :exc:`~trio.TrioInternalError` and *all* tasks are cancelled. You should be careful that ``sync_fn`` doesn't crash. All calls with ``idempotent=False`` are processed in strict first-in first-out order. If ``idempotent=True``, then ``sync_fn`` and ``args`` must be hashable, and Trio will make a best-effort attempt to discard any call submission which is equal to an already-pending call. Trio will process these in first-in first-out order. Any ordering guarantees apply separately to ``idempotent=False`` and ``idempotent=True`` calls; there's no rule for how calls in the different categories are ordered with respect to each other. :raises trio.RunFinishedError: if the associated call to :func:`trio.run` has already exited. (Any call that *doesn't* raise this error is guaranteed to be fully processed before :func:`trio.run` exits.) """ self._reentry_queue.run_sync_soon(sync_fn, *args, idempotent=idempotent)
[ "def", "run_sync_soon", "(", "self", ",", "sync_fn", ",", "*", "args", ",", "idempotent", "=", "False", ")", ":", "self", ".", "_reentry_queue", ".", "run_sync_soon", "(", "sync_fn", ",", "*", "args", ",", "idempotent", "=", "idempotent", ")" ]
[ 152, 4 ]
[ 196, 80 ]
python
en
['en', 'en', 'en']
True
RAGenerator.__init__
( self, model_name_or_path: str = "facebook/rag-token-nq", model_version: Optional[str] = None, retriever: Optional[DensePassageRetriever] = None, generator_type: RAGeneratorType = RAGeneratorType.TOKEN, top_k_answers: int = 2, max_length: int = 200, min_length: int = 2, num_beams: int = 2, embed_title: bool = True, prefix: Optional[str] = None, use_gpu: bool = True, )
Load a RAG model from Transformers along with passage_embedding_model. See https://huggingface.co/transformers/model_doc/rag.html for more details :param model_name_or_path: Directory of a saved model or the name of a public model e.g. 'facebook/rag-token-nq', 'facebook/rag-sequence-nq'. See https://huggingface.co/models for full list of available models. :param model_version: The version of model to use from the HuggingFace model hub. Can be tag name, branch name, or commit hash. :param retriever: `DensePassageRetriever` used to embedded passage :param generator_type: Which RAG generator implementation to use? RAG-TOKEN or RAG-SEQUENCE :param top_k_answers: Number of independently generated text to return :param max_length: Maximum length of generated text :param min_length: Minimum length of generated text :param num_beams: Number of beams for beam search. 1 means no beam search. :param embed_title: Embedded the title of passage while generating embedding :param prefix: The prefix used by the generator's tokenizer. :param use_gpu: Whether to use GPU (if available)
Load a RAG model from Transformers along with passage_embedding_model. See https://huggingface.co/transformers/model_doc/rag.html for more details
def __init__( self, model_name_or_path: str = "facebook/rag-token-nq", model_version: Optional[str] = None, retriever: Optional[DensePassageRetriever] = None, generator_type: RAGeneratorType = RAGeneratorType.TOKEN, top_k_answers: int = 2, max_length: int = 200, min_length: int = 2, num_beams: int = 2, embed_title: bool = True, prefix: Optional[str] = None, use_gpu: bool = True, ): """ Load a RAG model from Transformers along with passage_embedding_model. See https://huggingface.co/transformers/model_doc/rag.html for more details :param model_name_or_path: Directory of a saved model or the name of a public model e.g. 'facebook/rag-token-nq', 'facebook/rag-sequence-nq'. See https://huggingface.co/models for full list of available models. :param model_version: The version of model to use from the HuggingFace model hub. Can be tag name, branch name, or commit hash. :param retriever: `DensePassageRetriever` used to embedded passage :param generator_type: Which RAG generator implementation to use? RAG-TOKEN or RAG-SEQUENCE :param top_k_answers: Number of independently generated text to return :param max_length: Maximum length of generated text :param min_length: Minimum length of generated text :param num_beams: Number of beams for beam search. 1 means no beam search. :param embed_title: Embedded the title of passage while generating embedding :param prefix: The prefix used by the generator's tokenizer. :param use_gpu: Whether to use GPU (if available) """ self.model_name_or_path = model_name_or_path self.max_length = max_length self.min_length = min_length self.generator_type = generator_type self.num_beams = num_beams self.embed_title = embed_title self.prefix = prefix self.retriever = retriever if top_k_answers > self.num_beams: top_k_answers = self.num_beams logger.warning(f'top_k_answers value should not be greater than num_beams, hence setting it to {num_beams}') self.top_k_answers = top_k_answers if use_gpu and torch.cuda.is_available(): self.device = torch.device("cuda") else: self.device = torch.device("cpu") self.tokenizer = RagTokenizer.from_pretrained(model_name_or_path) if self.generator_type == RAGeneratorType.SEQUENCE: raise NotImplementedError("RagSequenceForGeneration is not implemented yet") # TODO: Enable when transformers have it. Refer https://github.com/huggingface/transformers/issues/7905 # Also refer refer https://github.com/huggingface/transformers/issues/7829 # self.model = RagSequenceForGeneration.from_pretrained(model_name_or_path) else: self.model = RagTokenForGeneration.from_pretrained(model_name_or_path, revision=model_version).to(self.device)
[ "def", "__init__", "(", "self", ",", "model_name_or_path", ":", "str", "=", "\"facebook/rag-token-nq\"", ",", "model_version", ":", "Optional", "[", "str", "]", "=", "None", ",", "retriever", ":", "Optional", "[", "DensePassageRetriever", "]", "=", "None", ",", "generator_type", ":", "RAGeneratorType", "=", "RAGeneratorType", ".", "TOKEN", ",", "top_k_answers", ":", "int", "=", "2", ",", "max_length", ":", "int", "=", "200", ",", "min_length", ":", "int", "=", "2", ",", "num_beams", ":", "int", "=", "2", ",", "embed_title", ":", "bool", "=", "True", ",", "prefix", ":", "Optional", "[", "str", "]", "=", "None", ",", "use_gpu", ":", "bool", "=", "True", ",", ")", ":", "self", ".", "model_name_or_path", "=", "model_name_or_path", "self", ".", "max_length", "=", "max_length", "self", ".", "min_length", "=", "min_length", "self", ".", "generator_type", "=", "generator_type", "self", ".", "num_beams", "=", "num_beams", "self", ".", "embed_title", "=", "embed_title", "self", ".", "prefix", "=", "prefix", "self", ".", "retriever", "=", "retriever", "if", "top_k_answers", ">", "self", ".", "num_beams", ":", "top_k_answers", "=", "self", ".", "num_beams", "logger", ".", "warning", "(", "f'top_k_answers value should not be greater than num_beams, hence setting it to {num_beams}'", ")", "self", ".", "top_k_answers", "=", "top_k_answers", "if", "use_gpu", "and", "torch", ".", "cuda", ".", "is_available", "(", ")", ":", "self", ".", "device", "=", "torch", ".", "device", "(", "\"cuda\"", ")", "else", ":", "self", ".", "device", "=", "torch", ".", "device", "(", "\"cpu\"", ")", "self", ".", "tokenizer", "=", "RagTokenizer", ".", "from_pretrained", "(", "model_name_or_path", ")", "if", "self", ".", "generator_type", "==", "RAGeneratorType", ".", "SEQUENCE", ":", "raise", "NotImplementedError", "(", "\"RagSequenceForGeneration is not implemented yet\"", ")", "# TODO: Enable when transformers have it. Refer https://github.com/huggingface/transformers/issues/7905", "# Also refer refer https://github.com/huggingface/transformers/issues/7829", "# self.model = RagSequenceForGeneration.from_pretrained(model_name_or_path)", "else", ":", "self", ".", "model", "=", "RagTokenForGeneration", ".", "from_pretrained", "(", "model_name_or_path", ",", "revision", "=", "model_version", ")", ".", "to", "(", "self", ".", "device", ")" ]
[ 63, 4 ]
[ 124, 122 ]
python
en
['en', 'error', 'th']
False
RAGenerator.predict
(self, query: str, documents: List[Document], top_k: Optional[int] = None)
Generate the answer to the input query. The generation will be conditioned on the supplied documents. These document can for example be retrieved via the Retriever. :param query: Query :param documents: Related documents (e.g. coming from a retriever) that the answer shall be conditioned on. :param top_k: Number of returned answers :return: Generated answers plus additional infos in a dict like this: ```python | {'query': 'who got the first nobel prize in physics', | 'answers': | [{'query': 'who got the first nobel prize in physics', | 'answer': ' albert einstein', | 'meta': { 'doc_ids': [...], | 'doc_scores': [80.42758 ...], | 'doc_probabilities': [40.71379089355469, ... | 'texts': ['Albert Einstein was a ...] | 'titles': ['"Albert Einstein"', ...] | }}]} ```
Generate the answer to the input query. The generation will be conditioned on the supplied documents. These document can for example be retrieved via the Retriever.
def predict(self, query: str, documents: List[Document], top_k: Optional[int] = None) -> Dict: """ Generate the answer to the input query. The generation will be conditioned on the supplied documents. These document can for example be retrieved via the Retriever. :param query: Query :param documents: Related documents (e.g. coming from a retriever) that the answer shall be conditioned on. :param top_k: Number of returned answers :return: Generated answers plus additional infos in a dict like this: ```python | {'query': 'who got the first nobel prize in physics', | 'answers': | [{'query': 'who got the first nobel prize in physics', | 'answer': ' albert einstein', | 'meta': { 'doc_ids': [...], | 'doc_scores': [80.42758 ...], | 'doc_probabilities': [40.71379089355469, ... | 'texts': ['Albert Einstein was a ...] | 'titles': ['"Albert Einstein"', ...] | }}]} ``` """ torch.set_grad_enabled(False) if len(documents) == 0: raise AttributeError("generator need documents to predict the answer") top_k_answers = top_k if top_k is not None else self.top_k_answers if top_k_answers > self.num_beams: top_k_answers = self.num_beams logger.warning(f'top_k value should not be greater than num_beams, ' f'hence setting it to {top_k_answers}') # Flatten the documents so easy to reference flat_docs_dict: Dict[str, Any] = {} for document in documents: for k, v in document.__dict__.items(): if k not in flat_docs_dict: flat_docs_dict[k] = [] flat_docs_dict[k].append(v) # Extract title titles = [d.meta["name"] if d.meta and "name" in d.meta else "" for d in documents] # Raw document embedding and set device of query_embedding passage_embeddings = self._prepare_passage_embeddings(docs=documents, embeddings=flat_docs_dict["embedding"]) # Query tokenization input_dict = self.tokenizer.prepare_seq2seq_batch( src_texts=[query], return_tensors="pt" ) input_ids = input_dict['input_ids'].to(self.device) # Query embedding query_embedding = self.model.question_encoder(input_ids)[0] # Prepare contextualized input_ids of documents # (will be transformed into contextualized inputs inside generator) context_input_ids, context_attention_mask = self._get_contextualized_inputs( texts=flat_docs_dict["text"], titles=titles, query=query ) # Compute doc scores from docs_embedding doc_scores = torch.bmm(query_embedding.unsqueeze(1), passage_embeddings.unsqueeze(0).transpose(1, 2)).squeeze(1) # Get generated ids from generator generator_ids = self.model.generate( context_input_ids=context_input_ids, context_attention_mask=context_attention_mask, doc_scores=doc_scores, num_return_sequences=top_k_answers, num_beams=self.num_beams, max_length=self.max_length, min_length=self.min_length, n_docs=len(flat_docs_dict["text"]) ) generated_answers = self.tokenizer.batch_decode(generator_ids, skip_special_tokens=True) answers: List[Any] = [] for generated_answer in generated_answers: cur_answer = { "query": query, "answer": generated_answer, "meta": { "doc_ids": flat_docs_dict["id"], "doc_scores": flat_docs_dict["score"], "doc_probabilities": flat_docs_dict["probability"], "texts": flat_docs_dict["text"], "titles": titles, } } answers.append(cur_answer) result = {"query": query, "answers": answers} return result
[ "def", "predict", "(", "self", ",", "query", ":", "str", ",", "documents", ":", "List", "[", "Document", "]", ",", "top_k", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Dict", ":", "torch", ".", "set_grad_enabled", "(", "False", ")", "if", "len", "(", "documents", ")", "==", "0", ":", "raise", "AttributeError", "(", "\"generator need documents to predict the answer\"", ")", "top_k_answers", "=", "top_k", "if", "top_k", "is", "not", "None", "else", "self", ".", "top_k_answers", "if", "top_k_answers", ">", "self", ".", "num_beams", ":", "top_k_answers", "=", "self", ".", "num_beams", "logger", ".", "warning", "(", "f'top_k value should not be greater than num_beams, '", "f'hence setting it to {top_k_answers}'", ")", "# Flatten the documents so easy to reference", "flat_docs_dict", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "}", "for", "document", "in", "documents", ":", "for", "k", ",", "v", "in", "document", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "not", "in", "flat_docs_dict", ":", "flat_docs_dict", "[", "k", "]", "=", "[", "]", "flat_docs_dict", "[", "k", "]", ".", "append", "(", "v", ")", "# Extract title", "titles", "=", "[", "d", ".", "meta", "[", "\"name\"", "]", "if", "d", ".", "meta", "and", "\"name\"", "in", "d", ".", "meta", "else", "\"\"", "for", "d", "in", "documents", "]", "# Raw document embedding and set device of query_embedding", "passage_embeddings", "=", "self", ".", "_prepare_passage_embeddings", "(", "docs", "=", "documents", ",", "embeddings", "=", "flat_docs_dict", "[", "\"embedding\"", "]", ")", "# Query tokenization", "input_dict", "=", "self", ".", "tokenizer", ".", "prepare_seq2seq_batch", "(", "src_texts", "=", "[", "query", "]", ",", "return_tensors", "=", "\"pt\"", ")", "input_ids", "=", "input_dict", "[", "'input_ids'", "]", ".", "to", "(", "self", ".", "device", ")", "# Query embedding", "query_embedding", "=", "self", ".", "model", ".", "question_encoder", "(", "input_ids", ")", "[", "0", "]", "# Prepare contextualized input_ids of documents", "# (will be transformed into contextualized inputs inside generator)", "context_input_ids", ",", "context_attention_mask", "=", "self", ".", "_get_contextualized_inputs", "(", "texts", "=", "flat_docs_dict", "[", "\"text\"", "]", ",", "titles", "=", "titles", ",", "query", "=", "query", ")", "# Compute doc scores from docs_embedding", "doc_scores", "=", "torch", ".", "bmm", "(", "query_embedding", ".", "unsqueeze", "(", "1", ")", ",", "passage_embeddings", ".", "unsqueeze", "(", "0", ")", ".", "transpose", "(", "1", ",", "2", ")", ")", ".", "squeeze", "(", "1", ")", "# Get generated ids from generator", "generator_ids", "=", "self", ".", "model", ".", "generate", "(", "context_input_ids", "=", "context_input_ids", ",", "context_attention_mask", "=", "context_attention_mask", ",", "doc_scores", "=", "doc_scores", ",", "num_return_sequences", "=", "top_k_answers", ",", "num_beams", "=", "self", ".", "num_beams", ",", "max_length", "=", "self", ".", "max_length", ",", "min_length", "=", "self", ".", "min_length", ",", "n_docs", "=", "len", "(", "flat_docs_dict", "[", "\"text\"", "]", ")", ")", "generated_answers", "=", "self", ".", "tokenizer", ".", "batch_decode", "(", "generator_ids", ",", "skip_special_tokens", "=", "True", ")", "answers", ":", "List", "[", "Any", "]", "=", "[", "]", "for", "generated_answer", "in", "generated_answers", ":", "cur_answer", "=", "{", "\"query\"", ":", "query", ",", "\"answer\"", ":", "generated_answer", ",", "\"meta\"", ":", "{", "\"doc_ids\"", ":", "flat_docs_dict", "[", "\"id\"", "]", ",", "\"doc_scores\"", ":", "flat_docs_dict", "[", "\"score\"", "]", ",", "\"doc_probabilities\"", ":", "flat_docs_dict", "[", "\"probability\"", "]", ",", "\"texts\"", ":", "flat_docs_dict", "[", "\"text\"", "]", ",", "\"titles\"", ":", "titles", ",", "}", "}", "answers", ".", "append", "(", "cur_answer", ")", "result", "=", "{", "\"query\"", ":", "query", ",", "\"answers\"", ":", "answers", "}", "return", "result" ]
[ 186, 4 ]
[ 286, 21 ]
python
en
['en', 'error', 'th']
False
OrderedDict.__init__
(self, *args, **kwds)
Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.
Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.
def __init__(self, *args, **kwds): '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__root except AttributeError: self.__root = root = [] # sentinel node root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "'expected at most 1 arguments, got %d'", "%", "len", "(", "args", ")", ")", "try", ":", "self", ".", "__root", "except", "AttributeError", ":", "self", ".", "__root", "=", "root", "=", "[", "]", "# sentinel node", "root", "[", ":", "]", "=", "[", "root", ",", "root", ",", "None", "]", "self", ".", "__map", "=", "{", "}", "self", ".", "__update", "(", "*", "args", ",", "*", "*", "kwds", ")" ]
[ 54, 4 ]
[ 68, 36 ]
python
en
['en', 'en', 'en']
True
OrderedDict.__setitem__
(self, key, value, dict_setitem=dict.__setitem__)
od.__setitem__(i, y) <==> od[i]=y
od.__setitem__(i, y) <==> od[i]=y
def __setitem__(self, key, value, dict_setitem=dict.__setitem__): 'od.__setitem__(i, y) <==> od[i]=y' # Setting a new item creates a new link which goes at the end of the linked # list, and the inherited dictionary is updated with the new key/value pair. if key not in self: root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
[ "def", "__setitem__", "(", "self", ",", "key", ",", "value", ",", "dict_setitem", "=", "dict", ".", "__setitem__", ")", ":", "# Setting a new item creates a new link which goes at the end of the linked", "# list, and the inherited dictionary is updated with the new key/value pair.", "if", "key", "not", "in", "self", ":", "root", "=", "self", ".", "__root", "last", "=", "root", "[", "0", "]", "last", "[", "1", "]", "=", "root", "[", "0", "]", "=", "self", ".", "__map", "[", "key", "]", "=", "[", "last", ",", "root", ",", "key", "]", "dict_setitem", "(", "self", ",", "key", ",", "value", ")" ]
[ 70, 4 ]
[ 78, 38 ]
python
cy
['de', 'cy', 'es']
False
OrderedDict.__delitem__
(self, key, dict_delitem=dict.__delitem__)
od.__delitem__(y) <==> del od[y]
od.__delitem__(y) <==> del od[y]
def __delitem__(self, key, dict_delitem=dict.__delitem__): 'od.__delitem__(y) <==> del od[y]' # Deleting an existing item uses self.__map to find the link which is # then removed by updating the links in the predecessor and successor nodes. dict_delitem(self, key) link_prev, link_next, key = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
[ "def", "__delitem__", "(", "self", ",", "key", ",", "dict_delitem", "=", "dict", ".", "__delitem__", ")", ":", "# Deleting an existing item uses self.__map to find the link which is", "# then removed by updating the links in the predecessor and successor nodes.", "dict_delitem", "(", "self", ",", "key", ")", "link_prev", ",", "link_next", ",", "key", "=", "self", ".", "__map", ".", "pop", "(", "key", ")", "link_prev", "[", "1", "]", "=", "link_next", "link_next", "[", "0", "]", "=", "link_prev" ]
[ 80, 4 ]
[ 87, 32 ]
python
it
['it', 'es', 'it']
True
OrderedDict.__iter__
(self)
od.__iter__() <==> iter(od)
od.__iter__() <==> iter(od)
def __iter__(self): 'od.__iter__() <==> iter(od)' root = self.__root curr = root[1] while curr is not root: yield curr[2] curr = curr[1]
[ "def", "__iter__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "1", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "1", "]" ]
[ 89, 4 ]
[ 95, 26 ]
python
en
['en', 'hr', 'ur']
False
OrderedDict.__reversed__
(self)
od.__reversed__() <==> reversed(od)
od.__reversed__() <==> reversed(od)
def __reversed__(self): 'od.__reversed__() <==> reversed(od)' root = self.__root curr = root[0] while curr is not root: yield curr[2] curr = curr[0]
[ "def", "__reversed__", "(", "self", ")", ":", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "0", "]", "while", "curr", "is", "not", "root", ":", "yield", "curr", "[", "2", "]", "curr", "=", "curr", "[", "0", "]" ]
[ 97, 4 ]
[ 103, 26 ]
python
en
['en', 'no', 'en']
True
OrderedDict.clear
(self)
od.clear() -> None. Remove all items from od.
od.clear() -> None. Remove all items from od.
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
[ "def", "clear", "(", "self", ")", ":", "try", ":", "for", "node", "in", "self", ".", "__map", ".", "itervalues", "(", ")", ":", "del", "node", "[", ":", "]", "root", "=", "self", ".", "__root", "root", "[", ":", "]", "=", "[", "root", ",", "root", ",", "None", "]", "self", ".", "__map", ".", "clear", "(", ")", "except", "AttributeError", ":", "pass", "dict", ".", "clear", "(", "self", ")" ]
[ 105, 4 ]
[ 115, 24 ]
python
en
['en', 'en', 'en']
True
OrderedDict.popitem
(self, last=True)
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return key, value
[ "def", "popitem", "(", "self", ",", "last", "=", "True", ")", ":", "if", "not", "self", ":", "raise", "KeyError", "(", "'dictionary is empty'", ")", "root", "=", "self", ".", "__root", "if", "last", ":", "link", "=", "root", "[", "0", "]", "link_prev", "=", "link", "[", "0", "]", "link_prev", "[", "1", "]", "=", "root", "root", "[", "0", "]", "=", "link_prev", "else", ":", "link", "=", "root", "[", "1", "]", "link_next", "=", "link", "[", "1", "]", "root", "[", "1", "]", "=", "link_next", "link_next", "[", "0", "]", "=", "root", "key", "=", "link", "[", "2", "]", "del", "self", ".", "__map", "[", "key", "]", "value", "=", "dict", ".", "pop", "(", "self", ",", "key", ")", "return", "key", ",", "value" ]
[ 117, 4 ]
[ 138, 25 ]
python
en
['en', 'hi-Latn', 'en']
True
OrderedDict.keys
(self)
od.keys() -> list of keys in od
od.keys() -> list of keys in od
def keys(self): 'od.keys() -> list of keys in od' return list(self)
[ "def", "keys", "(", "self", ")", ":", "return", "list", "(", "self", ")" ]
[ 142, 4 ]
[ 144, 25 ]
python
en
['en', 'fy', 'en']
True
OrderedDict.values
(self)
od.values() -> list of values in od
od.values() -> list of values in od
def values(self): 'od.values() -> list of values in od' return [self[key] for key in self]
[ "def", "values", "(", "self", ")", ":", "return", "[", "self", "[", "key", "]", "for", "key", "in", "self", "]" ]
[ 146, 4 ]
[ 148, 42 ]
python
en
['en', 'en', 'en']
True
OrderedDict.items
(self)
od.items() -> list of (key, value) pairs in od
od.items() -> list of (key, value) pairs in od
def items(self): 'od.items() -> list of (key, value) pairs in od' return [(key, self[key]) for key in self]
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "key", ",", "self", "[", "key", "]", ")", "for", "key", "in", "self", "]" ]
[ 150, 4 ]
[ 152, 49 ]
python
en
['en', 'en', 'en']
True
OrderedDict.iterkeys
(self)
od.iterkeys() -> an iterator over the keys in od
od.iterkeys() -> an iterator over the keys in od
def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self)
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "self", ")" ]
[ 154, 4 ]
[ 156, 25 ]
python
en
['en', 'sv', 'en']
True
OrderedDict.itervalues
(self)
od.itervalues -> an iterator over the values in od
od.itervalues -> an iterator over the values in od
def itervalues(self): 'od.itervalues -> an iterator over the values in od' for k in self: yield self[k]
[ "def", "itervalues", "(", "self", ")", ":", "for", "k", "in", "self", ":", "yield", "self", "[", "k", "]" ]
[ 158, 4 ]
[ 161, 25 ]
python
en
['en', 'en', 'en']
True
OrderedDict.iteritems
(self)
od.iteritems -> an iterator over the (key, value) items in od
od.iteritems -> an iterator over the (key, value) items in od
def iteritems(self): 'od.iteritems -> an iterator over the (key, value) items in od' for k in self: yield (k, self[k])
[ "def", "iteritems", "(", "self", ")", ":", "for", "k", "in", "self", ":", "yield", "(", "k", ",", "self", "[", "k", "]", ")" ]
[ 163, 4 ]
[ 166, 30 ]
python
en
['en', 'en', 'en']
True
OrderedDict.update
(*args, **kwds)
od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v
od.update(E, **F) -> None. Update od from dict/iterable E and F.
def update(*args, **kwds): '''od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, v in F.items(): od[k] = v ''' if len(args) > 2: raise TypeError('update() takes at most 2 positional ' 'arguments (%d given)' % (len(args),)) elif not args: raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] # Make progressively weaker assumptions about "other" other = () if len(args) == 2: other = args[1] if isinstance(other, dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value
[ "def", "update", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "len", "(", "args", ")", ">", "2", ":", "raise", "TypeError", "(", "'update() takes at most 2 positional '", "'arguments (%d given)'", "%", "(", "len", "(", "args", ")", ",", ")", ")", "elif", "not", "args", ":", "raise", "TypeError", "(", "'update() takes at least 1 argument (0 given)'", ")", "self", "=", "args", "[", "0", "]", "# Make progressively weaker assumptions about \"other\"", "other", "=", "(", ")", "if", "len", "(", "args", ")", "==", "2", ":", "other", "=", "args", "[", "1", "]", "if", "isinstance", "(", "other", ",", "dict", ")", ":", "for", "key", "in", "other", ":", "self", "[", "key", "]", "=", "other", "[", "key", "]", "elif", "hasattr", "(", "other", ",", "'keys'", ")", ":", "for", "key", "in", "other", ".", "keys", "(", ")", ":", "self", "[", "key", "]", "=", "other", "[", "key", "]", "else", ":", "for", "key", ",", "value", "in", "other", ":", "self", "[", "key", "]", "=", "value", "for", "key", ",", "value", "in", "kwds", ".", "items", "(", ")", ":", "self", "[", "key", "]", "=", "value" ]
[ 170, 4 ]
[ 199, 29 ]
python
en
['en', 'en', 'en']
True
OrderedDict.pop
(self, key, default=__marker)
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] return result if default is self.__marker: raise KeyError(key) return default
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "if", "key", "in", "self", ":", "result", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "result", "if", "default", "is", "self", ".", "__marker", ":", "raise", "KeyError", "(", "key", ")", "return", "default" ]
[ 205, 4 ]
[ 216, 22 ]
python
en
['en', 'en', 'en']
True
OrderedDict.setdefault
(self, key, default=None)
od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od
od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od
def setdefault(self, key, default=None): 'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od' if key in self: return self[key] self[key] = default return default
[ "def", "setdefault", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", "[", "key", "]", "self", "[", "key", "]", "=", "default", "return", "default" ]
[ 218, 4 ]
[ 223, 22 ]
python
en
['en', 'sl', 'en']
True
OrderedDict.__repr__
(self, _repr_running={})
od.__repr__() <==> repr(od)
od.__repr__() <==> repr(od)
def __repr__(self, _repr_running={}): 'od.__repr__() <==> repr(od)' call_key = id(self), _get_ident() if call_key in _repr_running: return '...' _repr_running[call_key] = 1 try: if not self: return '%s()' % (self.__class__.__name__,) return '%s(%r)' % (self.__class__.__name__, self.items()) finally: del _repr_running[call_key]
[ "def", "__repr__", "(", "self", ",", "_repr_running", "=", "{", "}", ")", ":", "call_key", "=", "id", "(", "self", ")", ",", "_get_ident", "(", ")", "if", "call_key", "in", "_repr_running", ":", "return", "'...'", "_repr_running", "[", "call_key", "]", "=", "1", "try", ":", "if", "not", "self", ":", "return", "'%s()'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", ")", "return", "'%s(%r)'", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "items", "(", ")", ")", "finally", ":", "del", "_repr_running", "[", "call_key", "]" ]
[ 225, 4 ]
[ 236, 39 ]
python
en
['en', 'it', 'hi']
False
OrderedDict.__reduce__
(self)
Return state information for pickling
Return state information for pickling
def __reduce__(self): 'Return state information for pickling' items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return self.__class__, (items,)
[ "def", "__reduce__", "(", "self", ")", ":", "items", "=", "[", "[", "k", ",", "self", "[", "k", "]", "]", "for", "k", "in", "self", "]", "inst_dict", "=", "vars", "(", "self", ")", ".", "copy", "(", ")", "for", "k", "in", "vars", "(", "OrderedDict", "(", ")", ")", ":", "inst_dict", ".", "pop", "(", "k", ",", "None", ")", "if", "inst_dict", ":", "return", "(", "self", ".", "__class__", ",", "(", "items", ",", ")", ",", "inst_dict", ")", "return", "self", ".", "__class__", ",", "(", "items", ",", ")" ]
[ 238, 4 ]
[ 246, 39 ]
python
en
['en', 'da', 'en']
True
OrderedDict.copy
(self)
od.copy() -> a shallow copy of od
od.copy() -> a shallow copy of od
def copy(self): 'od.copy() -> a shallow copy of od' return self.__class__(self)
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "self", ")" ]
[ 248, 4 ]
[ 250, 35 ]
python
en
['en', 'cs', 'en']
True
OrderedDict.fromkeys
(cls, iterable, value=None)
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).
def fromkeys(cls, iterable, value=None): '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None). ''' d = cls() for key in iterable: d[key] = value return d
[ "def", "fromkeys", "(", "cls", ",", "iterable", ",", "value", "=", "None", ")", ":", "d", "=", "cls", "(", ")", "for", "key", "in", "iterable", ":", "d", "[", "key", "]", "=", "value", "return", "d" ]
[ 253, 4 ]
[ 261, 16 ]
python
en
['en', 'en', 'en']
True
OrderedDict.__eq__
(self, other)
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.
def __eq__(self, other): '''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive. ''' if isinstance(other, OrderedDict): return len(self)==len(other) and self.items() == other.items() return dict.__eq__(self, other)
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "OrderedDict", ")", ":", "return", "len", "(", "self", ")", "==", "len", "(", "other", ")", "and", "self", ".", "items", "(", ")", "==", "other", ".", "items", "(", ")", "return", "dict", ".", "__eq__", "(", "self", ",", "other", ")" ]
[ 263, 4 ]
[ 270, 39 ]
python
en
['en', 'en', 'en']
True
OrderedDict.viewkeys
(self)
od.viewkeys() -> a set-like object providing a view on od's keys
od.viewkeys() -> a set-like object providing a view on od's keys
def viewkeys(self): "od.viewkeys() -> a set-like object providing a view on od's keys" return KeysView(self)
[ "def", "viewkeys", "(", "self", ")", ":", "return", "KeysView", "(", "self", ")" ]
[ 277, 4 ]
[ 279, 29 ]
python
en
['en', 'cs', 'en']
True
OrderedDict.viewvalues
(self)
od.viewvalues() -> an object providing a view on od's values
od.viewvalues() -> an object providing a view on od's values
def viewvalues(self): "od.viewvalues() -> an object providing a view on od's values" return ValuesView(self)
[ "def", "viewvalues", "(", "self", ")", ":", "return", "ValuesView", "(", "self", ")" ]
[ 281, 4 ]
[ 283, 31 ]
python
en
['en', 'en', 'en']
True
OrderedDict.viewitems
(self)
od.viewitems() -> a set-like object providing a view on od's items
od.viewitems() -> a set-like object providing a view on od's items
def viewitems(self): "od.viewitems() -> a set-like object providing a view on od's items" return ItemsView(self)
[ "def", "viewitems", "(", "self", ")", ":", "return", "ItemsView", "(", "self", ")" ]
[ 285, 4 ]
[ 287, 30 ]
python
en
['en', 'haw', 'en']
True
PublicIngredientsApiTests.test_login_required
(self)
Test that login is required to access the endpoint
Test that login is required to access the endpoint
def test_login_required(self): """"Test that login is required to access the endpoint""" res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
[ "def", "test_login_required", "(", "self", ")", ":", "res", "=", "self", ".", "client", ".", "get", "(", "INGREDIENTS_URL", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_401_UNAUTHORIZED", ")" ]
[ 21, 4 ]
[ 25, 71 ]
python
en
['en', 'en', 'en']
True
PrivateIngredientsApiTests.test_retrieve_ingredient_list
(self)
Test retrieving a list of ingredients
Test retrieving a list of ingredients
def test_retrieve_ingredient_list(self): """"Test retrieving a list of ingredients""" Ingredient.objects.create(user=self.user, name='Kale') Ingredient.objects.create(user=self.user, name='Salt') res = self.client.get(INGREDIENTS_URL) ingredients = Ingredient.objects.all().order_by('-name') serializer = IngredientSerializer(ingredients, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
[ "def", "test_retrieve_ingredient_list", "(", "self", ")", ":", "Ingredient", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Kale'", ")", "Ingredient", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Salt'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "INGREDIENTS_URL", ")", "ingredients", "=", "Ingredient", ".", "objects", ".", "all", "(", ")", ".", "order_by", "(", "'-name'", ")", "serializer", "=", "IngredientSerializer", "(", "ingredients", ",", "many", "=", "True", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_200_OK", ")", "self", ".", "assertEqual", "(", "res", ".", "data", ",", "serializer", ".", "data", ")" ]
[ 39, 4 ]
[ 50, 51 ]
python
en
['en', 'en', 'en']
True
PrivateIngredientsApiTests.test_ingredients_limited_to_user
(self)
Test that ingredients for the authenticated user are returned
Test that ingredients for the authenticated user are returned
def test_ingredients_limited_to_user(self): """"Test that ingredients for the authenticated user are returned""" user2 = get_user_model().objects.create_user( '[email protected]', 'testpass' ) Ingredient.objects.create(user=user2, name='Vinegar') ingredient = Ingredient.objects.create(user=self.user, name='Tumeric') res = self.client.get(INGREDIENTS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], ingredient.name)
[ "def", "test_ingredients_limited_to_user", "(", "self", ")", ":", "user2", "=", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "'[email protected]'", ",", "'testpass'", ")", "Ingredient", ".", "objects", ".", "create", "(", "user", "=", "user2", ",", "name", "=", "'Vinegar'", ")", "ingredient", "=", "Ingredient", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Tumeric'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "INGREDIENTS_URL", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_200_OK", ")", "self", ".", "assertEqual", "(", "len", "(", "res", ".", "data", ")", ",", "1", ")", "self", ".", "assertEqual", "(", "res", ".", "data", "[", "0", "]", "[", "'name'", "]", ",", "ingredient", ".", "name", ")" ]
[ 52, 4 ]
[ 65, 62 ]
python
en
['en', 'en', 'en']
True
PrivateIngredientsApiTests.test_create_ingredient_successful
(self)
Test create a new ingredient
Test create a new ingredient
def test_create_ingredient_successful(self): """Test create a new ingredient""" payload = {'name': 'Cabbage'} self.client.post(INGREDIENTS_URL, payload) exists = Ingredient.objects.filter( user=self.user, name=payload['name'], ).exists() self.assertTrue(exists)
[ "def", "test_create_ingredient_successful", "(", "self", ")", ":", "payload", "=", "{", "'name'", ":", "'Cabbage'", "}", "self", ".", "client", ".", "post", "(", "INGREDIENTS_URL", ",", "payload", ")", "exists", "=", "Ingredient", ".", "objects", ".", "filter", "(", "user", "=", "self", ".", "user", ",", "name", "=", "payload", "[", "'name'", "]", ",", ")", ".", "exists", "(", ")", "self", ".", "assertTrue", "(", "exists", ")" ]
[ 67, 4 ]
[ 77, 31 ]
python
en
['nl', 'en', 'en']
True