repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 39
1.84M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
Type.get_fields
|
def get_fields(self):
"""Return an iterator for accessing the fields of this type."""
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
# Create reference to TU so it isn't GC'd before Cursor.
field._tu = self._tu
fields.append(field)
return 1 # continue
fields = []
conf.lib.clang_Type_visitFields(self,
callbacks['fields_visit'](visitor), fields)
return iter(fields)
|
python
|
def get_fields(self):
def visitor(field, children):
assert field != conf.lib.clang_getNullCursor()
field._tu = self._tu
fields.append(field)
return 1
fields = []
conf.lib.clang_Type_visitFields(self,
callbacks['fields_visit'](visitor), fields)
return iter(fields)
|
[
"def",
"get_fields",
"(",
"self",
")",
":",
"def",
"visitor",
"(",
"field",
",",
"children",
")",
":",
"assert",
"field",
"!=",
"conf",
".",
"lib",
".",
"clang_getNullCursor",
"(",
")",
"# Create reference to TU so it isn't GC'd before Cursor.",
"field",
".",
"_tu",
"=",
"self",
".",
"_tu",
"fields",
".",
"append",
"(",
"field",
")",
"return",
"1",
"# continue",
"fields",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_Type_visitFields",
"(",
"self",
",",
"callbacks",
"[",
"'fields_visit'",
"]",
"(",
"visitor",
")",
",",
"fields",
")",
"return",
"iter",
"(",
"fields",
")"
] |
Return an iterator for accessing the fields of this type.
|
[
"Return",
"an",
"iterator",
"for",
"accessing",
"the",
"fields",
"of",
"this",
"type",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2174-L2187
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
Index.parse
|
def parse(self, path, args=None, unsaved_files=None, options = 0):
"""Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised.
"""
return TranslationUnit.from_source(path, args, unsaved_files, options,
self)
|
python
|
def parse(self, path, args=None, unsaved_files=None, options = 0):
return TranslationUnit.from_source(path, args, unsaved_files, options,
self)
|
[
"def",
"parse",
"(",
"self",
",",
"path",
",",
"args",
"=",
"None",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"return",
"TranslationUnit",
".",
"from_source",
"(",
"path",
",",
"args",
",",
"unsaved_files",
",",
"options",
",",
"self",
")"
] |
Load the translation unit from the given source code file by running
clang and generating the AST before loading. Additional command line
parameters can be passed to clang via the args parameter.
In-memory contents for files can be provided by passing a list of pairs
to as unsaved_files, the first item should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
If an error was encountered during parsing, a TranslationUnitLoadError
will be raised.
|
[
"Load",
"the",
"translation",
"unit",
"from",
"the",
"given",
"source",
"code",
"file",
"by",
"running",
"clang",
"and",
"generating",
"the",
"AST",
"before",
"loading",
".",
"Additional",
"command",
"line",
"parameters",
"can",
"be",
"passed",
"to",
"clang",
"via",
"the",
"args",
"parameter",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2471-L2485
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.from_ast_file
|
def from_ast_file(cls, filename, index=None):
"""Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
"""
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index)
|
python
|
def from_ast_file(cls, filename, index=None):
if index is None:
index = Index.create()
ptr = conf.lib.clang_createTranslationUnit(index, filename)
if not ptr:
raise TranslationUnitLoadError(filename)
return cls(ptr=ptr, index=index)
|
[
"def",
"from_ast_file",
"(",
"cls",
",",
"filename",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"index",
"=",
"Index",
".",
"create",
"(",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_createTranslationUnit",
"(",
"index",
",",
"filename",
")",
"if",
"not",
"ptr",
":",
"raise",
"TranslationUnitLoadError",
"(",
"filename",
")",
"return",
"cls",
"(",
"ptr",
"=",
"ptr",
",",
"index",
"=",
"index",
")"
] |
Create a TranslationUnit instance from a saved AST file.
A previously-saved AST file (provided with -emit-ast or
TranslationUnit.save()) is loaded from the filename specified.
If the file cannot be loaded, a TranslationUnitLoadError will be
raised.
index is optional and is the Index instance to use. If not provided,
a default Index will be created.
|
[
"Create",
"a",
"TranslationUnit",
"instance",
"from",
"a",
"saved",
"AST",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2604-L2623
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.get_includes
|
def get_includes(self):
"""
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers.
"""
def visitor(fobj, lptr, depth, includes):
if depth > 0:
loc = lptr.contents
includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
# Automatically adapt CIndex/ctype pointers to python objects
includes = []
conf.lib.clang_getInclusions(self,
callbacks['translation_unit_includes'](visitor), includes)
return iter(includes)
|
python
|
def get_includes(self):
def visitor(fobj, lptr, depth, includes):
if depth > 0:
loc = lptr.contents
includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
includes = []
conf.lib.clang_getInclusions(self,
callbacks['translation_unit_includes'](visitor), includes)
return iter(includes)
|
[
"def",
"get_includes",
"(",
"self",
")",
":",
"def",
"visitor",
"(",
"fobj",
",",
"lptr",
",",
"depth",
",",
"includes",
")",
":",
"if",
"depth",
">",
"0",
":",
"loc",
"=",
"lptr",
".",
"contents",
"includes",
".",
"append",
"(",
"FileInclusion",
"(",
"loc",
".",
"file",
",",
"File",
"(",
"fobj",
")",
",",
"loc",
",",
"depth",
")",
")",
"# Automatically adapt CIndex/ctype pointers to python objects",
"includes",
"=",
"[",
"]",
"conf",
".",
"lib",
".",
"clang_getInclusions",
"(",
"self",
",",
"callbacks",
"[",
"'translation_unit_includes'",
"]",
"(",
"visitor",
")",
",",
"includes",
")",
"return",
"iter",
"(",
"includes",
")"
] |
Return an iterable sequence of FileInclusion objects that describe the
sequence of inclusions in a translation unit. The first object in
this sequence is always the input file. Note that this method will not
recursively iterate over header files included through precompiled
headers.
|
[
"Return",
"an",
"iterable",
"sequence",
"of",
"FileInclusion",
"objects",
"that",
"describe",
"the",
"sequence",
"of",
"inclusions",
"in",
"a",
"translation",
"unit",
".",
"The",
"first",
"object",
"in",
"this",
"sequence",
"is",
"always",
"the",
"input",
"file",
".",
"Note",
"that",
"this",
"method",
"will",
"not",
"recursively",
"iterate",
"over",
"header",
"files",
"included",
"through",
"precompiled",
"headers",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2648-L2666
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.get_location
|
def get_location(self, filename, position):
"""Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
"""
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1])
|
python
|
def get_location(self, filename, position):
f = self.get_file(filename)
if isinstance(position, int):
return SourceLocation.from_offset(self, f, position)
return SourceLocation.from_position(self, f, position[0], position[1])
|
[
"def",
"get_location",
"(",
"self",
",",
"filename",
",",
"position",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"isinstance",
"(",
"position",
",",
"int",
")",
":",
"return",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"position",
")",
"return",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"position",
"[",
"0",
"]",
",",
"position",
"[",
"1",
"]",
")"
] |
Obtain a SourceLocation for a file in this translation unit.
The position can be specified by passing:
- Integer file offset. Initial file offset is 0.
- 2-tuple of (line number, column number). Initial file position is
(0, 0)
|
[
"Obtain",
"a",
"SourceLocation",
"for",
"a",
"file",
"in",
"this",
"translation",
"unit",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2673-L2687
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.get_extent
|
def get_extent(self, filename, locations):
"""Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
"""
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location)
|
python
|
def get_extent(self, filename, locations):
f = self.get_file(filename)
if len(locations) < 2:
raise Exception('Must pass object with at least 2 elements')
start_location, end_location = locations
if hasattr(start_location, '__len__'):
start_location = SourceLocation.from_position(self, f,
start_location[0], start_location[1])
elif isinstance(start_location, int):
start_location = SourceLocation.from_offset(self, f,
start_location)
if hasattr(end_location, '__len__'):
end_location = SourceLocation.from_position(self, f,
end_location[0], end_location[1])
elif isinstance(end_location, int):
end_location = SourceLocation.from_offset(self, f, end_location)
assert isinstance(start_location, SourceLocation)
assert isinstance(end_location, SourceLocation)
return SourceRange.from_locations(start_location, end_location)
|
[
"def",
"get_extent",
"(",
"self",
",",
"filename",
",",
"locations",
")",
":",
"f",
"=",
"self",
".",
"get_file",
"(",
"filename",
")",
"if",
"len",
"(",
"locations",
")",
"<",
"2",
":",
"raise",
"Exception",
"(",
"'Must pass object with at least 2 elements'",
")",
"start_location",
",",
"end_location",
"=",
"locations",
"if",
"hasattr",
"(",
"start_location",
",",
"'__len__'",
")",
":",
"start_location",
"=",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"start_location",
"[",
"0",
"]",
",",
"start_location",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"start_location",
",",
"int",
")",
":",
"start_location",
"=",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"start_location",
")",
"if",
"hasattr",
"(",
"end_location",
",",
"'__len__'",
")",
":",
"end_location",
"=",
"SourceLocation",
".",
"from_position",
"(",
"self",
",",
"f",
",",
"end_location",
"[",
"0",
"]",
",",
"end_location",
"[",
"1",
"]",
")",
"elif",
"isinstance",
"(",
"end_location",
",",
"int",
")",
":",
"end_location",
"=",
"SourceLocation",
".",
"from_offset",
"(",
"self",
",",
"f",
",",
"end_location",
")",
"assert",
"isinstance",
"(",
"start_location",
",",
"SourceLocation",
")",
"assert",
"isinstance",
"(",
"end_location",
",",
"SourceLocation",
")",
"return",
"SourceRange",
".",
"from_locations",
"(",
"start_location",
",",
"end_location",
")"
] |
Obtain a SourceRange from this translation unit.
The bounds of the SourceRange must ultimately be defined by a start and
end SourceLocation. For the locations argument, you can pass:
- 2 SourceLocation instances in a 2-tuple or list.
- 2 int file offsets via a 2-tuple or list.
- 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
e.g.
get_extent('foo.c', (5, 10))
get_extent('foo.c', ((1, 1), (1, 15)))
|
[
"Obtain",
"a",
"SourceRange",
"from",
"this",
"translation",
"unit",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2689-L2727
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.diagnostics
|
def diagnostics(self):
"""
Return an iterable (and indexable) object containing the diagnostics.
"""
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
def __getitem__(self, key):
diag = conf.lib.clang_getDiagnostic(self.tu, key)
if not diag:
raise IndexError
return Diagnostic(diag)
return DiagIterator(self)
|
python
|
def diagnostics(self):
class DiagIterator:
def __init__(self, tu):
self.tu = tu
def __len__(self):
return int(conf.lib.clang_getNumDiagnostics(self.tu))
def __getitem__(self, key):
diag = conf.lib.clang_getDiagnostic(self.tu, key)
if not diag:
raise IndexError
return Diagnostic(diag)
return DiagIterator(self)
|
[
"def",
"diagnostics",
"(",
"self",
")",
":",
"class",
"DiagIterator",
":",
"def",
"__init__",
"(",
"self",
",",
"tu",
")",
":",
"self",
".",
"tu",
"=",
"tu",
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"int",
"(",
"conf",
".",
"lib",
".",
"clang_getNumDiagnostics",
"(",
"self",
".",
"tu",
")",
")",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"diag",
"=",
"conf",
".",
"lib",
".",
"clang_getDiagnostic",
"(",
"self",
".",
"tu",
",",
"key",
")",
"if",
"not",
"diag",
":",
"raise",
"IndexError",
"return",
"Diagnostic",
"(",
"diag",
")",
"return",
"DiagIterator",
"(",
"self",
")"
] |
Return an iterable (and indexable) object containing the diagnostics.
|
[
"Return",
"an",
"iterable",
"(",
"and",
"indexable",
")",
"object",
"containing",
"the",
"diagnostics",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2730-L2747
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.reparse
|
def reparse(self, unsaved_files=None, options=0):
"""
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options)
|
python
|
def reparse(self, unsaved_files=None, options=0):
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = name
unsaved_files_array[i].contents = value
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
unsaved_files_array, options)
|
[
"def",
"reparse",
"(",
"self",
",",
"unsaved_files",
"=",
"None",
",",
"options",
"=",
"0",
")",
":",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
"unsaved_files_array",
"=",
"(",
"_CXUnsavedFile",
"*",
"len",
"(",
"unsaved_files",
")",
")",
"(",
")",
"for",
"i",
",",
"(",
"name",
",",
"value",
")",
"in",
"enumerate",
"(",
"unsaved_files",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# FIXME: It would be great to support an efficient version",
"# of this, one day.",
"value",
"=",
"value",
".",
"read",
"(",
")",
"print",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Unexpected unsaved file contents.'",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"name",
"=",
"name",
"unsaved_files_array",
"[",
"i",
"]",
".",
"contents",
"=",
"value",
"unsaved_files_array",
"[",
"i",
"]",
".",
"length",
"=",
"len",
"(",
"value",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_reparseTranslationUnit",
"(",
"self",
",",
"len",
"(",
"unsaved_files",
")",
",",
"unsaved_files_array",
",",
"options",
")"
] |
Reparse an already parsed translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
|
[
"Reparse",
"an",
"already",
"parsed",
"translation",
"unit",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2749-L2776
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.save
|
def save(self, filename):
"""Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
"""
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.')
|
python
|
def save(self, filename):
options = conf.lib.clang_defaultSaveOptions(self)
result = int(conf.lib.clang_saveTranslationUnit(self, filename,
options))
if result != 0:
raise TranslationUnitSaveError(result,
'Error saving TranslationUnit.')
|
[
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"options",
"=",
"conf",
".",
"lib",
".",
"clang_defaultSaveOptions",
"(",
"self",
")",
"result",
"=",
"int",
"(",
"conf",
".",
"lib",
".",
"clang_saveTranslationUnit",
"(",
"self",
",",
"filename",
",",
"options",
")",
")",
"if",
"result",
"!=",
"0",
":",
"raise",
"TranslationUnitSaveError",
"(",
"result",
",",
"'Error saving TranslationUnit.'",
")"
] |
Saves the TranslationUnit to a file.
This is equivalent to passing -emit-ast to the clang frontend. The
saved file can be loaded back into a TranslationUnit. Or, if it
corresponds to a header, it can be used as a pre-compiled header file.
If an error occurs while saving, a TranslationUnitSaveError is raised.
If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
the constructed TranslationUnit was not valid at time of save. In this
case, the reason(s) why should be available via
TranslationUnit.diagnostics().
filename -- The path to save the translation unit to.
|
[
"Saves",
"the",
"TranslationUnit",
"to",
"a",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2778-L2798
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.codeComplete
|
def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
"""
options = 0
if include_macros:
options += 1
if include_code_patterns:
options += 2
if include_brief_comments:
options += 4
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
# FIXME: It would be great to support an efficient version
# of this, one day.
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = c_string_p(name)
unsaved_files_array[i].contents = c_string_p(value)
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
unsaved_files_array, len(unsaved_files), options)
if ptr:
return CodeCompletionResults(ptr)
return None
|
python
|
def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
options = 0
if include_macros:
options += 1
if include_code_patterns:
options += 2
if include_brief_comments:
options += 4
if unsaved_files is None:
unsaved_files = []
unsaved_files_array = 0
if len(unsaved_files):
unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
for i,(name,value) in enumerate(unsaved_files):
if not isinstance(value, str):
value = value.read()
print(value)
if not isinstance(value, str):
raise TypeError('Unexpected unsaved file contents.')
unsaved_files_array[i].name = c_string_p(name)
unsaved_files_array[i].contents = c_string_p(value)
unsaved_files_array[i].length = len(value)
ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
unsaved_files_array, len(unsaved_files), options)
if ptr:
return CodeCompletionResults(ptr)
return None
|
[
"def",
"codeComplete",
"(",
"self",
",",
"path",
",",
"line",
",",
"column",
",",
"unsaved_files",
"=",
"None",
",",
"include_macros",
"=",
"False",
",",
"include_code_patterns",
"=",
"False",
",",
"include_brief_comments",
"=",
"False",
")",
":",
"options",
"=",
"0",
"if",
"include_macros",
":",
"options",
"+=",
"1",
"if",
"include_code_patterns",
":",
"options",
"+=",
"2",
"if",
"include_brief_comments",
":",
"options",
"+=",
"4",
"if",
"unsaved_files",
"is",
"None",
":",
"unsaved_files",
"=",
"[",
"]",
"unsaved_files_array",
"=",
"0",
"if",
"len",
"(",
"unsaved_files",
")",
":",
"unsaved_files_array",
"=",
"(",
"_CXUnsavedFile",
"*",
"len",
"(",
"unsaved_files",
")",
")",
"(",
")",
"for",
"i",
",",
"(",
"name",
",",
"value",
")",
"in",
"enumerate",
"(",
"unsaved_files",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# FIXME: It would be great to support an efficient version",
"# of this, one day.",
"value",
"=",
"value",
".",
"read",
"(",
")",
"print",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"'Unexpected unsaved file contents.'",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"name",
"=",
"c_string_p",
"(",
"name",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"contents",
"=",
"c_string_p",
"(",
"value",
")",
"unsaved_files_array",
"[",
"i",
"]",
".",
"length",
"=",
"len",
"(",
"value",
")",
"ptr",
"=",
"conf",
".",
"lib",
".",
"clang_codeCompleteAt",
"(",
"self",
",",
"path",
",",
"line",
",",
"column",
",",
"unsaved_files_array",
",",
"len",
"(",
"unsaved_files",
")",
",",
"options",
")",
"if",
"ptr",
":",
"return",
"CodeCompletionResults",
"(",
"ptr",
")",
"return",
"None"
] |
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as strings or file objects.
|
[
"Code",
"complete",
"in",
"this",
"translation",
"unit",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2800-L2843
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
TranslationUnit.get_tokens
|
def get_tokens(self, locations=None, extent=None):
"""Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
"""
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent)
|
python
|
def get_tokens(self, locations=None, extent=None):
if locations is not None:
extent = SourceRange(start=locations[0], end=locations[1])
return TokenGroup.get_tokens(self, extent)
|
[
"def",
"get_tokens",
"(",
"self",
",",
"locations",
"=",
"None",
",",
"extent",
"=",
"None",
")",
":",
"if",
"locations",
"is",
"not",
"None",
":",
"extent",
"=",
"SourceRange",
"(",
"start",
"=",
"locations",
"[",
"0",
"]",
",",
"end",
"=",
"locations",
"[",
"1",
"]",
")",
"return",
"TokenGroup",
".",
"get_tokens",
"(",
"self",
",",
"extent",
")"
] |
Obtain tokens in this translation unit.
This is a generator for Token instances. The caller specifies a range
of source code to obtain tokens for. The range can be specified as a
2-tuple of SourceLocation or as a SourceRange. If both are defined,
behavior is undefined.
|
[
"Obtain",
"tokens",
"in",
"this",
"translation",
"unit",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2845-L2856
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
File.name
|
def name(self):
"""Return the complete file and path name of the file."""
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self)))
|
python
|
def name(self):
return str(conf.lib.clang_getCString(conf.lib.clang_getFileName(self)))
|
[
"def",
"name",
"(",
"self",
")",
":",
"return",
"str",
"(",
"conf",
".",
"lib",
".",
"clang_getCString",
"(",
"conf",
".",
"lib",
".",
"clang_getFileName",
"(",
"self",
")",
")",
")"
] |
Return the complete file and path name of the file.
|
[
"Return",
"the",
"complete",
"file",
"and",
"path",
"name",
"of",
"the",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2870-L2872
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
CompileCommand.arguments
|
def arguments(self):
"""
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
"""
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in xrange(length):
yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i))
|
python
|
def arguments(self):
length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
for i in xrange(length):
yield str(conf.lib.clang_CompileCommand_getArg(self.cmd, i))
|
[
"def",
"arguments",
"(",
"self",
")",
":",
"length",
"=",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getNumArgs",
"(",
"self",
".",
"cmd",
")",
"for",
"i",
"in",
"xrange",
"(",
"length",
")",
":",
"yield",
"str",
"(",
"conf",
".",
"lib",
".",
"clang_CompileCommand_getArg",
"(",
"self",
".",
"cmd",
",",
"i",
")",
")"
] |
Get an iterable object providing each argument in the
command line for the compiler invocation as a _CXString.
Invariant : the first argument is the compiler executable
|
[
"Get",
"an",
"iterable",
"object",
"providing",
"each",
"argument",
"in",
"the",
"command",
"line",
"for",
"the",
"compiler",
"invocation",
"as",
"a",
"_CXString",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L2957-L2966
|
hotdoc/hotdoc
|
hotdoc/extensions/c/clang/cindex.py
|
CompilationDatabase.fromDirectory
|
def fromDirectory(buildDir):
"""Builds a CompilationDatabase from the database found in buildDir"""
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb
|
python
|
def fromDirectory(buildDir):
errorCode = c_uint()
try:
cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
byref(errorCode))
except CompilationDatabaseError as e:
raise CompilationDatabaseError(int(errorCode.value),
"CompilationDatabase loading failed")
return cdb
|
[
"def",
"fromDirectory",
"(",
"buildDir",
")",
":",
"errorCode",
"=",
"c_uint",
"(",
")",
"try",
":",
"cdb",
"=",
"conf",
".",
"lib",
".",
"clang_CompilationDatabase_fromDirectory",
"(",
"buildDir",
",",
"byref",
"(",
"errorCode",
")",
")",
"except",
"CompilationDatabaseError",
"as",
"e",
":",
"raise",
"CompilationDatabaseError",
"(",
"int",
"(",
"errorCode",
".",
"value",
")",
",",
"\"CompilationDatabase loading failed\"",
")",
"return",
"cdb"
] |
Builds a CompilationDatabase from the database found in buildDir
|
[
"Builds",
"a",
"CompilationDatabase",
"from",
"the",
"database",
"found",
"in",
"buildDir"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/c/clang/cindex.py#L3013-L3022
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
make_translations
|
def make_translations(unique_name, node):
'''
Compute and store the title that should be displayed
when linking to a given unique_name, eg in python
when linking to test_greeter_greet() we want to display
Test.Greeter.greet
'''
introspectable = not node.attrib.get('introspectable') == '0'
if node.tag == core_ns('member'):
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
components = get_gi_name_components(node)
components[-1] = components[-1].upper()
gi_name = '.'.join(components)
__TRANSLATED_NAMES['python'][unique_name] = gi_name
__TRANSLATED_NAMES['javascript'][unique_name] = gi_name
elif c_ns('identifier') in node.attrib:
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
components = get_gi_name_components(node)
gi_name = '.'.join(components)
__TRANSLATED_NAMES['python'][unique_name] = gi_name
components[-1] = 'prototype.%s' % components[-1]
__TRANSLATED_NAMES['javascript'][unique_name] = '.'.join(components)
elif c_ns('type') in node.attrib:
components = get_gi_name_components(node)
gi_name = '.'.join(components)
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = gi_name
__TRANSLATED_NAMES['python'][unique_name] = gi_name
elif node.tag == core_ns('field'):
components = []
get_field_c_name_components(node, components)
display_name = '.'.join(components[1:])
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = display_name
__TRANSLATED_NAMES['python'][unique_name] = display_name
elif node.tag == core_ns('virtual-method'):
display_name = node.attrib['name']
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = 'vfunc_%s' % display_name
__TRANSLATED_NAMES['python'][unique_name] = 'do_%s' % display_name
elif node.tag == core_ns('property'):
display_name = node.attrib['name']
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = display_name
__TRANSLATED_NAMES['python'][unique_name] = display_name.replace('-', '_')
else:
__TRANSLATED_NAMES['c'][unique_name] = node.attrib.get('name')
if introspectable:
__TRANSLATED_NAMES['python'][unique_name] = node.attrib.get('name')
__TRANSLATED_NAMES['javascript'][unique_name] = node.attrib.get('name')
|
python
|
def make_translations(unique_name, node):
introspectable = not node.attrib.get('introspectable') == '0'
if node.tag == core_ns('member'):
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
components = get_gi_name_components(node)
components[-1] = components[-1].upper()
gi_name = '.'.join(components)
__TRANSLATED_NAMES['python'][unique_name] = gi_name
__TRANSLATED_NAMES['javascript'][unique_name] = gi_name
elif c_ns('identifier') in node.attrib:
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
components = get_gi_name_components(node)
gi_name = '.'.join(components)
__TRANSLATED_NAMES['python'][unique_name] = gi_name
components[-1] = 'prototype.%s' % components[-1]
__TRANSLATED_NAMES['javascript'][unique_name] = '.'.join(components)
elif c_ns('type') in node.attrib:
components = get_gi_name_components(node)
gi_name = '.'.join(components)
__TRANSLATED_NAMES['c'][unique_name] = unique_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = gi_name
__TRANSLATED_NAMES['python'][unique_name] = gi_name
elif node.tag == core_ns('field'):
components = []
get_field_c_name_components(node, components)
display_name = '.'.join(components[1:])
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = display_name
__TRANSLATED_NAMES['python'][unique_name] = display_name
elif node.tag == core_ns('virtual-method'):
display_name = node.attrib['name']
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = 'vfunc_%s' % display_name
__TRANSLATED_NAMES['python'][unique_name] = 'do_%s' % display_name
elif node.tag == core_ns('property'):
display_name = node.attrib['name']
__TRANSLATED_NAMES['c'][unique_name] = display_name
if introspectable:
__TRANSLATED_NAMES['javascript'][unique_name] = display_name
__TRANSLATED_NAMES['python'][unique_name] = display_name.replace('-', '_')
else:
__TRANSLATED_NAMES['c'][unique_name] = node.attrib.get('name')
if introspectable:
__TRANSLATED_NAMES['python'][unique_name] = node.attrib.get('name')
__TRANSLATED_NAMES['javascript'][unique_name] = node.attrib.get('name')
|
[
"def",
"make_translations",
"(",
"unique_name",
",",
"node",
")",
":",
"introspectable",
"=",
"not",
"node",
".",
"attrib",
".",
"get",
"(",
"'introspectable'",
")",
"==",
"'0'",
"if",
"node",
".",
"tag",
"==",
"core_ns",
"(",
"'member'",
")",
":",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"unique_name",
"if",
"introspectable",
":",
"components",
"=",
"get_gi_name_components",
"(",
"node",
")",
"components",
"[",
"-",
"1",
"]",
"=",
"components",
"[",
"-",
"1",
"]",
".",
"upper",
"(",
")",
"gi_name",
"=",
"'.'",
".",
"join",
"(",
"components",
")",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"gi_name",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"gi_name",
"elif",
"c_ns",
"(",
"'identifier'",
")",
"in",
"node",
".",
"attrib",
":",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"unique_name",
"if",
"introspectable",
":",
"components",
"=",
"get_gi_name_components",
"(",
"node",
")",
"gi_name",
"=",
"'.'",
".",
"join",
"(",
"components",
")",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"gi_name",
"components",
"[",
"-",
"1",
"]",
"=",
"'prototype.%s'",
"%",
"components",
"[",
"-",
"1",
"]",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"'.'",
".",
"join",
"(",
"components",
")",
"elif",
"c_ns",
"(",
"'type'",
")",
"in",
"node",
".",
"attrib",
":",
"components",
"=",
"get_gi_name_components",
"(",
"node",
")",
"gi_name",
"=",
"'.'",
".",
"join",
"(",
"components",
")",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"unique_name",
"if",
"introspectable",
":",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"gi_name",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"gi_name",
"elif",
"node",
".",
"tag",
"==",
"core_ns",
"(",
"'field'",
")",
":",
"components",
"=",
"[",
"]",
"get_field_c_name_components",
"(",
"node",
",",
"components",
")",
"display_name",
"=",
"'.'",
".",
"join",
"(",
"components",
"[",
"1",
":",
"]",
")",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"if",
"introspectable",
":",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"elif",
"node",
".",
"tag",
"==",
"core_ns",
"(",
"'virtual-method'",
")",
":",
"display_name",
"=",
"node",
".",
"attrib",
"[",
"'name'",
"]",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"if",
"introspectable",
":",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"'vfunc_%s'",
"%",
"display_name",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"'do_%s'",
"%",
"display_name",
"elif",
"node",
".",
"tag",
"==",
"core_ns",
"(",
"'property'",
")",
":",
"display_name",
"=",
"node",
".",
"attrib",
"[",
"'name'",
"]",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"if",
"introspectable",
":",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"display_name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"else",
":",
"__TRANSLATED_NAMES",
"[",
"'c'",
"]",
"[",
"unique_name",
"]",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
"if",
"introspectable",
":",
"__TRANSLATED_NAMES",
"[",
"'python'",
"]",
"[",
"unique_name",
"]",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
"__TRANSLATED_NAMES",
"[",
"'javascript'",
"]",
"[",
"unique_name",
"]",
"=",
"node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")"
] |
Compute and store the title that should be displayed
when linking to a given unique_name, eg in python
when linking to test_greeter_greet() we want to display
Test.Greeter.greet
|
[
"Compute",
"and",
"store",
"the",
"title",
"that",
"should",
"be",
"displayed",
"when",
"linking",
"to",
"a",
"given",
"unique_name",
"eg",
"in",
"python",
"when",
"linking",
"to",
"test_greeter_greet",
"()",
"we",
"want",
"to",
"display",
"Test",
".",
"Greeter",
".",
"greet"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L85-L141
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
get_klass_parents
|
def get_klass_parents(gi_name):
'''
Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name
'''
res = []
parents = __HIERARCHY_GRAPH.predecessors(gi_name)
if not parents:
return []
__get_parent_link_recurse(parents[0], res)
return res
|
python
|
def get_klass_parents(gi_name):
res = []
parents = __HIERARCHY_GRAPH.predecessors(gi_name)
if not parents:
return []
__get_parent_link_recurse(parents[0], res)
return res
|
[
"def",
"get_klass_parents",
"(",
"gi_name",
")",
":",
"res",
"=",
"[",
"]",
"parents",
"=",
"__HIERARCHY_GRAPH",
".",
"predecessors",
"(",
"gi_name",
")",
"if",
"not",
"parents",
":",
"return",
"[",
"]",
"__get_parent_link_recurse",
"(",
"parents",
"[",
"0",
"]",
",",
"res",
")",
"return",
"res"
] |
Returns a sorted list of qualified symbols representing
the parents of the klass-like symbol named gi_name
|
[
"Returns",
"a",
"sorted",
"list",
"of",
"qualified",
"symbols",
"representing",
"the",
"parents",
"of",
"the",
"klass",
"-",
"like",
"symbol",
"named",
"gi_name"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L173-L183
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
get_klass_children
|
def get_klass_children(gi_name):
'''
Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name
'''
res = {}
children = __HIERARCHY_GRAPH.successors(gi_name)
for gi_name in children:
ctype_name = ALL_GI_TYPES[gi_name]
qs = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)])
qs.add_extension_attribute ('gi-extension', 'type_desc',
SymbolTypeDesc([], gi_name, ctype_name, 0))
res[ctype_name] = qs
return res
|
python
|
def get_klass_children(gi_name):
res = {}
children = __HIERARCHY_GRAPH.successors(gi_name)
for gi_name in children:
ctype_name = ALL_GI_TYPES[gi_name]
qs = QualifiedSymbol(type_tokens=[Link(None, ctype_name, ctype_name)])
qs.add_extension_attribute ('gi-extension', 'type_desc',
SymbolTypeDesc([], gi_name, ctype_name, 0))
res[ctype_name] = qs
return res
|
[
"def",
"get_klass_children",
"(",
"gi_name",
")",
":",
"res",
"=",
"{",
"}",
"children",
"=",
"__HIERARCHY_GRAPH",
".",
"successors",
"(",
"gi_name",
")",
"for",
"gi_name",
"in",
"children",
":",
"ctype_name",
"=",
"ALL_GI_TYPES",
"[",
"gi_name",
"]",
"qs",
"=",
"QualifiedSymbol",
"(",
"type_tokens",
"=",
"[",
"Link",
"(",
"None",
",",
"ctype_name",
",",
"ctype_name",
")",
"]",
")",
"qs",
".",
"add_extension_attribute",
"(",
"'gi-extension'",
",",
"'type_desc'",
",",
"SymbolTypeDesc",
"(",
"[",
"]",
",",
"gi_name",
",",
"ctype_name",
",",
"0",
")",
")",
"res",
"[",
"ctype_name",
"]",
"=",
"qs",
"return",
"res"
] |
Returns a dict of qualified symbols representing
the children of the klass-like symbol named gi_name
|
[
"Returns",
"a",
"dict",
"of",
"qualified",
"symbols",
"representing",
"the",
"children",
"of",
"the",
"klass",
"-",
"like",
"symbol",
"named",
"gi_name"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L186-L199
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
cache_nodes
|
def cache_nodes(gir_root, all_girs):
'''
Identify and store all the gir symbols the symbols we will document
may link to, or be typed with
'''
ns_node = gir_root.find('./{%s}namespace' % NS_MAP['core'])
id_prefixes = ns_node.attrib['{%s}identifier-prefixes' % NS_MAP['c']]
sym_prefixes = ns_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']]
id_key = '{%s}identifier' % NS_MAP['c']
for node in gir_root.xpath(
'.//*[@c:identifier]',
namespaces=NS_MAP):
make_translations (node.attrib[id_key], node)
id_type = c_ns('type')
glib_type = glib_ns('type-name')
class_tag = core_ns('class')
callback_tag = core_ns('callback')
interface_tag = core_ns('interface')
for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]',
namespaces=NS_MAP):
try:
name = node.attrib[id_type]
except KeyError:
name = node.attrib[glib_type]
make_translations (name, node)
gi_name = '.'.join(get_gi_name_components(node))
ALL_GI_TYPES[gi_name] = get_klass_name(node)
if node.tag in (class_tag, interface_tag):
__update_hierarchies (ns_node.attrib.get('name'), node, gi_name)
make_translations('%s::%s' % (name, name), node)
__generate_smart_filters(id_prefixes, sym_prefixes, node)
elif node.tag in (callback_tag,):
ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')])
for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP):
unique_name = get_field_c_name(field)
make_translations(unique_name, field)
for node in gir_root.xpath(
'.//core:property',
namespaces=NS_MAP):
name = '%s:%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//glib:signal',
namespaces=NS_MAP):
name = '%s::%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//core:virtual-method',
namespaces=NS_MAP):
name = get_symbol_names(node)[0]
make_translations (name, node)
for inc in gir_root.findall('./core:include',
namespaces = NS_MAP):
inc_name = inc.attrib["name"]
inc_version = inc.attrib["version"]
gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs)
if not gir_file:
warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" %
(inc_name, inc_version))
continue
if gir_file in __PARSED_GIRS:
continue
__PARSED_GIRS.add(gir_file)
inc_gir_root = etree.parse(gir_file).getroot()
cache_nodes(inc_gir_root, all_girs)
|
python
|
def cache_nodes(gir_root, all_girs):
ns_node = gir_root.find('./{%s}namespace' % NS_MAP['core'])
id_prefixes = ns_node.attrib['{%s}identifier-prefixes' % NS_MAP['c']]
sym_prefixes = ns_node.attrib['{%s}symbol-prefixes' % NS_MAP['c']]
id_key = '{%s}identifier' % NS_MAP['c']
for node in gir_root.xpath(
'.//*[@c:identifier]',
namespaces=NS_MAP):
make_translations (node.attrib[id_key], node)
id_type = c_ns('type')
glib_type = glib_ns('type-name')
class_tag = core_ns('class')
callback_tag = core_ns('callback')
interface_tag = core_ns('interface')
for node in gir_root.xpath('.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]',
namespaces=NS_MAP):
try:
name = node.attrib[id_type]
except KeyError:
name = node.attrib[glib_type]
make_translations (name, node)
gi_name = '.'.join(get_gi_name_components(node))
ALL_GI_TYPES[gi_name] = get_klass_name(node)
if node.tag in (class_tag, interface_tag):
__update_hierarchies (ns_node.attrib.get('name'), node, gi_name)
make_translations('%s::%s' % (name, name), node)
__generate_smart_filters(id_prefixes, sym_prefixes, node)
elif node.tag in (callback_tag,):
ALL_CALLBACK_TYPES.add(node.attrib[c_ns('type')])
for field in gir_root.xpath('.//self::core:field', namespaces=NS_MAP):
unique_name = get_field_c_name(field)
make_translations(unique_name, field)
for node in gir_root.xpath(
'.//core:property',
namespaces=NS_MAP):
name = '%s:%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//glib:signal',
namespaces=NS_MAP):
name = '%s::%s' % (get_klass_name(node.getparent()),
node.attrib['name'])
make_translations (name, node)
for node in gir_root.xpath(
'.//core:virtual-method',
namespaces=NS_MAP):
name = get_symbol_names(node)[0]
make_translations (name, node)
for inc in gir_root.findall('./core:include',
namespaces = NS_MAP):
inc_name = inc.attrib["name"]
inc_version = inc.attrib["version"]
gir_file = __find_gir_file('%s-%s.gir' % (inc_name, inc_version), all_girs)
if not gir_file:
warn('missing-gir-include', "Couldn't find a gir for %s-%s.gir" %
(inc_name, inc_version))
continue
if gir_file in __PARSED_GIRS:
continue
__PARSED_GIRS.add(gir_file)
inc_gir_root = etree.parse(gir_file).getroot()
cache_nodes(inc_gir_root, all_girs)
|
[
"def",
"cache_nodes",
"(",
"gir_root",
",",
"all_girs",
")",
":",
"ns_node",
"=",
"gir_root",
".",
"find",
"(",
"'./{%s}namespace'",
"%",
"NS_MAP",
"[",
"'core'",
"]",
")",
"id_prefixes",
"=",
"ns_node",
".",
"attrib",
"[",
"'{%s}identifier-prefixes'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"]",
"sym_prefixes",
"=",
"ns_node",
".",
"attrib",
"[",
"'{%s}symbol-prefixes'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"]",
"id_key",
"=",
"'{%s}identifier'",
"%",
"NS_MAP",
"[",
"'c'",
"]",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//*[@c:identifier]'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"make_translations",
"(",
"node",
".",
"attrib",
"[",
"id_key",
"]",
",",
"node",
")",
"id_type",
"=",
"c_ns",
"(",
"'type'",
")",
"glib_type",
"=",
"glib_ns",
"(",
"'type-name'",
")",
"class_tag",
"=",
"core_ns",
"(",
"'class'",
")",
"callback_tag",
"=",
"core_ns",
"(",
"'callback'",
")",
"interface_tag",
"=",
"core_ns",
"(",
"'interface'",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//*[not(self::core:type) and not (self::core:array)][@c:type or @glib:type-name]'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"try",
":",
"name",
"=",
"node",
".",
"attrib",
"[",
"id_type",
"]",
"except",
"KeyError",
":",
"name",
"=",
"node",
".",
"attrib",
"[",
"glib_type",
"]",
"make_translations",
"(",
"name",
",",
"node",
")",
"gi_name",
"=",
"'.'",
".",
"join",
"(",
"get_gi_name_components",
"(",
"node",
")",
")",
"ALL_GI_TYPES",
"[",
"gi_name",
"]",
"=",
"get_klass_name",
"(",
"node",
")",
"if",
"node",
".",
"tag",
"in",
"(",
"class_tag",
",",
"interface_tag",
")",
":",
"__update_hierarchies",
"(",
"ns_node",
".",
"attrib",
".",
"get",
"(",
"'name'",
")",
",",
"node",
",",
"gi_name",
")",
"make_translations",
"(",
"'%s::%s'",
"%",
"(",
"name",
",",
"name",
")",
",",
"node",
")",
"__generate_smart_filters",
"(",
"id_prefixes",
",",
"sym_prefixes",
",",
"node",
")",
"elif",
"node",
".",
"tag",
"in",
"(",
"callback_tag",
",",
")",
":",
"ALL_CALLBACK_TYPES",
".",
"add",
"(",
"node",
".",
"attrib",
"[",
"c_ns",
"(",
"'type'",
")",
"]",
")",
"for",
"field",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//self::core:field'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"unique_name",
"=",
"get_field_c_name",
"(",
"field",
")",
"make_translations",
"(",
"unique_name",
",",
"field",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//core:property'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"'%s:%s'",
"%",
"(",
"get_klass_name",
"(",
"node",
".",
"getparent",
"(",
")",
")",
",",
"node",
".",
"attrib",
"[",
"'name'",
"]",
")",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//glib:signal'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"'%s::%s'",
"%",
"(",
"get_klass_name",
"(",
"node",
".",
"getparent",
"(",
")",
")",
",",
"node",
".",
"attrib",
"[",
"'name'",
"]",
")",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"node",
"in",
"gir_root",
".",
"xpath",
"(",
"'.//core:virtual-method'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"name",
"=",
"get_symbol_names",
"(",
"node",
")",
"[",
"0",
"]",
"make_translations",
"(",
"name",
",",
"node",
")",
"for",
"inc",
"in",
"gir_root",
".",
"findall",
"(",
"'./core:include'",
",",
"namespaces",
"=",
"NS_MAP",
")",
":",
"inc_name",
"=",
"inc",
".",
"attrib",
"[",
"\"name\"",
"]",
"inc_version",
"=",
"inc",
".",
"attrib",
"[",
"\"version\"",
"]",
"gir_file",
"=",
"__find_gir_file",
"(",
"'%s-%s.gir'",
"%",
"(",
"inc_name",
",",
"inc_version",
")",
",",
"all_girs",
")",
"if",
"not",
"gir_file",
":",
"warn",
"(",
"'missing-gir-include'",
",",
"\"Couldn't find a gir for %s-%s.gir\"",
"%",
"(",
"inc_name",
",",
"inc_version",
")",
")",
"continue",
"if",
"gir_file",
"in",
"__PARSED_GIRS",
":",
"continue",
"__PARSED_GIRS",
".",
"add",
"(",
"gir_file",
")",
"inc_gir_root",
"=",
"etree",
".",
"parse",
"(",
"gir_file",
")",
".",
"getroot",
"(",
")",
"cache_nodes",
"(",
"inc_gir_root",
",",
"all_girs",
")"
] |
Identify and store all the gir symbols the symbols we will document
may link to, or be typed with
|
[
"Identify",
"and",
"store",
"all",
"the",
"gir",
"symbols",
"the",
"symbols",
"we",
"will",
"document",
"may",
"link",
"to",
"or",
"be",
"typed",
"with"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L202-L277
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
type_description_from_node
|
def type_description_from_node(gi_node):
'''
Parse a typed node, returns a usable description
'''
ctype_name, gi_name, array_nesting = unnest_type (gi_node)
cur_ns = get_namespace(gi_node)
if ctype_name is not None:
type_tokens = __type_tokens_from_cdecl (ctype_name)
else:
type_tokens = __type_tokens_from_gitype (cur_ns, gi_name)
namespaced = '%s.%s' % (cur_ns, gi_name)
if namespaced in ALL_GI_TYPES:
gi_name = namespaced
return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting)
|
python
|
def type_description_from_node(gi_node):
ctype_name, gi_name, array_nesting = unnest_type (gi_node)
cur_ns = get_namespace(gi_node)
if ctype_name is not None:
type_tokens = __type_tokens_from_cdecl (ctype_name)
else:
type_tokens = __type_tokens_from_gitype (cur_ns, gi_name)
namespaced = '%s.%s' % (cur_ns, gi_name)
if namespaced in ALL_GI_TYPES:
gi_name = namespaced
return SymbolTypeDesc(type_tokens, gi_name, ctype_name, array_nesting)
|
[
"def",
"type_description_from_node",
"(",
"gi_node",
")",
":",
"ctype_name",
",",
"gi_name",
",",
"array_nesting",
"=",
"unnest_type",
"(",
"gi_node",
")",
"cur_ns",
"=",
"get_namespace",
"(",
"gi_node",
")",
"if",
"ctype_name",
"is",
"not",
"None",
":",
"type_tokens",
"=",
"__type_tokens_from_cdecl",
"(",
"ctype_name",
")",
"else",
":",
"type_tokens",
"=",
"__type_tokens_from_gitype",
"(",
"cur_ns",
",",
"gi_name",
")",
"namespaced",
"=",
"'%s.%s'",
"%",
"(",
"cur_ns",
",",
"gi_name",
")",
"if",
"namespaced",
"in",
"ALL_GI_TYPES",
":",
"gi_name",
"=",
"namespaced",
"return",
"SymbolTypeDesc",
"(",
"type_tokens",
",",
"gi_name",
",",
"ctype_name",
",",
"array_nesting",
")"
] |
Parse a typed node, returns a usable description
|
[
"Parse",
"a",
"typed",
"node",
"returns",
"a",
"usable",
"description"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L318-L335
|
hotdoc/hotdoc
|
hotdoc/extensions/gi/node_cache.py
|
is_introspectable
|
def is_introspectable(name, language):
'''
Do not call this before caching the nodes
'''
if name in FUNDAMENTALS[language]:
return True
if name not in __TRANSLATED_NAMES[language]:
return False
return True
|
python
|
def is_introspectable(name, language):
if name in FUNDAMENTALS[language]:
return True
if name not in __TRANSLATED_NAMES[language]:
return False
return True
|
[
"def",
"is_introspectable",
"(",
"name",
",",
"language",
")",
":",
"if",
"name",
"in",
"FUNDAMENTALS",
"[",
"language",
"]",
":",
"return",
"True",
"if",
"name",
"not",
"in",
"__TRANSLATED_NAMES",
"[",
"language",
"]",
":",
"return",
"False",
"return",
"True"
] |
Do not call this before caching the nodes
|
[
"Do",
"not",
"call",
"this",
"before",
"caching",
"the",
"nodes"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/extensions/gi/node_cache.py#L338-L348
|
hotdoc/hotdoc
|
hotdoc/core/links.py
|
dict_to_html_attrs
|
def dict_to_html_attrs(dict_):
"""
Banana banana
"""
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res
|
python
|
def dict_to_html_attrs(dict_):
res = ' '.join('%s="%s"' % (k, v) for k, v in dict_.items())
return res
|
[
"def",
"dict_to_html_attrs",
"(",
"dict_",
")",
":",
"res",
"=",
"' '",
".",
"join",
"(",
"'%s=\"%s\"'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"dict_",
".",
"items",
"(",
")",
")",
"return",
"res"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/links.py#L27-L32
|
hotdoc/hotdoc
|
hotdoc/core/links.py
|
Link.title
|
def title(self):
"""
Banana banana
"""
resolved_title = Link.resolving_title_signal(self)
resolved_title = [elem for elem in resolved_title if elem is not
None]
if resolved_title:
return str(resolved_title[0])
return self._title
|
python
|
def title(self):
resolved_title = Link.resolving_title_signal(self)
resolved_title = [elem for elem in resolved_title if elem is not
None]
if resolved_title:
return str(resolved_title[0])
return self._title
|
[
"def",
"title",
"(",
"self",
")",
":",
"resolved_title",
"=",
"Link",
".",
"resolving_title_signal",
"(",
"self",
")",
"resolved_title",
"=",
"[",
"elem",
"for",
"elem",
"in",
"resolved_title",
"if",
"elem",
"is",
"not",
"None",
"]",
"if",
"resolved_title",
":",
"return",
"str",
"(",
"resolved_title",
"[",
"0",
"]",
")",
"return",
"self",
".",
"_title"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/links.py#L53-L62
|
hotdoc/hotdoc
|
hotdoc/core/links.py
|
Link.get_link
|
def get_link(self, link_resolver):
"""
Banana banana
"""
res = link_resolver.resolving_link_signal(self)
if not res:
return self.ref, None
ref = res[0] or self.ref
if res[1]:
return ref, dict_to_html_attrs(res[1])
return ref, None
|
python
|
def get_link(self, link_resolver):
res = link_resolver.resolving_link_signal(self)
if not res:
return self.ref, None
ref = res[0] or self.ref
if res[1]:
return ref, dict_to_html_attrs(res[1])
return ref, None
|
[
"def",
"get_link",
"(",
"self",
",",
"link_resolver",
")",
":",
"res",
"=",
"link_resolver",
".",
"resolving_link_signal",
"(",
"self",
")",
"if",
"not",
"res",
":",
"return",
"self",
".",
"ref",
",",
"None",
"ref",
"=",
"res",
"[",
"0",
"]",
"or",
"self",
".",
"ref",
"if",
"res",
"[",
"1",
"]",
":",
"return",
"ref",
",",
"dict_to_html_attrs",
"(",
"res",
"[",
"1",
"]",
")",
"return",
"ref",
",",
"None"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/links.py#L76-L86
|
hotdoc/hotdoc
|
hotdoc/core/links.py
|
LinkResolver.add_link
|
def add_link(self, link):
"""
Banana banana
"""
if link.id_ not in self.__links:
self.__links[link.id_] = link
|
python
|
def add_link(self, link):
if link.id_ not in self.__links:
self.__links[link.id_] = link
|
[
"def",
"add_link",
"(",
"self",
",",
"link",
")",
":",
"if",
"link",
".",
"id_",
"not",
"in",
"self",
".",
"__links",
":",
"self",
".",
"__links",
"[",
"link",
".",
"id_",
"]",
"=",
"link"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/links.py#L143-L148
|
hotdoc/hotdoc
|
hotdoc/core/links.py
|
LinkResolver.upsert_link
|
def upsert_link(self, link, overwrite_ref=False):
"""
Banana banana
"""
elink = self.__links.get(link.id_)
if elink:
if elink.ref is None or overwrite_ref and link.ref:
elink.ref = link.ref
# pylint: disable=protected-access
if link._title is not None:
# pylint: disable=protected-access
elink.title = link._title
return elink
if not overwrite_ref:
sym = self.__doc_db.get_symbol(link.id_)
if sym and sym.link:
self.__links[link.id_] = sym.link
return sym.link
self.add_link(link)
return link
|
python
|
def upsert_link(self, link, overwrite_ref=False):
elink = self.__links.get(link.id_)
if elink:
if elink.ref is None or overwrite_ref and link.ref:
elink.ref = link.ref
if link._title is not None:
elink.title = link._title
return elink
if not overwrite_ref:
sym = self.__doc_db.get_symbol(link.id_)
if sym and sym.link:
self.__links[link.id_] = sym.link
return sym.link
self.add_link(link)
return link
|
[
"def",
"upsert_link",
"(",
"self",
",",
"link",
",",
"overwrite_ref",
"=",
"False",
")",
":",
"elink",
"=",
"self",
".",
"__links",
".",
"get",
"(",
"link",
".",
"id_",
")",
"if",
"elink",
":",
"if",
"elink",
".",
"ref",
"is",
"None",
"or",
"overwrite_ref",
"and",
"link",
".",
"ref",
":",
"elink",
".",
"ref",
"=",
"link",
".",
"ref",
"# pylint: disable=protected-access",
"if",
"link",
".",
"_title",
"is",
"not",
"None",
":",
"# pylint: disable=protected-access",
"elink",
".",
"title",
"=",
"link",
".",
"_title",
"return",
"elink",
"if",
"not",
"overwrite_ref",
":",
"sym",
"=",
"self",
".",
"__doc_db",
".",
"get_symbol",
"(",
"link",
".",
"id_",
")",
"if",
"sym",
"and",
"sym",
".",
"link",
":",
"self",
".",
"__links",
"[",
"link",
".",
"id_",
"]",
"=",
"sym",
".",
"link",
"return",
"sym",
".",
"link",
"self",
".",
"add_link",
"(",
"link",
")",
"return",
"link"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/links.py#L150-L172
|
hotdoc/hotdoc
|
hotdoc/core/inclusions.py
|
find_file
|
def find_file(filename, include_paths):
"""Banana banana
"""
if os.path.isabs(filename):
if os.path.exists(filename):
return filename
return None
for include_path in include_paths:
fpath = os.path.join(include_path, filename)
if os.path.exists(fpath) and os.path.isfile(fpath):
return fpath
return None
|
python
|
def find_file(filename, include_paths):
if os.path.isabs(filename):
if os.path.exists(filename):
return filename
return None
for include_path in include_paths:
fpath = os.path.join(include_path, filename)
if os.path.exists(fpath) and os.path.isfile(fpath):
return fpath
return None
|
[
"def",
"find_file",
"(",
"filename",
",",
"include_paths",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"return",
"filename",
"return",
"None",
"for",
"include_path",
"in",
"include_paths",
":",
"fpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"include_path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"fpath",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"fpath",
")",
":",
"return",
"fpath",
"return",
"None"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/inclusions.py#L45-L58
|
hotdoc/hotdoc
|
hotdoc/core/inclusions.py
|
resolve
|
def resolve(uri, include_paths):
"""
Banana banana
"""
include_filename, line_ranges, symbol = __parse_include(uri)
if include_filename is None:
return None
include_path = find_file(include_filename, include_paths)
if include_path is None:
return None
return __get_content(include_path.strip(),
line_ranges, symbol)
|
python
|
def resolve(uri, include_paths):
include_filename, line_ranges, symbol = __parse_include(uri)
if include_filename is None:
return None
include_path = find_file(include_filename, include_paths)
if include_path is None:
return None
return __get_content(include_path.strip(),
line_ranges, symbol)
|
[
"def",
"resolve",
"(",
"uri",
",",
"include_paths",
")",
":",
"include_filename",
",",
"line_ranges",
",",
"symbol",
"=",
"__parse_include",
"(",
"uri",
")",
"if",
"include_filename",
"is",
"None",
":",
"return",
"None",
"include_path",
"=",
"find_file",
"(",
"include_filename",
",",
"include_paths",
")",
"if",
"include_path",
"is",
"None",
":",
"return",
"None",
"return",
"__get_content",
"(",
"include_path",
".",
"strip",
"(",
")",
",",
"line_ranges",
",",
"symbol",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/inclusions.py#L94-L105
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
load_config_json
|
def load_config_json(conf_file):
"""Banana?"""
try:
with open(conf_file) as _:
try:
json_conf = json.load(_)
except ValueError as ze_error:
error('invalid-config',
'The provided configuration file %s is not valid json.\n'
'The exact error was %s.\n'
'This often happens because of missing or extra commas, '
'but it may be something else, please fix it!\n' %
(conf_file, str(ze_error)))
except FileNotFoundError:
json_conf = {}
except IOError as _err:
error('setup-issue',
'Passed config file %s could not be opened (%s)' %
(conf_file, _err))
return json_conf
|
python
|
def load_config_json(conf_file):
try:
with open(conf_file) as _:
try:
json_conf = json.load(_)
except ValueError as ze_error:
error('invalid-config',
'The provided configuration file %s is not valid json.\n'
'The exact error was %s.\n'
'This often happens because of missing or extra commas, '
'but it may be something else, please fix it!\n' %
(conf_file, str(ze_error)))
except FileNotFoundError:
json_conf = {}
except IOError as _err:
error('setup-issue',
'Passed config file %s could not be opened (%s)' %
(conf_file, _err))
return json_conf
|
[
"def",
"load_config_json",
"(",
"conf_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"conf_file",
")",
"as",
"_",
":",
"try",
":",
"json_conf",
"=",
"json",
".",
"load",
"(",
"_",
")",
"except",
"ValueError",
"as",
"ze_error",
":",
"error",
"(",
"'invalid-config'",
",",
"'The provided configuration file %s is not valid json.\\n'",
"'The exact error was %s.\\n'",
"'This often happens because of missing or extra commas, '",
"'but it may be something else, please fix it!\\n'",
"%",
"(",
"conf_file",
",",
"str",
"(",
"ze_error",
")",
")",
")",
"except",
"FileNotFoundError",
":",
"json_conf",
"=",
"{",
"}",
"except",
"IOError",
"as",
"_err",
":",
"error",
"(",
"'setup-issue'",
",",
"'Passed config file %s could not be opened (%s)'",
"%",
"(",
"conf_file",
",",
"_err",
")",
")",
"return",
"json_conf"
] |
Banana?
|
[
"Banana?"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L31-L52
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_markdown_files
|
def get_markdown_files(self, dir_):
"""
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
"""
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.path.splitext(name)
if len(split) == 1:
continue
if split[1] in ('.markdown', '.md', '.yaml'):
md_files.add(os.path.join(root, name))
return md_files
|
python
|
def get_markdown_files(self, dir_):
md_files = OrderedSet()
for root, _, files in os.walk(dir_):
for name in files:
split = os.path.splitext(name)
if len(split) == 1:
continue
if split[1] in ('.markdown', '.md', '.yaml'):
md_files.add(os.path.join(root, name))
return md_files
|
[
"def",
"get_markdown_files",
"(",
"self",
",",
"dir_",
")",
":",
"md_files",
"=",
"OrderedSet",
"(",
")",
"for",
"root",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir_",
")",
":",
"for",
"name",
"in",
"files",
":",
"split",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
"if",
"len",
"(",
"split",
")",
"==",
"1",
":",
"continue",
"if",
"split",
"[",
"1",
"]",
"in",
"(",
"'.markdown'",
",",
"'.md'",
",",
"'.yaml'",
")",
":",
"md_files",
".",
"add",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"name",
")",
")",
"return",
"md_files"
] |
Get all the markdown files in a folder, recursively
Args:
dir_: str, a toplevel folder to walk.
|
[
"Get",
"all",
"the",
"markdown",
"files",
"in",
"a",
"folder",
"recursively"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L164-L179
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get
|
def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self.__cli[key]
if key in self.__config:
return self.__config.get(key)
if key in self.__defaults:
return self.__defaults.get(key)
return default
|
python
|
def get(self, key, default=None):
if key in self.__cli:
return self.__cli[key]
if key in self.__config:
return self.__config.get(key)
if key in self.__defaults:
return self.__defaults.get(key)
return default
|
[
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"return",
"self",
".",
"__cli",
"[",
"key",
"]",
"if",
"key",
"in",
"self",
".",
"__config",
":",
"return",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"if",
"key",
"in",
"self",
".",
"__defaults",
":",
"return",
"self",
".",
"__defaults",
".",
"get",
"(",
"key",
")",
"return",
"default"
] |
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
|
[
"Get",
"the",
"value",
"for",
"key",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L187-L205
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_index
|
def get_index(self, prefix=''):
"""
Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None`
"""
if prefix:
prefixed = '%s_index' % prefix
else:
prefixed = 'index'
if prefixed in self.__cli and self.__cli[prefixed]:
index = self.__cli.get(prefixed)
from_conf = False
else:
index = self.__config.get(prefixed)
from_conf = True
return self.__abspath(index, from_conf)
|
python
|
def get_index(self, prefix=''):
if prefix:
prefixed = '%s_index' % prefix
else:
prefixed = 'index'
if prefixed in self.__cli and self.__cli[prefixed]:
index = self.__cli.get(prefixed)
from_conf = False
else:
index = self.__config.get(prefixed)
from_conf = True
return self.__abspath(index, from_conf)
|
[
"def",
"get_index",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"if",
"prefix",
":",
"prefixed",
"=",
"'%s_index'",
"%",
"prefix",
"else",
":",
"prefixed",
"=",
"'index'",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
"and",
"self",
".",
"__cli",
"[",
"prefixed",
"]",
":",
"index",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"index",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"return",
"self",
".",
"__abspath",
"(",
"index",
",",
"from_conf",
")"
] |
Retrieve the absolute path to an index, according to
`prefix`.
Args:
prefix: str, the desired prefix or `None`.
Returns:
str: An absolute path, or `None`
|
[
"Retrieve",
"the",
"absolute",
"path",
"to",
"an",
"index",
"according",
"to",
"prefix",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L207-L230
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_path
|
def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
"""
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None`
"""
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
res = self.__abspath(path, from_conf)
if rel_to_cwd:
return os.path.relpath(res, self.__invoke_dir)
if rel_to_conf:
return os.path.relpath(res, self.__conf_dir)
return self.__abspath(path, from_conf)
|
python
|
def get_path(self, key, rel_to_cwd=False, rel_to_conf=False):
if key in self.__cli:
path = self.__cli[key]
from_conf = False
else:
path = self.__config.get(key)
from_conf = True
if not isinstance(path, str):
return None
res = self.__abspath(path, from_conf)
if rel_to_cwd:
return os.path.relpath(res, self.__invoke_dir)
if rel_to_conf:
return os.path.relpath(res, self.__conf_dir)
return self.__abspath(path, from_conf)
|
[
"def",
"get_path",
"(",
"self",
",",
"key",
",",
"rel_to_cwd",
"=",
"False",
",",
"rel_to_conf",
"=",
"False",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"path",
"=",
"self",
".",
"__cli",
"[",
"key",
"]",
"from_conf",
"=",
"False",
"else",
":",
"path",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"from_conf",
"=",
"True",
"if",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"None",
"res",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")",
"if",
"rel_to_cwd",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"res",
",",
"self",
".",
"__invoke_dir",
")",
"if",
"rel_to_conf",
":",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"res",
",",
"self",
".",
"__conf_dir",
")",
"return",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")"
] |
Retrieve a path from the config, resolving it against
the invokation directory or the configuration file directory,
depending on whether it was passed through the command-line
or the configuration file.
Args:
key: str, the key to lookup the path with
Returns:
str: The path, or `None`
|
[
"Retrieve",
"a",
"path",
"from",
"the",
"config",
"resolving",
"it",
"against",
"the",
"invokation",
"directory",
"or",
"the",
"configuration",
"file",
"directory",
"depending",
"on",
"whether",
"it",
"was",
"passed",
"through",
"the",
"command",
"-",
"line",
"or",
"the",
"configuration",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L232-L262
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_paths
|
def get_paths(self, key):
"""
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
"""
final_paths = []
if key in self.__cli:
paths = self.__cli[key] or []
from_conf = False
else:
paths = self.__config.get(key) or []
from_conf = True
for path in flatten_list(paths):
final_path = self.__abspath(path, from_conf)
if final_path:
final_paths.append(final_path)
return final_paths
|
python
|
def get_paths(self, key):
final_paths = []
if key in self.__cli:
paths = self.__cli[key] or []
from_conf = False
else:
paths = self.__config.get(key) or []
from_conf = True
for path in flatten_list(paths):
final_path = self.__abspath(path, from_conf)
if final_path:
final_paths.append(final_path)
return final_paths
|
[
"def",
"get_paths",
"(",
"self",
",",
"key",
")",
":",
"final_paths",
"=",
"[",
"]",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"paths",
"=",
"self",
".",
"__cli",
"[",
"key",
"]",
"or",
"[",
"]",
"from_conf",
"=",
"False",
"else",
":",
"paths",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"key",
")",
"or",
"[",
"]",
"from_conf",
"=",
"True",
"for",
"path",
"in",
"flatten_list",
"(",
"paths",
")",
":",
"final_path",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
")",
"if",
"final_path",
":",
"final_paths",
".",
"append",
"(",
"final_path",
")",
"return",
"final_paths"
] |
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
|
[
"Same",
"as",
"ConfigParser",
".",
"get_path",
"for",
"a",
"list",
"of",
"paths",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L264-L288
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_sources
|
def get_sources(self, prefix=''):
"""
Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The set of sources for the given
`prefix`.
"""
prefix = prefix.replace('-', '_')
prefixed = '%s_sources' % prefix
if prefixed in self.__cli:
sources = self.__cli.get(prefixed)
from_conf = False
else:
sources = self.__config.get(prefixed)
from_conf = True
if sources is None:
return OrderedSet()
sources = self.__resolve_patterns(sources, from_conf)
prefixed = '%s_source_filters' % prefix
if prefixed in self.__cli:
filters = self.__cli.get(prefixed)
from_conf = False
else:
filters = self.__config.get(prefixed)
from_conf = True
if filters is None:
return sources
sources -= self.__resolve_patterns(filters, from_conf)
return sources
|
python
|
def get_sources(self, prefix=''):
prefix = prefix.replace('-', '_')
prefixed = '%s_sources' % prefix
if prefixed in self.__cli:
sources = self.__cli.get(prefixed)
from_conf = False
else:
sources = self.__config.get(prefixed)
from_conf = True
if sources is None:
return OrderedSet()
sources = self.__resolve_patterns(sources, from_conf)
prefixed = '%s_source_filters' % prefix
if prefixed in self.__cli:
filters = self.__cli.get(prefixed)
from_conf = False
else:
filters = self.__config.get(prefixed)
from_conf = True
if filters is None:
return sources
sources -= self.__resolve_patterns(filters, from_conf)
return sources
|
[
"def",
"get_sources",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"prefix",
"=",
"prefix",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"prefixed",
"=",
"'%s_sources'",
"%",
"prefix",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
":",
"sources",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"sources",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"if",
"sources",
"is",
"None",
":",
"return",
"OrderedSet",
"(",
")",
"sources",
"=",
"self",
".",
"__resolve_patterns",
"(",
"sources",
",",
"from_conf",
")",
"prefixed",
"=",
"'%s_source_filters'",
"%",
"prefix",
"if",
"prefixed",
"in",
"self",
".",
"__cli",
":",
"filters",
"=",
"self",
".",
"__cli",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"False",
"else",
":",
"filters",
"=",
"self",
".",
"__config",
".",
"get",
"(",
"prefixed",
")",
"from_conf",
"=",
"True",
"if",
"filters",
"is",
"None",
":",
"return",
"sources",
"sources",
"-=",
"self",
".",
"__resolve_patterns",
"(",
"filters",
",",
"from_conf",
")",
"return",
"sources"
] |
Retrieve a set of absolute paths to sources, according to `prefix`
`ConfigParser` will perform wildcard expansion and
filtering.
Args:
prefix: str, the desired prefix.
Returns:
utils.utils.OrderedSet: The set of sources for the given
`prefix`.
|
[
"Retrieve",
"a",
"set",
"of",
"absolute",
"paths",
"to",
"sources",
"according",
"to",
"prefix"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L290-L332
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.get_dependencies
|
def get_dependencies(self):
"""
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
"""
all_deps = OrderedSet()
for key, _ in list(self.__config.items()):
if key in self.__cli:
continue
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
for key, _ in list(self.__cli.items()):
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
if self.conf_file is not None:
all_deps.add(self.conf_file)
all_deps.add(self.get_path("sitemap", rel_to_cwd=True))
cwd = os.getcwd()
return [os.path.relpath(fname, cwd) for fname in all_deps if fname]
|
python
|
def get_dependencies(self):
all_deps = OrderedSet()
for key, _ in list(self.__config.items()):
if key in self.__cli:
continue
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
for key, _ in list(self.__cli.items()):
if key.endswith('sources'):
all_deps |= self.get_sources(key[:len('sources') * -1 - 1])
if self.conf_file is not None:
all_deps.add(self.conf_file)
all_deps.add(self.get_path("sitemap", rel_to_cwd=True))
cwd = os.getcwd()
return [os.path.relpath(fname, cwd) for fname in all_deps if fname]
|
[
"def",
"get_dependencies",
"(",
"self",
")",
":",
"all_deps",
"=",
"OrderedSet",
"(",
")",
"for",
"key",
",",
"_",
"in",
"list",
"(",
"self",
".",
"__config",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"continue",
"if",
"key",
".",
"endswith",
"(",
"'sources'",
")",
":",
"all_deps",
"|=",
"self",
".",
"get_sources",
"(",
"key",
"[",
":",
"len",
"(",
"'sources'",
")",
"*",
"-",
"1",
"-",
"1",
"]",
")",
"for",
"key",
",",
"_",
"in",
"list",
"(",
"self",
".",
"__cli",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'sources'",
")",
":",
"all_deps",
"|=",
"self",
".",
"get_sources",
"(",
"key",
"[",
":",
"len",
"(",
"'sources'",
")",
"*",
"-",
"1",
"-",
"1",
"]",
")",
"if",
"self",
".",
"conf_file",
"is",
"not",
"None",
":",
"all_deps",
".",
"add",
"(",
"self",
".",
"conf_file",
")",
"all_deps",
".",
"add",
"(",
"self",
".",
"get_path",
"(",
"\"sitemap\"",
",",
"rel_to_cwd",
"=",
"True",
")",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"return",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"fname",
",",
"cwd",
")",
"for",
"fname",
"in",
"all_deps",
"if",
"fname",
"]"
] |
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
|
[
"Retrieve",
"the",
"set",
"of",
"all",
"dependencies",
"for",
"a",
"given",
"configuration",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L334-L360
|
hotdoc/hotdoc
|
hotdoc/core/config.py
|
Config.dump
|
def dump(self, conf_file=None):
"""
Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration.
"""
if conf_file:
conf_dir = os.path.dirname(conf_file)
if not conf_dir:
conf_dir = self.__invoke_dir
elif not os.path.exists(conf_dir):
os.makedirs(conf_dir)
else:
conf_dir = self.__conf_dir
final_conf = {}
for key, value in list(self.__config.items()):
if key in self.__cli:
continue
final_conf[key] = value
for key, value in list(self.__cli.items()):
if key.endswith('index') or key in ['sitemap', 'output']:
path = self.__abspath(value, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
final_conf[key] = relpath
elif key.endswith('sources') or key.endswith('source_filters'):
new_list = []
for path in value:
path = self.__abspath(path, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
new_list.append(relpath)
final_conf[key] = new_list
elif key not in ['command', 'output_conf_file']:
final_conf[key] = value
with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _:
_.write(json.dumps(final_conf, sort_keys=True, indent=4))
|
python
|
def dump(self, conf_file=None):
if conf_file:
conf_dir = os.path.dirname(conf_file)
if not conf_dir:
conf_dir = self.__invoke_dir
elif not os.path.exists(conf_dir):
os.makedirs(conf_dir)
else:
conf_dir = self.__conf_dir
final_conf = {}
for key, value in list(self.__config.items()):
if key in self.__cli:
continue
final_conf[key] = value
for key, value in list(self.__cli.items()):
if key.endswith('index') or key in ['sitemap', 'output']:
path = self.__abspath(value, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
final_conf[key] = relpath
elif key.endswith('sources') or key.endswith('source_filters'):
new_list = []
for path in value:
path = self.__abspath(path, from_conf=False)
if path:
relpath = os.path.relpath(path, conf_dir)
new_list.append(relpath)
final_conf[key] = new_list
elif key not in ['command', 'output_conf_file']:
final_conf[key] = value
with open(conf_file or self.conf_file or 'hotdoc.json', 'w') as _:
_.write(json.dumps(final_conf, sort_keys=True, indent=4))
|
[
"def",
"dump",
"(",
"self",
",",
"conf_file",
"=",
"None",
")",
":",
"if",
"conf_file",
":",
"conf_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"conf_file",
")",
"if",
"not",
"conf_dir",
":",
"conf_dir",
"=",
"self",
".",
"__invoke_dir",
"elif",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"conf_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"conf_dir",
")",
"else",
":",
"conf_dir",
"=",
"self",
".",
"__conf_dir",
"final_conf",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"__config",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"in",
"self",
".",
"__cli",
":",
"continue",
"final_conf",
"[",
"key",
"]",
"=",
"value",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"self",
".",
"__cli",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'index'",
")",
"or",
"key",
"in",
"[",
"'sitemap'",
",",
"'output'",
"]",
":",
"path",
"=",
"self",
".",
"__abspath",
"(",
"value",
",",
"from_conf",
"=",
"False",
")",
"if",
"path",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"conf_dir",
")",
"final_conf",
"[",
"key",
"]",
"=",
"relpath",
"elif",
"key",
".",
"endswith",
"(",
"'sources'",
")",
"or",
"key",
".",
"endswith",
"(",
"'source_filters'",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"path",
"in",
"value",
":",
"path",
"=",
"self",
".",
"__abspath",
"(",
"path",
",",
"from_conf",
"=",
"False",
")",
"if",
"path",
":",
"relpath",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"conf_dir",
")",
"new_list",
".",
"append",
"(",
"relpath",
")",
"final_conf",
"[",
"key",
"]",
"=",
"new_list",
"elif",
"key",
"not",
"in",
"[",
"'command'",
",",
"'output_conf_file'",
"]",
":",
"final_conf",
"[",
"key",
"]",
"=",
"value",
"with",
"open",
"(",
"conf_file",
"or",
"self",
".",
"conf_file",
"or",
"'hotdoc.json'",
",",
"'w'",
")",
"as",
"_",
":",
"_",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"final_conf",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
")",
")"
] |
Dump the possibly updated config to a file.
Args:
conf_file: str, the destination, or None to overwrite the
existing configuration.
|
[
"Dump",
"the",
"possibly",
"updated",
"config",
"to",
"a",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/config.py#L363-L405
|
hotdoc/hotdoc
|
hotdoc/utils/setup_utils.py
|
_check_submodule_status
|
def _check_submodule_status(root, submodules):
"""check submodule status
Has three return values:
'missing' - submodules are absent
'unclean' - submodules have unstaged changes
'clean' - all submodules are up to date
"""
if hasattr(sys, "frozen"):
# frozen via py2exe or similar, don't bother
return 'clean'
if not os.path.exists(os.path.join(root, '.git')):
# not in git, assume clean
return 'clean'
for submodule in submodules:
if not os.path.exists(submodule):
return 'missing'
# Popen can't handle unicode cwd on Windows Python 2
if sys.platform == 'win32' and sys.version_info[0] < 3 \
and not isinstance(root, bytes):
root = root.encode(sys.getfilesystemencoding() or 'ascii')
# check with git submodule status
proc = subprocess.Popen('git submodule status',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=root)
status, _ = proc.communicate()
status = status.decode("ascii", "replace")
for line in status.splitlines():
if line.startswith('-'):
return 'missing'
elif line.startswith('+'):
return 'unclean'
return 'clean'
|
python
|
def _check_submodule_status(root, submodules):
if hasattr(sys, "frozen"):
return 'clean'
if not os.path.exists(os.path.join(root, '.git')):
return 'clean'
for submodule in submodules:
if not os.path.exists(submodule):
return 'missing'
if sys.platform == 'win32' and sys.version_info[0] < 3 \
and not isinstance(root, bytes):
root = root.encode(sys.getfilesystemencoding() or 'ascii')
proc = subprocess.Popen('git submodule status',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
cwd=root)
status, _ = proc.communicate()
status = status.decode("ascii", "replace")
for line in status.splitlines():
if line.startswith('-'):
return 'missing'
elif line.startswith('+'):
return 'unclean'
return 'clean'
|
[
"def",
"_check_submodule_status",
"(",
"root",
",",
"submodules",
")",
":",
"if",
"hasattr",
"(",
"sys",
",",
"\"frozen\"",
")",
":",
"# frozen via py2exe or similar, don't bother",
"return",
"'clean'",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"'.git'",
")",
")",
":",
"# not in git, assume clean",
"return",
"'clean'",
"for",
"submodule",
"in",
"submodules",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"submodule",
")",
":",
"return",
"'missing'",
"# Popen can't handle unicode cwd on Windows Python 2",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"and",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"and",
"not",
"isinstance",
"(",
"root",
",",
"bytes",
")",
":",
"root",
"=",
"root",
".",
"encode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
"or",
"'ascii'",
")",
"# check with git submodule status",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"'git submodule status'",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"shell",
"=",
"True",
",",
"cwd",
"=",
"root",
")",
"status",
",",
"_",
"=",
"proc",
".",
"communicate",
"(",
")",
"status",
"=",
"status",
".",
"decode",
"(",
"\"ascii\"",
",",
"\"replace\"",
")",
"for",
"line",
"in",
"status",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'-'",
")",
":",
"return",
"'missing'",
"elif",
"line",
".",
"startswith",
"(",
"'+'",
")",
":",
"return",
"'unclean'",
"return",
"'clean'"
] |
check submodule status
Has three return values:
'missing' - submodules are absent
'unclean' - submodules have unstaged changes
'clean' - all submodules are up to date
|
[
"check",
"submodule",
"status",
"Has",
"three",
"return",
"values",
":",
"missing",
"-",
"submodules",
"are",
"absent",
"unclean",
"-",
"submodules",
"have",
"unstaged",
"changes",
"clean",
"-",
"all",
"submodules",
"are",
"up",
"to",
"date"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L33-L72
|
hotdoc/hotdoc
|
hotdoc/utils/setup_utils.py
|
_update_submodules
|
def _update_submodules(repo_dir):
"""update submodules in a repo"""
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True)
|
python
|
def _update_submodules(repo_dir):
subprocess.check_call("git submodule init", cwd=repo_dir, shell=True)
subprocess.check_call(
"git submodule update --recursive", cwd=repo_dir, shell=True)
|
[
"def",
"_update_submodules",
"(",
"repo_dir",
")",
":",
"subprocess",
".",
"check_call",
"(",
"\"git submodule init\"",
",",
"cwd",
"=",
"repo_dir",
",",
"shell",
"=",
"True",
")",
"subprocess",
".",
"check_call",
"(",
"\"git submodule update --recursive\"",
",",
"cwd",
"=",
"repo_dir",
",",
"shell",
"=",
"True",
")"
] |
update submodules in a repo
|
[
"update",
"submodules",
"in",
"a",
"repo"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L75-L79
|
hotdoc/hotdoc
|
hotdoc/utils/setup_utils.py
|
require_clean_submodules
|
def require_clean_submodules(repo_root, submodules):
"""Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command.
"""
# PACKAGERS: Add a return here to skip checks for git submodules
# don't do anything if nothing is actually supposed to happen
for do_nothing in (
'-h', '--help', '--help-commands', 'clean', 'submodule'):
if do_nothing in sys.argv:
return
status = _check_submodule_status(repo_root, submodules)
if status == "missing":
print("checking out submodules for the first time")
_update_submodules(repo_root)
elif status == "unclean":
print(UNCLEAN_SUBMODULES_MSG)
|
python
|
def require_clean_submodules(repo_root, submodules):
for do_nothing in (
'-h', '--help', '--help-commands', 'clean', 'submodule'):
if do_nothing in sys.argv:
return
status = _check_submodule_status(repo_root, submodules)
if status == "missing":
print("checking out submodules for the first time")
_update_submodules(repo_root)
elif status == "unclean":
print(UNCLEAN_SUBMODULES_MSG)
|
[
"def",
"require_clean_submodules",
"(",
"repo_root",
",",
"submodules",
")",
":",
"# PACKAGERS: Add a return here to skip checks for git submodules",
"# don't do anything if nothing is actually supposed to happen",
"for",
"do_nothing",
"in",
"(",
"'-h'",
",",
"'--help'",
",",
"'--help-commands'",
",",
"'clean'",
",",
"'submodule'",
")",
":",
"if",
"do_nothing",
"in",
"sys",
".",
"argv",
":",
"return",
"status",
"=",
"_check_submodule_status",
"(",
"repo_root",
",",
"submodules",
")",
"if",
"status",
"==",
"\"missing\"",
":",
"print",
"(",
"\"checking out submodules for the first time\"",
")",
"_update_submodules",
"(",
"repo_root",
")",
"elif",
"status",
"==",
"\"unclean\"",
":",
"print",
"(",
"UNCLEAN_SUBMODULES_MSG",
")"
] |
Check on git submodules before distutils can do anything
Since distutils cannot be trusted to update the tree
after everything has been set in motion,
this is not a distutils command.
|
[
"Check",
"on",
"git",
"submodules",
"before",
"distutils",
"can",
"do",
"anything",
"Since",
"distutils",
"cannot",
"be",
"trusted",
"to",
"update",
"the",
"tree",
"after",
"everything",
"has",
"been",
"set",
"in",
"motion",
"this",
"is",
"not",
"a",
"distutils",
"command",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L93-L113
|
hotdoc/hotdoc
|
hotdoc/utils/setup_utils.py
|
symlink
|
def symlink(source, link_name):
"""
Method to allow creating symlinks on Windows
"""
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError()
|
python
|
def symlink(source, link_name):
if os.path.islink(link_name) and os.readlink(link_name) == source:
return
os_symlink = getattr(os, "symlink", None)
if callable(os_symlink):
os_symlink(source, link_name)
else:
import ctypes
csl = ctypes.windll.kernel32.CreateSymbolicLinkW
csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
csl.restype = ctypes.c_ubyte
flags = 1 if os.path.isdir(source) else 0
if csl(link_name, source, flags) == 0:
raise ctypes.WinError()
|
[
"def",
"symlink",
"(",
"source",
",",
"link_name",
")",
":",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"link_name",
")",
"and",
"os",
".",
"readlink",
"(",
"link_name",
")",
"==",
"source",
":",
"return",
"os_symlink",
"=",
"getattr",
"(",
"os",
",",
"\"symlink\"",
",",
"None",
")",
"if",
"callable",
"(",
"os_symlink",
")",
":",
"os_symlink",
"(",
"source",
",",
"link_name",
")",
"else",
":",
"import",
"ctypes",
"csl",
"=",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"CreateSymbolicLinkW",
"csl",
".",
"argtypes",
"=",
"(",
"ctypes",
".",
"c_wchar_p",
",",
"ctypes",
".",
"c_wchar_p",
",",
"ctypes",
".",
"c_uint32",
")",
"csl",
".",
"restype",
"=",
"ctypes",
".",
"c_ubyte",
"flags",
"=",
"1",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source",
")",
"else",
"0",
"if",
"csl",
"(",
"link_name",
",",
"source",
",",
"flags",
")",
"==",
"0",
":",
"raise",
"ctypes",
".",
"WinError",
"(",
")"
] |
Method to allow creating symlinks on Windows
|
[
"Method",
"to",
"allow",
"creating",
"symlinks",
"on",
"Windows"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L116-L133
|
hotdoc/hotdoc
|
hotdoc/utils/setup_utils.py
|
pkgconfig
|
def pkgconfig(*packages, **kw):
"""
Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
returns e.g.
{'extra_compile_args': [],
'extra_link_args': [],
'include_dirs': ['/usr/include/ffmpeg'],
'libraries': ['avformat'],
'library_dirs': []}
Intended use:
distutils.core.Extension('pyextension', sources=['source.cpp'], **c)
Set PKG_CONFIG_PATH environment variable for nonstandard library locations.
based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/)
"""
config = kw.setdefault('config', {})
optional_args = kw.setdefault('optional', '')
# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}
flag_map = {'include_dirs': ['--cflags-only-I', 2],
'library_dirs': ['--libs-only-L', 2],
'libraries': ['--libs-only-l', 2],
'extra_compile_args': ['--cflags-only-other', 0],
'extra_link_args': ['--libs-only-other', 0],
}
for package in packages:
for distutils_key, (pkg_option, n) in flag_map.items():
items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split()
config.setdefault(distutils_key, []).extend([i[n:] for i in items])
return config
|
python
|
def pkgconfig(*packages, **kw):
config = kw.setdefault('config', {})
optional_args = kw.setdefault('optional', '')
flag_map = {'include_dirs': ['--cflags-only-I', 2],
'library_dirs': ['--libs-only-L', 2],
'libraries': ['--libs-only-l', 2],
'extra_compile_args': ['--cflags-only-other', 0],
'extra_link_args': ['--libs-only-other', 0],
}
for package in packages:
for distutils_key, (pkg_option, n) in flag_map.items():
items = subprocess.check_output(['pkg-config', optional_args, pkg_option, package]).decode('utf8').split()
config.setdefault(distutils_key, []).extend([i[n:] for i in items])
return config
|
[
"def",
"pkgconfig",
"(",
"*",
"packages",
",",
"*",
"*",
"kw",
")",
":",
"config",
"=",
"kw",
".",
"setdefault",
"(",
"'config'",
",",
"{",
"}",
")",
"optional_args",
"=",
"kw",
".",
"setdefault",
"(",
"'optional'",
",",
"''",
")",
"# { <distutils Extension arg>: [<pkg config option>, <prefix length to strip>], ...}",
"flag_map",
"=",
"{",
"'include_dirs'",
":",
"[",
"'--cflags-only-I'",
",",
"2",
"]",
",",
"'library_dirs'",
":",
"[",
"'--libs-only-L'",
",",
"2",
"]",
",",
"'libraries'",
":",
"[",
"'--libs-only-l'",
",",
"2",
"]",
",",
"'extra_compile_args'",
":",
"[",
"'--cflags-only-other'",
",",
"0",
"]",
",",
"'extra_link_args'",
":",
"[",
"'--libs-only-other'",
",",
"0",
"]",
",",
"}",
"for",
"package",
"in",
"packages",
":",
"for",
"distutils_key",
",",
"(",
"pkg_option",
",",
"n",
")",
"in",
"flag_map",
".",
"items",
"(",
")",
":",
"items",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'pkg-config'",
",",
"optional_args",
",",
"pkg_option",
",",
"package",
"]",
")",
".",
"decode",
"(",
"'utf8'",
")",
".",
"split",
"(",
")",
"config",
".",
"setdefault",
"(",
"distutils_key",
",",
"[",
"]",
")",
".",
"extend",
"(",
"[",
"i",
"[",
"n",
":",
"]",
"for",
"i",
"in",
"items",
"]",
")",
"return",
"config"
] |
Query pkg-config for library compile and linking options. Return configuration in distutils
Extension format.
Usage:
pkgconfig('opencv')
pkgconfig('opencv', 'libavformat')
pkgconfig('opencv', optional='--static')
pkgconfig('opencv', config=c)
returns e.g.
{'extra_compile_args': [],
'extra_link_args': [],
'include_dirs': ['/usr/include/ffmpeg'],
'libraries': ['avformat'],
'library_dirs': []}
Intended use:
distutils.core.Extension('pyextension', sources=['source.cpp'], **c)
Set PKG_CONFIG_PATH environment variable for nonstandard library locations.
based on work of Micah Dowty (http://code.activestate.com/recipes/502261-python-distutils-pkg-config/)
|
[
"Query",
"pkg",
"-",
"config",
"for",
"library",
"compile",
"and",
"linking",
"options",
".",
"Return",
"configuration",
"in",
"distutils",
"Extension",
"format",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/setup_utils.py#L135-L180
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.register_error_code
|
def register_error_code(code, exception_type, domain='core'):
"""Register a new error code"""
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code)
|
python
|
def register_error_code(code, exception_type, domain='core'):
Logger._error_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code)
|
[
"def",
"register_error_code",
"(",
"code",
",",
"exception_type",
",",
"domain",
"=",
"'core'",
")",
":",
"Logger",
".",
"_error_code_to_exception",
"[",
"code",
"]",
"=",
"(",
"exception_type",
",",
"domain",
")",
"Logger",
".",
"_domain_codes",
"[",
"domain",
"]",
".",
"add",
"(",
"code",
")"
] |
Register a new error code
|
[
"Register",
"a",
"new",
"error",
"code"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L201-L204
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.register_warning_code
|
def register_warning_code(code, exception_type, domain='core'):
"""Register a new warning code"""
Logger._warning_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code)
|
python
|
def register_warning_code(code, exception_type, domain='core'):
Logger._warning_code_to_exception[code] = (exception_type, domain)
Logger._domain_codes[domain].add(code)
|
[
"def",
"register_warning_code",
"(",
"code",
",",
"exception_type",
",",
"domain",
"=",
"'core'",
")",
":",
"Logger",
".",
"_warning_code_to_exception",
"[",
"code",
"]",
"=",
"(",
"exception_type",
",",
"domain",
")",
"Logger",
".",
"_domain_codes",
"[",
"domain",
"]",
".",
"add",
"(",
"code",
")"
] |
Register a new warning code
|
[
"Register",
"a",
"new",
"warning",
"code"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L207-L210
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger._log
|
def _log(code, message, level, domain):
"""Call this to add an entry in the journal"""
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry)
|
python
|
def _log(code, message, level, domain):
entry = LogEntry(level, domain, code, message)
Logger.journal.append(entry)
if Logger.silent:
return
if level >= Logger._verbosity:
_print_entry(entry)
|
[
"def",
"_log",
"(",
"code",
",",
"message",
",",
"level",
",",
"domain",
")",
":",
"entry",
"=",
"LogEntry",
"(",
"level",
",",
"domain",
",",
"code",
",",
"message",
")",
"Logger",
".",
"journal",
".",
"append",
"(",
"entry",
")",
"if",
"Logger",
".",
"silent",
":",
"return",
"if",
"level",
">=",
"Logger",
".",
"_verbosity",
":",
"_print_entry",
"(",
"entry",
")"
] |
Call this to add an entry in the journal
|
[
"Call",
"this",
"to",
"add",
"an",
"entry",
"in",
"the",
"journal"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L213-L222
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.error
|
def error(code, message, **kwargs):
"""Call this to raise an exception and have it stored in the journal"""
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERROR, domain)
raise exc
|
python
|
def error(code, message, **kwargs):
assert code in Logger._error_code_to_exception
exc_type, domain = Logger._error_code_to_exception[code]
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, ERROR, domain)
raise exc
|
[
"def",
"error",
"(",
"code",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"code",
"in",
"Logger",
".",
"_error_code_to_exception",
"exc_type",
",",
"domain",
"=",
"Logger",
".",
"_error_code_to_exception",
"[",
"code",
"]",
"exc",
"=",
"exc_type",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
"Logger",
".",
"_log",
"(",
"code",
",",
"exc",
".",
"message",
",",
"ERROR",
",",
"domain",
")",
"raise",
"exc"
] |
Call this to raise an exception and have it stored in the journal
|
[
"Call",
"this",
"to",
"raise",
"an",
"exception",
"and",
"have",
"it",
"stored",
"in",
"the",
"journal"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L225-L231
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.warn
|
def warn(code, message, **kwargs):
"""
Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True.
"""
if code in Logger._ignored_codes:
return
assert code in Logger._warning_code_to_exception
exc_type, domain = Logger._warning_code_to_exception[code]
if domain in Logger._ignored_domains:
return
level = WARNING
if Logger.fatal_warnings:
level = ERROR
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, level, domain)
if Logger.fatal_warnings:
raise exc
|
python
|
def warn(code, message, **kwargs):
if code in Logger._ignored_codes:
return
assert code in Logger._warning_code_to_exception
exc_type, domain = Logger._warning_code_to_exception[code]
if domain in Logger._ignored_domains:
return
level = WARNING
if Logger.fatal_warnings:
level = ERROR
exc = exc_type(message, **kwargs)
Logger._log(code, exc.message, level, domain)
if Logger.fatal_warnings:
raise exc
|
[
"def",
"warn",
"(",
"code",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"code",
"in",
"Logger",
".",
"_ignored_codes",
":",
"return",
"assert",
"code",
"in",
"Logger",
".",
"_warning_code_to_exception",
"exc_type",
",",
"domain",
"=",
"Logger",
".",
"_warning_code_to_exception",
"[",
"code",
"]",
"if",
"domain",
"in",
"Logger",
".",
"_ignored_domains",
":",
"return",
"level",
"=",
"WARNING",
"if",
"Logger",
".",
"fatal_warnings",
":",
"level",
"=",
"ERROR",
"exc",
"=",
"exc_type",
"(",
"message",
",",
"*",
"*",
"kwargs",
")",
"Logger",
".",
"_log",
"(",
"code",
",",
"exc",
".",
"message",
",",
"level",
",",
"domain",
")",
"if",
"Logger",
".",
"fatal_warnings",
":",
"raise",
"exc"
] |
Call this to store a warning in the journal.
Will raise if `Logger.fatal_warnings` is set to True.
|
[
"Call",
"this",
"to",
"store",
"a",
"warning",
"in",
"the",
"journal",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L234-L259
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.debug
|
def debug(message, domain):
"""Log debugging information"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, DEBUG, domain)
|
python
|
def debug(message, domain):
if domain in Logger._ignored_domains:
return
Logger._log(None, message, DEBUG, domain)
|
[
"def",
"debug",
"(",
"message",
",",
"domain",
")",
":",
"if",
"domain",
"in",
"Logger",
".",
"_ignored_domains",
":",
"return",
"Logger",
".",
"_log",
"(",
"None",
",",
"message",
",",
"DEBUG",
",",
"domain",
")"
] |
Log debugging information
|
[
"Log",
"debugging",
"information"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L262-L267
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.info
|
def info(message, domain):
"""Log simple info"""
if domain in Logger._ignored_domains:
return
Logger._log(None, message, INFO, domain)
|
python
|
def info(message, domain):
if domain in Logger._ignored_domains:
return
Logger._log(None, message, INFO, domain)
|
[
"def",
"info",
"(",
"message",
",",
"domain",
")",
":",
"if",
"domain",
"in",
"Logger",
".",
"_ignored_domains",
":",
"return",
"Logger",
".",
"_log",
"(",
"None",
",",
"message",
",",
"INFO",
",",
"domain",
")"
] |
Log simple info
|
[
"Log",
"simple",
"info"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L270-L275
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.get_issues
|
def get_issues():
"""Get actual issues in the journal."""
issues = []
for entry in Logger.journal:
if entry.level >= WARNING:
issues.append(entry)
return issues
|
python
|
def get_issues():
issues = []
for entry in Logger.journal:
if entry.level >= WARNING:
issues.append(entry)
return issues
|
[
"def",
"get_issues",
"(",
")",
":",
"issues",
"=",
"[",
"]",
"for",
"entry",
"in",
"Logger",
".",
"journal",
":",
"if",
"entry",
".",
"level",
">=",
"WARNING",
":",
"issues",
".",
"append",
"(",
"entry",
")",
"return",
"issues"
] |
Get actual issues in the journal.
|
[
"Get",
"actual",
"issues",
"in",
"the",
"journal",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L298-L304
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.reset
|
def reset():
"""Resets Logger to its initial state"""
Logger.journal = []
Logger.fatal_warnings = False
Logger._ignored_codes = set()
Logger._ignored_domains = set()
Logger._verbosity = 2
Logger._last_checkpoint = 0
|
python
|
def reset():
Logger.journal = []
Logger.fatal_warnings = False
Logger._ignored_codes = set()
Logger._ignored_domains = set()
Logger._verbosity = 2
Logger._last_checkpoint = 0
|
[
"def",
"reset",
"(",
")",
":",
"Logger",
".",
"journal",
"=",
"[",
"]",
"Logger",
".",
"fatal_warnings",
"=",
"False",
"Logger",
".",
"_ignored_codes",
"=",
"set",
"(",
")",
"Logger",
".",
"_ignored_domains",
"=",
"set",
"(",
")",
"Logger",
".",
"_verbosity",
"=",
"2",
"Logger",
".",
"_last_checkpoint",
"=",
"0"
] |
Resets Logger to its initial state
|
[
"Resets",
"Logger",
"to",
"its",
"initial",
"state"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L307-L314
|
hotdoc/hotdoc
|
hotdoc/utils/loggable.py
|
Logger.set_verbosity
|
def set_verbosity(verbosity):
"""Banana banana
"""
Logger._verbosity = min(max(0, WARNING - verbosity), 2)
debug("Verbosity set to %d" % (WARNING - Logger._verbosity), 'logging')
|
python
|
def set_verbosity(verbosity):
Logger._verbosity = min(max(0, WARNING - verbosity), 2)
debug("Verbosity set to %d" % (WARNING - Logger._verbosity), 'logging')
|
[
"def",
"set_verbosity",
"(",
"verbosity",
")",
":",
"Logger",
".",
"_verbosity",
"=",
"min",
"(",
"max",
"(",
"0",
",",
"WARNING",
"-",
"verbosity",
")",
",",
"2",
")",
"debug",
"(",
"\"Verbosity set to %d\"",
"%",
"(",
"WARNING",
"-",
"Logger",
".",
"_verbosity",
")",
",",
"'logging'",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/utils/loggable.py#L329-L333
|
hotdoc/hotdoc
|
hotdoc/parsers/sitemap.py
|
Sitemap.walk
|
def walk(self, action, user_data=None):
"""
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.
"""
action(self.index_file, self.__root, 0, user_data)
self.__do_walk(self.__root, 1, action, user_data)
|
python
|
def walk(self, action, user_data=None):
action(self.index_file, self.__root, 0, user_data)
self.__do_walk(self.__root, 1, action, user_data)
|
[
"def",
"walk",
"(",
"self",
",",
"action",
",",
"user_data",
"=",
"None",
")",
":",
"action",
"(",
"self",
".",
"index_file",
",",
"self",
".",
"__root",
",",
"0",
",",
"user_data",
")",
"self",
".",
"__do_walk",
"(",
"self",
".",
"__root",
",",
"1",
",",
"action",
",",
"user_data",
")"
] |
Walk the hierarchy, applying action to each filename.
Args:
action: callable, the callable to invoke for each filename,
will be invoked with the filename, the subfiles, and
the level in the sitemap.
|
[
"Walk",
"the",
"hierarchy",
"applying",
"action",
"to",
"each",
"filename",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L77-L87
|
hotdoc/hotdoc
|
hotdoc/parsers/sitemap.py
|
Sitemap.get_all_sources
|
def get_all_sources(self):
"""
Returns:
OrderedDict: all source file names in the hierarchy, paired with
the names of their subpages.
"""
if self.__all_sources is None:
self.__all_sources = OrderedDict()
self.walk(self.__add_one)
return self.__all_sources
|
python
|
def get_all_sources(self):
if self.__all_sources is None:
self.__all_sources = OrderedDict()
self.walk(self.__add_one)
return self.__all_sources
|
[
"def",
"get_all_sources",
"(",
"self",
")",
":",
"if",
"self",
".",
"__all_sources",
"is",
"None",
":",
"self",
".",
"__all_sources",
"=",
"OrderedDict",
"(",
")",
"self",
".",
"walk",
"(",
"self",
".",
"__add_one",
")",
"return",
"self",
".",
"__all_sources"
] |
Returns:
OrderedDict: all source file names in the hierarchy, paired with
the names of their subpages.
|
[
"Returns",
":",
"OrderedDict",
":",
"all",
"source",
"file",
"names",
"in",
"the",
"hierarchy",
"paired",
"with",
"the",
"names",
"of",
"their",
"subpages",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L101-L110
|
hotdoc/hotdoc
|
hotdoc/parsers/sitemap.py
|
SitemapParser.parse
|
def parse(self, filename):
"""
Parse a sitemap file.
Args:
filename: str, the path to the sitemap file.
Returns:
Sitemap: the generated sitemap.
"""
with io.open(filename, 'r', encoding='utf-8') as _:
lines = _.readlines()
all_source_files = set()
source_map = {}
lineno = 0
root = None
index = None
cur_level = -1
parent_queue = []
for line in lines:
try:
level, line = dedent(line)
if line.startswith('#'):
lineno += 1
continue
elif line.startswith('\\#'):
line = line[1:]
except IndentError as exc:
error('bad-indent', 'Invalid indentation', filename=filename,
lineno=lineno, column=exc.column)
if not line:
lineno += 1
continue
source_file = dequote(line)
if not source_file:
lineno += 1
continue
if source_file in all_source_files:
error('sitemap-duplicate', 'Filename listed twice',
filename=filename, lineno=lineno, column=level * 8 + 1)
all_source_files.add(source_file)
source_map[source_file] = (lineno, level * 8 + 1)
page = OrderedDict()
if root is not None and level == 0:
error('sitemap-error', 'Sitemaps only support one root',
filename=filename, lineno=lineno, column=0)
if root is None:
root = page
index = source_file
else:
lvl_diff = cur_level - level
while lvl_diff >= 0:
parent_queue.pop()
lvl_diff -= 1
parent_queue[-1][source_file] = page
parent_queue.append(page)
cur_level = level
lineno += 1
return Sitemap(root, filename, index, source_map)
|
python
|
def parse(self, filename):
with io.open(filename, 'r', encoding='utf-8') as _:
lines = _.readlines()
all_source_files = set()
source_map = {}
lineno = 0
root = None
index = None
cur_level = -1
parent_queue = []
for line in lines:
try:
level, line = dedent(line)
if line.startswith('
lineno += 1
continue
elif line.startswith('\\
line = line[1:]
except IndentError as exc:
error('bad-indent', 'Invalid indentation', filename=filename,
lineno=lineno, column=exc.column)
if not line:
lineno += 1
continue
source_file = dequote(line)
if not source_file:
lineno += 1
continue
if source_file in all_source_files:
error('sitemap-duplicate', 'Filename listed twice',
filename=filename, lineno=lineno, column=level * 8 + 1)
all_source_files.add(source_file)
source_map[source_file] = (lineno, level * 8 + 1)
page = OrderedDict()
if root is not None and level == 0:
error('sitemap-error', 'Sitemaps only support one root',
filename=filename, lineno=lineno, column=0)
if root is None:
root = page
index = source_file
else:
lvl_diff = cur_level - level
while lvl_diff >= 0:
parent_queue.pop()
lvl_diff -= 1
parent_queue[-1][source_file] = page
parent_queue.append(page)
cur_level = level
lineno += 1
return Sitemap(root, filename, index, source_map)
|
[
"def",
"parse",
"(",
"self",
",",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"_",
":",
"lines",
"=",
"_",
".",
"readlines",
"(",
")",
"all_source_files",
"=",
"set",
"(",
")",
"source_map",
"=",
"{",
"}",
"lineno",
"=",
"0",
"root",
"=",
"None",
"index",
"=",
"None",
"cur_level",
"=",
"-",
"1",
"parent_queue",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"try",
":",
"level",
",",
"line",
"=",
"dedent",
"(",
"line",
")",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"lineno",
"+=",
"1",
"continue",
"elif",
"line",
".",
"startswith",
"(",
"'\\\\#'",
")",
":",
"line",
"=",
"line",
"[",
"1",
":",
"]",
"except",
"IndentError",
"as",
"exc",
":",
"error",
"(",
"'bad-indent'",
",",
"'Invalid indentation'",
",",
"filename",
"=",
"filename",
",",
"lineno",
"=",
"lineno",
",",
"column",
"=",
"exc",
".",
"column",
")",
"if",
"not",
"line",
":",
"lineno",
"+=",
"1",
"continue",
"source_file",
"=",
"dequote",
"(",
"line",
")",
"if",
"not",
"source_file",
":",
"lineno",
"+=",
"1",
"continue",
"if",
"source_file",
"in",
"all_source_files",
":",
"error",
"(",
"'sitemap-duplicate'",
",",
"'Filename listed twice'",
",",
"filename",
"=",
"filename",
",",
"lineno",
"=",
"lineno",
",",
"column",
"=",
"level",
"*",
"8",
"+",
"1",
")",
"all_source_files",
".",
"add",
"(",
"source_file",
")",
"source_map",
"[",
"source_file",
"]",
"=",
"(",
"lineno",
",",
"level",
"*",
"8",
"+",
"1",
")",
"page",
"=",
"OrderedDict",
"(",
")",
"if",
"root",
"is",
"not",
"None",
"and",
"level",
"==",
"0",
":",
"error",
"(",
"'sitemap-error'",
",",
"'Sitemaps only support one root'",
",",
"filename",
"=",
"filename",
",",
"lineno",
"=",
"lineno",
",",
"column",
"=",
"0",
")",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"page",
"index",
"=",
"source_file",
"else",
":",
"lvl_diff",
"=",
"cur_level",
"-",
"level",
"while",
"lvl_diff",
">=",
"0",
":",
"parent_queue",
".",
"pop",
"(",
")",
"lvl_diff",
"-=",
"1",
"parent_queue",
"[",
"-",
"1",
"]",
"[",
"source_file",
"]",
"=",
"page",
"parent_queue",
".",
"append",
"(",
"page",
")",
"cur_level",
"=",
"level",
"lineno",
"+=",
"1",
"return",
"Sitemap",
"(",
"root",
",",
"filename",
",",
"index",
",",
"source_map",
")"
] |
Parse a sitemap file.
Args:
filename: str, the path to the sitemap file.
Returns:
Sitemap: the generated sitemap.
|
[
"Parse",
"a",
"sitemap",
"file",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/sitemap.py#L144-L218
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
_grouper
|
def _grouper(iterable, n_args, fillvalue=None):
"""
Banana banana
"""
args = [iter(iterable)] * n_args
return zip_longest(*args, fillvalue=fillvalue)
|
python
|
def _grouper(iterable, n_args, fillvalue=None):
args = [iter(iterable)] * n_args
return zip_longest(*args, fillvalue=fillvalue)
|
[
"def",
"_grouper",
"(",
"iterable",
",",
"n_args",
",",
"fillvalue",
"=",
"None",
")",
":",
"args",
"=",
"[",
"iter",
"(",
"iterable",
")",
"]",
"*",
"n_args",
"return",
"zip_longest",
"(",
"*",
"args",
",",
"fillvalue",
"=",
"fillvalue",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L48-L53
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocParser.parse_comment
|
def parse_comment(self, comment, filename, lineno, endlineno,
include_paths=None, stripped=False):
"""
Returns a Comment given a string
"""
if not stripped and not self.__validate_c_comment(comment.strip()):
return None
title_offset = 0
column_offset = 0
raw_comment = comment
if not stripped:
try:
while comment[column_offset * -1 - 1] != '\n':
column_offset += 1
except IndexError:
column_offset = 0
comment, title_offset = self.__strip_comment(comment)
title_and_params, description = self.__extract_titles_params_and_description(comment)
try:
block_name, parameters, annotations, is_section = \
self.__parse_title_and_parameters(filename, title_and_params)
except HotdocSourceException as _:
warn('gtk-doc-bad-syntax',
message=_.message,
filename=filename,
lineno=lineno + title_offset)
return None
params_offset = 0
for param in parameters:
param.filename = filename
param.lineno = lineno
param_offset = param.line_offset
param.line_offset = title_offset + params_offset + 1
params_offset += param_offset
param.col_offset = column_offset
if not block_name:
return None
description_offset = 0
meta = {}
tags = []
if description is not None:
n_lines = len(comment.split('\n'))
description_offset = (title_offset + n_lines -
len(description.split('\n')))
meta['description'], tags = self.__parse_description_and_tags(description)
actual_parameters = OrderedDict({})
for param in parameters:
if is_section:
cleaned_up_name = param.name.lower().replace('_', '-')
if cleaned_up_name in ['symbols', 'private-symbols', 'auto-sort', 'sources']:
meta.update(self.__parse_yaml_comment(param, filename))
if cleaned_up_name == 'sources':
sources_paths = [os.path.abspath(os.path.join(os.path.dirname(filename), path)) for path in meta[cleaned_up_name]]
meta[cleaned_up_name] = sources_paths
else:
meta[param.name] = param.description
else:
actual_parameters[param.name] = param
annotations = {annotation.name: annotation for annotation in
annotations}
tags = {tag.name.lower(): tag for tag in tags}
block = Comment(name=block_name, filename=filename, lineno=lineno,
endlineno=endlineno,
annotations=annotations, params=actual_parameters,
tags=tags, raw_comment=raw_comment,
meta=meta, toplevel=is_section)
block.line_offset = description_offset
block.col_offset = column_offset
return block
|
python
|
def parse_comment(self, comment, filename, lineno, endlineno,
include_paths=None, stripped=False):
if not stripped and not self.__validate_c_comment(comment.strip()):
return None
title_offset = 0
column_offset = 0
raw_comment = comment
if not stripped:
try:
while comment[column_offset * -1 - 1] != '\n':
column_offset += 1
except IndexError:
column_offset = 0
comment, title_offset = self.__strip_comment(comment)
title_and_params, description = self.__extract_titles_params_and_description(comment)
try:
block_name, parameters, annotations, is_section = \
self.__parse_title_and_parameters(filename, title_and_params)
except HotdocSourceException as _:
warn('gtk-doc-bad-syntax',
message=_.message,
filename=filename,
lineno=lineno + title_offset)
return None
params_offset = 0
for param in parameters:
param.filename = filename
param.lineno = lineno
param_offset = param.line_offset
param.line_offset = title_offset + params_offset + 1
params_offset += param_offset
param.col_offset = column_offset
if not block_name:
return None
description_offset = 0
meta = {}
tags = []
if description is not None:
n_lines = len(comment.split('\n'))
description_offset = (title_offset + n_lines -
len(description.split('\n')))
meta['description'], tags = self.__parse_description_and_tags(description)
actual_parameters = OrderedDict({})
for param in parameters:
if is_section:
cleaned_up_name = param.name.lower().replace('_', '-')
if cleaned_up_name in ['symbols', 'private-symbols', 'auto-sort', 'sources']:
meta.update(self.__parse_yaml_comment(param, filename))
if cleaned_up_name == 'sources':
sources_paths = [os.path.abspath(os.path.join(os.path.dirname(filename), path)) for path in meta[cleaned_up_name]]
meta[cleaned_up_name] = sources_paths
else:
meta[param.name] = param.description
else:
actual_parameters[param.name] = param
annotations = {annotation.name: annotation for annotation in
annotations}
tags = {tag.name.lower(): tag for tag in tags}
block = Comment(name=block_name, filename=filename, lineno=lineno,
endlineno=endlineno,
annotations=annotations, params=actual_parameters,
tags=tags, raw_comment=raw_comment,
meta=meta, toplevel=is_section)
block.line_offset = description_offset
block.col_offset = column_offset
return block
|
[
"def",
"parse_comment",
"(",
"self",
",",
"comment",
",",
"filename",
",",
"lineno",
",",
"endlineno",
",",
"include_paths",
"=",
"None",
",",
"stripped",
"=",
"False",
")",
":",
"if",
"not",
"stripped",
"and",
"not",
"self",
".",
"__validate_c_comment",
"(",
"comment",
".",
"strip",
"(",
")",
")",
":",
"return",
"None",
"title_offset",
"=",
"0",
"column_offset",
"=",
"0",
"raw_comment",
"=",
"comment",
"if",
"not",
"stripped",
":",
"try",
":",
"while",
"comment",
"[",
"column_offset",
"*",
"-",
"1",
"-",
"1",
"]",
"!=",
"'\\n'",
":",
"column_offset",
"+=",
"1",
"except",
"IndexError",
":",
"column_offset",
"=",
"0",
"comment",
",",
"title_offset",
"=",
"self",
".",
"__strip_comment",
"(",
"comment",
")",
"title_and_params",
",",
"description",
"=",
"self",
".",
"__extract_titles_params_and_description",
"(",
"comment",
")",
"try",
":",
"block_name",
",",
"parameters",
",",
"annotations",
",",
"is_section",
"=",
"self",
".",
"__parse_title_and_parameters",
"(",
"filename",
",",
"title_and_params",
")",
"except",
"HotdocSourceException",
"as",
"_",
":",
"warn",
"(",
"'gtk-doc-bad-syntax'",
",",
"message",
"=",
"_",
".",
"message",
",",
"filename",
"=",
"filename",
",",
"lineno",
"=",
"lineno",
"+",
"title_offset",
")",
"return",
"None",
"params_offset",
"=",
"0",
"for",
"param",
"in",
"parameters",
":",
"param",
".",
"filename",
"=",
"filename",
"param",
".",
"lineno",
"=",
"lineno",
"param_offset",
"=",
"param",
".",
"line_offset",
"param",
".",
"line_offset",
"=",
"title_offset",
"+",
"params_offset",
"+",
"1",
"params_offset",
"+=",
"param_offset",
"param",
".",
"col_offset",
"=",
"column_offset",
"if",
"not",
"block_name",
":",
"return",
"None",
"description_offset",
"=",
"0",
"meta",
"=",
"{",
"}",
"tags",
"=",
"[",
"]",
"if",
"description",
"is",
"not",
"None",
":",
"n_lines",
"=",
"len",
"(",
"comment",
".",
"split",
"(",
"'\\n'",
")",
")",
"description_offset",
"=",
"(",
"title_offset",
"+",
"n_lines",
"-",
"len",
"(",
"description",
".",
"split",
"(",
"'\\n'",
")",
")",
")",
"meta",
"[",
"'description'",
"]",
",",
"tags",
"=",
"self",
".",
"__parse_description_and_tags",
"(",
"description",
")",
"actual_parameters",
"=",
"OrderedDict",
"(",
"{",
"}",
")",
"for",
"param",
"in",
"parameters",
":",
"if",
"is_section",
":",
"cleaned_up_name",
"=",
"param",
".",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"cleaned_up_name",
"in",
"[",
"'symbols'",
",",
"'private-symbols'",
",",
"'auto-sort'",
",",
"'sources'",
"]",
":",
"meta",
".",
"update",
"(",
"self",
".",
"__parse_yaml_comment",
"(",
"param",
",",
"filename",
")",
")",
"if",
"cleaned_up_name",
"==",
"'sources'",
":",
"sources_paths",
"=",
"[",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
",",
"path",
")",
")",
"for",
"path",
"in",
"meta",
"[",
"cleaned_up_name",
"]",
"]",
"meta",
"[",
"cleaned_up_name",
"]",
"=",
"sources_paths",
"else",
":",
"meta",
"[",
"param",
".",
"name",
"]",
"=",
"param",
".",
"description",
"else",
":",
"actual_parameters",
"[",
"param",
".",
"name",
"]",
"=",
"param",
"annotations",
"=",
"{",
"annotation",
".",
"name",
":",
"annotation",
"for",
"annotation",
"in",
"annotations",
"}",
"tags",
"=",
"{",
"tag",
".",
"name",
".",
"lower",
"(",
")",
":",
"tag",
"for",
"tag",
"in",
"tags",
"}",
"block",
"=",
"Comment",
"(",
"name",
"=",
"block_name",
",",
"filename",
"=",
"filename",
",",
"lineno",
"=",
"lineno",
",",
"endlineno",
"=",
"endlineno",
",",
"annotations",
"=",
"annotations",
",",
"params",
"=",
"actual_parameters",
",",
"tags",
"=",
"tags",
",",
"raw_comment",
"=",
"raw_comment",
",",
"meta",
"=",
"meta",
",",
"toplevel",
"=",
"is_section",
")",
"block",
".",
"line_offset",
"=",
"description_offset",
"block",
".",
"col_offset",
"=",
"column_offset",
"return",
"block"
] |
Returns a Comment given a string
|
[
"Returns",
"a",
"Comment",
"given",
"a",
"string"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L303-L382
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocStringFormatter.comment_to_ast
|
def comment_to_ast(self, comment, link_resolver):
"""
Given a gtk-doc comment string, returns an opaque PyCapsule
containing the document root.
This is an optimization allowing to parse the docstring only
once, and to render it multiple times with
`ast_to_html`, links discovery and
most of the link resolution being lazily done in that second phase.
If you don't care about performance, you should simply
use `translate`.
Args:
text: unicode, the docstring to parse.
link_resolver: hotdoc.core.links.LinkResolver, an object
which will be called to retrieve `hotdoc.core.links.Link`
objects.
Returns:
capsule: A PyCapsule wrapping an opaque C pointer, which
can be passed to `ast_to_html`
afterwards.
diagnostics: A list of diagnostics as output by the gtk-doc cmark
extension
"""
assert comment is not None
text = comment.description
if (self.remove_xml_tags or comment.filename in
self.gdbus_codegen_sources):
text = re.sub('<.*?>', '', text)
if self.escape_html:
# pylint: disable=deprecated-method
text = cgi.escape(text)
ast, diagnostics = cmark.gtkdoc_to_ast(text, link_resolver)
for diag in diagnostics:
if (comment.filename and comment.filename not in
self.gdbus_codegen_sources):
column = diag.column + comment.col_offset
if diag.lineno == 0:
column += comment.initial_col_offset
lines = text.split('\n')
line = lines[diag.lineno]
i = 0
while line[i] == ' ':
i += 1
column += i - 1
if diag.lineno > 0 and any([c != ' ' for c in
lines[diag.lineno - 1]]):
column += 1
lineno = -1
if comment.lineno != -1:
lineno = (comment.lineno - 1 + comment.line_offset +
diag.lineno)
warn(
diag.code,
message=diag.message,
filename=comment.filename,
lineno=lineno,
column=column)
return ast
|
python
|
def comment_to_ast(self, comment, link_resolver):
assert comment is not None
text = comment.description
if (self.remove_xml_tags or comment.filename in
self.gdbus_codegen_sources):
text = re.sub('<.*?>', '', text)
if self.escape_html:
text = cgi.escape(text)
ast, diagnostics = cmark.gtkdoc_to_ast(text, link_resolver)
for diag in diagnostics:
if (comment.filename and comment.filename not in
self.gdbus_codegen_sources):
column = diag.column + comment.col_offset
if diag.lineno == 0:
column += comment.initial_col_offset
lines = text.split('\n')
line = lines[diag.lineno]
i = 0
while line[i] == ' ':
i += 1
column += i - 1
if diag.lineno > 0 and any([c != ' ' for c in
lines[diag.lineno - 1]]):
column += 1
lineno = -1
if comment.lineno != -1:
lineno = (comment.lineno - 1 + comment.line_offset +
diag.lineno)
warn(
diag.code,
message=diag.message,
filename=comment.filename,
lineno=lineno,
column=column)
return ast
|
[
"def",
"comment_to_ast",
"(",
"self",
",",
"comment",
",",
"link_resolver",
")",
":",
"assert",
"comment",
"is",
"not",
"None",
"text",
"=",
"comment",
".",
"description",
"if",
"(",
"self",
".",
"remove_xml_tags",
"or",
"comment",
".",
"filename",
"in",
"self",
".",
"gdbus_codegen_sources",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"'<.*?>'",
",",
"''",
",",
"text",
")",
"if",
"self",
".",
"escape_html",
":",
"# pylint: disable=deprecated-method",
"text",
"=",
"cgi",
".",
"escape",
"(",
"text",
")",
"ast",
",",
"diagnostics",
"=",
"cmark",
".",
"gtkdoc_to_ast",
"(",
"text",
",",
"link_resolver",
")",
"for",
"diag",
"in",
"diagnostics",
":",
"if",
"(",
"comment",
".",
"filename",
"and",
"comment",
".",
"filename",
"not",
"in",
"self",
".",
"gdbus_codegen_sources",
")",
":",
"column",
"=",
"diag",
".",
"column",
"+",
"comment",
".",
"col_offset",
"if",
"diag",
".",
"lineno",
"==",
"0",
":",
"column",
"+=",
"comment",
".",
"initial_col_offset",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"line",
"=",
"lines",
"[",
"diag",
".",
"lineno",
"]",
"i",
"=",
"0",
"while",
"line",
"[",
"i",
"]",
"==",
"' '",
":",
"i",
"+=",
"1",
"column",
"+=",
"i",
"-",
"1",
"if",
"diag",
".",
"lineno",
">",
"0",
"and",
"any",
"(",
"[",
"c",
"!=",
"' '",
"for",
"c",
"in",
"lines",
"[",
"diag",
".",
"lineno",
"-",
"1",
"]",
"]",
")",
":",
"column",
"+=",
"1",
"lineno",
"=",
"-",
"1",
"if",
"comment",
".",
"lineno",
"!=",
"-",
"1",
":",
"lineno",
"=",
"(",
"comment",
".",
"lineno",
"-",
"1",
"+",
"comment",
".",
"line_offset",
"+",
"diag",
".",
"lineno",
")",
"warn",
"(",
"diag",
".",
"code",
",",
"message",
"=",
"diag",
".",
"message",
",",
"filename",
"=",
"comment",
".",
"filename",
",",
"lineno",
"=",
"lineno",
",",
"column",
"=",
"column",
")",
"return",
"ast"
] |
Given a gtk-doc comment string, returns an opaque PyCapsule
containing the document root.
This is an optimization allowing to parse the docstring only
once, and to render it multiple times with
`ast_to_html`, links discovery and
most of the link resolution being lazily done in that second phase.
If you don't care about performance, you should simply
use `translate`.
Args:
text: unicode, the docstring to parse.
link_resolver: hotdoc.core.links.LinkResolver, an object
which will be called to retrieve `hotdoc.core.links.Link`
objects.
Returns:
capsule: A PyCapsule wrapping an opaque C pointer, which
can be passed to `ast_to_html`
afterwards.
diagnostics: A list of diagnostics as output by the gtk-doc cmark
extension
|
[
"Given",
"a",
"gtk",
"-",
"doc",
"comment",
"string",
"returns",
"an",
"opaque",
"PyCapsule",
"containing",
"the",
"document",
"root",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L396-L464
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocStringFormatter.ast_to_html
|
def ast_to_html(self, ast, link_resolver):
"""
See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance.
"""
out, _ = cmark.ast_to_html(ast, link_resolver)
return out
|
python
|
def ast_to_html(self, ast, link_resolver):
out, _ = cmark.ast_to_html(ast, link_resolver)
return out
|
[
"def",
"ast_to_html",
"(",
"self",
",",
"ast",
",",
"link_resolver",
")",
":",
"out",
",",
"_",
"=",
"cmark",
".",
"ast_to_html",
"(",
"ast",
",",
"link_resolver",
")",
"return",
"out"
] |
See the documentation of `to_ast` for
more information.
Args:
ast: PyCapsule, a capsule as returned by `to_ast`
link_resolver: hotdoc.core.links.LinkResolver, a link
resolver instance.
|
[
"See",
"the",
"documentation",
"of",
"to_ast",
"for",
"more",
"information",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L467-L478
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocStringFormatter.translate_comment
|
def translate_comment(self, comment, link_resolver):
"""
Given a gtk-doc comment string, returns the comment translated
to the desired format.
"""
out = u''
self.translate_tags(comment, link_resolver)
ast = self.comment_to_ast(comment, link_resolver)
out += self.ast_to_html(ast, link_resolver)
return out
|
python
|
def translate_comment(self, comment, link_resolver):
out = u''
self.translate_tags(comment, link_resolver)
ast = self.comment_to_ast(comment, link_resolver)
out += self.ast_to_html(ast, link_resolver)
return out
|
[
"def",
"translate_comment",
"(",
"self",
",",
"comment",
",",
"link_resolver",
")",
":",
"out",
"=",
"u''",
"self",
".",
"translate_tags",
"(",
"comment",
",",
"link_resolver",
")",
"ast",
"=",
"self",
".",
"comment_to_ast",
"(",
"comment",
",",
"link_resolver",
")",
"out",
"+=",
"self",
".",
"ast_to_html",
"(",
"ast",
",",
"link_resolver",
")",
"return",
"out"
] |
Given a gtk-doc comment string, returns the comment translated
to the desired format.
|
[
"Given",
"a",
"gtk",
"-",
"doc",
"comment",
"string",
"returns",
"the",
"comment",
"translated",
"to",
"the",
"desired",
"format",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L480-L490
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocStringFormatter.translate_tags
|
def translate_tags(self, comment, link_resolver):
"""Banana banana
"""
for tname in ('deprecated',):
tag = comment.tags.get(tname)
if tag is not None and tag.description:
comment = comment_from_tag(tag)
ast = self.comment_to_ast(comment, link_resolver)
tag.description = self.ast_to_html(ast, link_resolver) or ''
|
python
|
def translate_tags(self, comment, link_resolver):
for tname in ('deprecated',):
tag = comment.tags.get(tname)
if tag is not None and tag.description:
comment = comment_from_tag(tag)
ast = self.comment_to_ast(comment, link_resolver)
tag.description = self.ast_to_html(ast, link_resolver) or ''
|
[
"def",
"translate_tags",
"(",
"self",
",",
"comment",
",",
"link_resolver",
")",
":",
"for",
"tname",
"in",
"(",
"'deprecated'",
",",
")",
":",
"tag",
"=",
"comment",
".",
"tags",
".",
"get",
"(",
"tname",
")",
"if",
"tag",
"is",
"not",
"None",
"and",
"tag",
".",
"description",
":",
"comment",
"=",
"comment_from_tag",
"(",
"tag",
")",
"ast",
"=",
"self",
".",
"comment_to_ast",
"(",
"comment",
",",
"link_resolver",
")",
"tag",
".",
"description",
"=",
"self",
".",
"ast_to_html",
"(",
"ast",
",",
"link_resolver",
")",
"or",
"''"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L492-L500
|
hotdoc/hotdoc
|
hotdoc/parsers/gtk_doc.py
|
GtkDocStringFormatter.parse_config
|
def parse_config(self, config):
"""Banana banana
"""
self.remove_xml_tags = config.get('gtk_doc_remove_xml')
self.escape_html = config.get('gtk_doc_escape_html')
self.gdbus_codegen_sources = config.get_paths('gdbus_codegen_sources')
|
python
|
def parse_config(self, config):
self.remove_xml_tags = config.get('gtk_doc_remove_xml')
self.escape_html = config.get('gtk_doc_escape_html')
self.gdbus_codegen_sources = config.get_paths('gdbus_codegen_sources')
|
[
"def",
"parse_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"remove_xml_tags",
"=",
"config",
".",
"get",
"(",
"'gtk_doc_remove_xml'",
")",
"self",
".",
"escape_html",
"=",
"config",
".",
"get",
"(",
"'gtk_doc_escape_html'",
")",
"self",
".",
"gdbus_codegen_sources",
"=",
"config",
".",
"get_paths",
"(",
"'gdbus_codegen_sources'",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/parsers/gtk_doc.py#L520-L525
|
hotdoc/hotdoc
|
hotdoc/core/symbols.py
|
Symbol.add_extension_attribute
|
def add_extension_attribute(self, ext_name, key, value):
"""
Banana banana
"""
attributes = self.extension_attributes.pop(ext_name, {})
attributes[key] = value
self.extension_attributes[ext_name] = attributes
|
python
|
def add_extension_attribute(self, ext_name, key, value):
attributes = self.extension_attributes.pop(ext_name, {})
attributes[key] = value
self.extension_attributes[ext_name] = attributes
|
[
"def",
"add_extension_attribute",
"(",
"self",
",",
"ext_name",
",",
"key",
",",
"value",
")",
":",
"attributes",
"=",
"self",
".",
"extension_attributes",
".",
"pop",
"(",
"ext_name",
",",
"{",
"}",
")",
"attributes",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"extension_attributes",
"[",
"ext_name",
"]",
"=",
"attributes"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/symbols.py#L68-L74
|
hotdoc/hotdoc
|
hotdoc/core/symbols.py
|
Symbol.get_extension_attribute
|
def get_extension_attribute(self, ext_name, key):
"""
Banana banana
"""
attributes = self.extension_attributes.get(ext_name)
if not attributes:
return None
return attributes.get(key)
|
python
|
def get_extension_attribute(self, ext_name, key):
attributes = self.extension_attributes.get(ext_name)
if not attributes:
return None
return attributes.get(key)
|
[
"def",
"get_extension_attribute",
"(",
"self",
",",
"ext_name",
",",
"key",
")",
":",
"attributes",
"=",
"self",
".",
"extension_attributes",
".",
"get",
"(",
"ext_name",
")",
"if",
"not",
"attributes",
":",
"return",
"None",
"return",
"attributes",
".",
"get",
"(",
"key",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/symbols.py#L76-L83
|
hotdoc/hotdoc
|
hotdoc/core/symbols.py
|
Symbol.update_children_comments
|
def update_children_comments(self):
"""
Banana banana
"""
if self.comment is None:
return
for sym in self.get_children_symbols():
if isinstance(sym, ParameterSymbol):
sym.comment = self.comment.params.get(sym.argname)
elif isinstance(sym, FieldSymbol):
if not sym.comment or not sym.comment.description:
sym.comment = self.comment.params.get(sym.member_name)
elif isinstance(sym, EnumMemberSymbol):
if not sym.comment or not sym.comment.description:
sym.comment = self.comment.params.get(sym.unique_name)
elif isinstance(sym, ReturnItemSymbol):
tag = self.comment.tags.get('returns')
sym.comment = comment_from_tag(tag)
elif type(sym) == Symbol:
sym.comment = self.comment.params.get(sym.display_name)
|
python
|
def update_children_comments(self):
if self.comment is None:
return
for sym in self.get_children_symbols():
if isinstance(sym, ParameterSymbol):
sym.comment = self.comment.params.get(sym.argname)
elif isinstance(sym, FieldSymbol):
if not sym.comment or not sym.comment.description:
sym.comment = self.comment.params.get(sym.member_name)
elif isinstance(sym, EnumMemberSymbol):
if not sym.comment or not sym.comment.description:
sym.comment = self.comment.params.get(sym.unique_name)
elif isinstance(sym, ReturnItemSymbol):
tag = self.comment.tags.get('returns')
sym.comment = comment_from_tag(tag)
elif type(sym) == Symbol:
sym.comment = self.comment.params.get(sym.display_name)
|
[
"def",
"update_children_comments",
"(",
"self",
")",
":",
"if",
"self",
".",
"comment",
"is",
"None",
":",
"return",
"for",
"sym",
"in",
"self",
".",
"get_children_symbols",
"(",
")",
":",
"if",
"isinstance",
"(",
"sym",
",",
"ParameterSymbol",
")",
":",
"sym",
".",
"comment",
"=",
"self",
".",
"comment",
".",
"params",
".",
"get",
"(",
"sym",
".",
"argname",
")",
"elif",
"isinstance",
"(",
"sym",
",",
"FieldSymbol",
")",
":",
"if",
"not",
"sym",
".",
"comment",
"or",
"not",
"sym",
".",
"comment",
".",
"description",
":",
"sym",
".",
"comment",
"=",
"self",
".",
"comment",
".",
"params",
".",
"get",
"(",
"sym",
".",
"member_name",
")",
"elif",
"isinstance",
"(",
"sym",
",",
"EnumMemberSymbol",
")",
":",
"if",
"not",
"sym",
".",
"comment",
"or",
"not",
"sym",
".",
"comment",
".",
"description",
":",
"sym",
".",
"comment",
"=",
"self",
".",
"comment",
".",
"params",
".",
"get",
"(",
"sym",
".",
"unique_name",
")",
"elif",
"isinstance",
"(",
"sym",
",",
"ReturnItemSymbol",
")",
":",
"tag",
"=",
"self",
".",
"comment",
".",
"tags",
".",
"get",
"(",
"'returns'",
")",
"sym",
".",
"comment",
"=",
"comment_from_tag",
"(",
"tag",
")",
"elif",
"type",
"(",
"sym",
")",
"==",
"Symbol",
":",
"sym",
".",
"comment",
"=",
"self",
".",
"comment",
".",
"params",
".",
"get",
"(",
"sym",
".",
"display_name",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/symbols.py#L94-L114
|
hotdoc/hotdoc
|
hotdoc/core/symbols.py
|
Symbol.resolve_links
|
def resolve_links(self, link_resolver):
"""
Banana banana
"""
if self.link is None:
self.link = Link(self.unique_name, self._make_name(),
self.unique_name)
self.link = link_resolver.upsert_link(self.link, overwrite_ref=True)
for sym in self.get_children_symbols():
if sym:
sym.resolve_links(link_resolver)
|
python
|
def resolve_links(self, link_resolver):
if self.link is None:
self.link = Link(self.unique_name, self._make_name(),
self.unique_name)
self.link = link_resolver.upsert_link(self.link, overwrite_ref=True)
for sym in self.get_children_symbols():
if sym:
sym.resolve_links(link_resolver)
|
[
"def",
"resolve_links",
"(",
"self",
",",
"link_resolver",
")",
":",
"if",
"self",
".",
"link",
"is",
"None",
":",
"self",
".",
"link",
"=",
"Link",
"(",
"self",
".",
"unique_name",
",",
"self",
".",
"_make_name",
"(",
")",
",",
"self",
".",
"unique_name",
")",
"self",
".",
"link",
"=",
"link_resolver",
".",
"upsert_link",
"(",
"self",
".",
"link",
",",
"overwrite_ref",
"=",
"True",
")",
"for",
"sym",
"in",
"self",
".",
"get_children_symbols",
"(",
")",
":",
"if",
"sym",
":",
"sym",
".",
"resolve_links",
"(",
"link_resolver",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/symbols.py#L131-L143
|
hotdoc/hotdoc
|
hotdoc/core/symbols.py
|
QualifiedSymbol.resolve_links
|
def resolve_links(self, link_resolver):
"""
Banana banana
"""
self.type_link = None
self.type_tokens = []
for child in self.get_children_symbols():
child.resolve_links(link_resolver)
for tok in self.input_tokens:
if isinstance(tok, Link):
self.type_link = link_resolver.upsert_link(tok)
self.type_tokens.append(self.type_link)
else:
self.type_tokens.append(tok)
|
python
|
def resolve_links(self, link_resolver):
self.type_link = None
self.type_tokens = []
for child in self.get_children_symbols():
child.resolve_links(link_resolver)
for tok in self.input_tokens:
if isinstance(tok, Link):
self.type_link = link_resolver.upsert_link(tok)
self.type_tokens.append(self.type_link)
else:
self.type_tokens.append(tok)
|
[
"def",
"resolve_links",
"(",
"self",
",",
"link_resolver",
")",
":",
"self",
".",
"type_link",
"=",
"None",
"self",
".",
"type_tokens",
"=",
"[",
"]",
"for",
"child",
"in",
"self",
".",
"get_children_symbols",
"(",
")",
":",
"child",
".",
"resolve_links",
"(",
"link_resolver",
")",
"for",
"tok",
"in",
"self",
".",
"input_tokens",
":",
"if",
"isinstance",
"(",
"tok",
",",
"Link",
")",
":",
"self",
".",
"type_link",
"=",
"link_resolver",
".",
"upsert_link",
"(",
"tok",
")",
"self",
".",
"type_tokens",
".",
"append",
"(",
"self",
".",
"type_link",
")",
"else",
":",
"self",
".",
"type_tokens",
".",
"append",
"(",
"tok",
")"
] |
Banana banana
|
[
"Banana",
"banana"
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/symbols.py#L188-L203
|
hotdoc/hotdoc
|
hotdoc/core/comment.py
|
comment_from_tag
|
def comment_from_tag(tag):
"""
Convenience function to create a full-fledged comment for a
given tag, for example it is convenient to assign a Comment
to a ReturnValueSymbol.
"""
if not tag:
return None
comment = Comment(name=tag.name,
meta={'description': tag.description},
annotations=tag.annotations)
return comment
|
python
|
def comment_from_tag(tag):
if not tag:
return None
comment = Comment(name=tag.name,
meta={'description': tag.description},
annotations=tag.annotations)
return comment
|
[
"def",
"comment_from_tag",
"(",
"tag",
")",
":",
"if",
"not",
"tag",
":",
"return",
"None",
"comment",
"=",
"Comment",
"(",
"name",
"=",
"tag",
".",
"name",
",",
"meta",
"=",
"{",
"'description'",
":",
"tag",
".",
"description",
"}",
",",
"annotations",
"=",
"tag",
".",
"annotations",
")",
"return",
"comment"
] |
Convenience function to create a full-fledged comment for a
given tag, for example it is convenient to assign a Comment
to a ReturnValueSymbol.
|
[
"Convenience",
"function",
"to",
"create",
"a",
"full",
"-",
"fledged",
"comment",
"for",
"a",
"given",
"tag",
"for",
"example",
"it",
"is",
"convenient",
"to",
"assign",
"a",
"Comment",
"to",
"a",
"ReturnValueSymbol",
"."
] |
train
|
https://github.com/hotdoc/hotdoc/blob/1067cdc8482b585b364a38fb52ca5d904e486280/hotdoc/core/comment.py#L159-L170
|
tcalmant/python-javaobj
|
javaobj/modifiedutf8.py
|
decoder
|
def decoder(data):
"""
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
:param data: a string of bytes in Modified UTF-8 encoding.
:return: a generator producing a string of unicode characters
:raises UnicodeDecodeError: unrecognised byte in sequence encountered.
"""
def next_byte(_it, start, count):
try:
return next(_it)[1]
except StopIteration:
raise UnicodeDecodeError(
NAME, data, start, start + count, "incomplete byte sequence"
)
it = iter(enumerate(data))
for i, d in it:
if d == 0x00: # 00000000
raise UnicodeDecodeError(
NAME, data, i, i + 1, "embedded zero-byte not allowed"
)
elif d & 0x80: # 1xxxxxxx
if d & 0x40: # 11xxxxxx
if d & 0x20: # 111xxxxx
if d & 0x10: # 1111xxxx
raise UnicodeDecodeError(
NAME, data, i, i + 1, "invalid encoding character"
)
elif d == 0xED:
value = 0
for i1, dm in enumerate(DECODE_MAP[6]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else: # 1110xxxx
value = d & 0x0F
for i1, dm in enumerate(DECODE_MAP[3]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else: # 110xxxxx
value = d & 0x1F
for i1, dm in enumerate(DECODE_MAP[2]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else: # 10xxxxxx
raise UnicodeDecodeError(
NAME, data, i, i + 1, "misplaced continuation character"
)
else: # 0xxxxxxx
value = d
# noinspection PyCompatibility
yield mutf8_unichr(value)
|
python
|
def decoder(data):
def next_byte(_it, start, count):
try:
return next(_it)[1]
except StopIteration:
raise UnicodeDecodeError(
NAME, data, start, start + count, "incomplete byte sequence"
)
it = iter(enumerate(data))
for i, d in it:
if d == 0x00:
raise UnicodeDecodeError(
NAME, data, i, i + 1, "embedded zero-byte not allowed"
)
elif d & 0x80:
if d & 0x40:
if d & 0x20:
if d & 0x10:
raise UnicodeDecodeError(
NAME, data, i, i + 1, "invalid encoding character"
)
elif d == 0xED:
value = 0
for i1, dm in enumerate(DECODE_MAP[6]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else:
value = d & 0x0F
for i1, dm in enumerate(DECODE_MAP[3]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else:
value = d & 0x1F
for i1, dm in enumerate(DECODE_MAP[2]):
d1 = next_byte(it, i, i1 + 1)
value = dm.apply(d1, value, data, i, i1 + 1)
else:
raise UnicodeDecodeError(
NAME, data, i, i + 1, "misplaced continuation character"
)
else:
value = d
yield mutf8_unichr(value)
|
[
"def",
"decoder",
"(",
"data",
")",
":",
"def",
"next_byte",
"(",
"_it",
",",
"start",
",",
"count",
")",
":",
"try",
":",
"return",
"next",
"(",
"_it",
")",
"[",
"1",
"]",
"except",
"StopIteration",
":",
"raise",
"UnicodeDecodeError",
"(",
"NAME",
",",
"data",
",",
"start",
",",
"start",
"+",
"count",
",",
"\"incomplete byte sequence\"",
")",
"it",
"=",
"iter",
"(",
"enumerate",
"(",
"data",
")",
")",
"for",
"i",
",",
"d",
"in",
"it",
":",
"if",
"d",
"==",
"0x00",
":",
"# 00000000",
"raise",
"UnicodeDecodeError",
"(",
"NAME",
",",
"data",
",",
"i",
",",
"i",
"+",
"1",
",",
"\"embedded zero-byte not allowed\"",
")",
"elif",
"d",
"&",
"0x80",
":",
"# 1xxxxxxx",
"if",
"d",
"&",
"0x40",
":",
"# 11xxxxxx",
"if",
"d",
"&",
"0x20",
":",
"# 111xxxxx",
"if",
"d",
"&",
"0x10",
":",
"# 1111xxxx",
"raise",
"UnicodeDecodeError",
"(",
"NAME",
",",
"data",
",",
"i",
",",
"i",
"+",
"1",
",",
"\"invalid encoding character\"",
")",
"elif",
"d",
"==",
"0xED",
":",
"value",
"=",
"0",
"for",
"i1",
",",
"dm",
"in",
"enumerate",
"(",
"DECODE_MAP",
"[",
"6",
"]",
")",
":",
"d1",
"=",
"next_byte",
"(",
"it",
",",
"i",
",",
"i1",
"+",
"1",
")",
"value",
"=",
"dm",
".",
"apply",
"(",
"d1",
",",
"value",
",",
"data",
",",
"i",
",",
"i1",
"+",
"1",
")",
"else",
":",
"# 1110xxxx",
"value",
"=",
"d",
"&",
"0x0F",
"for",
"i1",
",",
"dm",
"in",
"enumerate",
"(",
"DECODE_MAP",
"[",
"3",
"]",
")",
":",
"d1",
"=",
"next_byte",
"(",
"it",
",",
"i",
",",
"i1",
"+",
"1",
")",
"value",
"=",
"dm",
".",
"apply",
"(",
"d1",
",",
"value",
",",
"data",
",",
"i",
",",
"i1",
"+",
"1",
")",
"else",
":",
"# 110xxxxx",
"value",
"=",
"d",
"&",
"0x1F",
"for",
"i1",
",",
"dm",
"in",
"enumerate",
"(",
"DECODE_MAP",
"[",
"2",
"]",
")",
":",
"d1",
"=",
"next_byte",
"(",
"it",
",",
"i",
",",
"i1",
"+",
"1",
")",
"value",
"=",
"dm",
".",
"apply",
"(",
"d1",
",",
"value",
",",
"data",
",",
"i",
",",
"i1",
"+",
"1",
")",
"else",
":",
"# 10xxxxxx",
"raise",
"UnicodeDecodeError",
"(",
"NAME",
",",
"data",
",",
"i",
",",
"i",
"+",
"1",
",",
"\"misplaced continuation character\"",
")",
"else",
":",
"# 0xxxxxxx",
"value",
"=",
"d",
"# noinspection PyCompatibility",
"yield",
"mutf8_unichr",
"(",
"value",
")"
] |
This generator processes a sequence of bytes in Modified UTF-8 encoding
and produces a sequence of unicode string characters.
It takes bits from the byte until it matches one of the known encoding
sequences.
It uses ``DecodeMap`` to mask, compare and generate values.
:param data: a string of bytes in Modified UTF-8 encoding.
:return: a generator producing a string of unicode characters
:raises UnicodeDecodeError: unrecognised byte in sequence encountered.
|
[
"This",
"generator",
"processes",
"a",
"sequence",
"of",
"bytes",
"in",
"Modified",
"UTF",
"-",
"8",
"encoding",
"and",
"produces",
"a",
"sequence",
"of",
"unicode",
"string",
"characters",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L103-L160
|
tcalmant/python-javaobj
|
javaobj/modifiedutf8.py
|
decode_modified_utf8
|
def decode_modified_utf8(data, errors="strict"):
"""
Decodes a sequence of bytes to a unicode text and length using
Modified UTF-8.
This function is designed to be used with Python ``codecs`` module.
:param data: a string of bytes in Modified UTF-8
:param errors: handle decoding errors
:return: unicode text and length
:raises UnicodeDecodeError: sequence is invalid.
"""
value, length = u"", 0
it = iter(decoder(data))
while True:
try:
value += next(it)
length += 1
except StopIteration:
break
except UnicodeDecodeError as e:
if errors == "strict":
raise e
elif errors == "ignore":
pass
elif errors == "replace":
value += u"\uFFFD"
length += 1
return value, length
|
python
|
def decode_modified_utf8(data, errors="strict"):
value, length = u"", 0
it = iter(decoder(data))
while True:
try:
value += next(it)
length += 1
except StopIteration:
break
except UnicodeDecodeError as e:
if errors == "strict":
raise e
elif errors == "ignore":
pass
elif errors == "replace":
value += u"\uFFFD"
length += 1
return value, length
|
[
"def",
"decode_modified_utf8",
"(",
"data",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"value",
",",
"length",
"=",
"u\"\"",
",",
"0",
"it",
"=",
"iter",
"(",
"decoder",
"(",
"data",
")",
")",
"while",
"True",
":",
"try",
":",
"value",
"+=",
"next",
"(",
"it",
")",
"length",
"+=",
"1",
"except",
"StopIteration",
":",
"break",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"if",
"errors",
"==",
"\"strict\"",
":",
"raise",
"e",
"elif",
"errors",
"==",
"\"ignore\"",
":",
"pass",
"elif",
"errors",
"==",
"\"replace\"",
":",
"value",
"+=",
"u\"\\uFFFD\"",
"length",
"+=",
"1",
"return",
"value",
",",
"length"
] |
Decodes a sequence of bytes to a unicode text and length using
Modified UTF-8.
This function is designed to be used with Python ``codecs`` module.
:param data: a string of bytes in Modified UTF-8
:param errors: handle decoding errors
:return: unicode text and length
:raises UnicodeDecodeError: sequence is invalid.
|
[
"Decodes",
"a",
"sequence",
"of",
"bytes",
"to",
"a",
"unicode",
"text",
"and",
"length",
"using",
"Modified",
"UTF",
"-",
"8",
".",
"This",
"function",
"is",
"designed",
"to",
"be",
"used",
"with",
"Python",
"codecs",
"module",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L163-L190
|
tcalmant/python-javaobj
|
javaobj/modifiedutf8.py
|
DecodeMap.apply
|
def apply(self, byte, value, data, i, count):
"""
Apply mask, compare to expected value, shift and return result.
Eventually, this could become a ``reduce`` function.
:param byte: The byte to compare
:param value: The currently accumulated value.
:param data: The data buffer, (array of bytes).
:param i: The position within the data buffer.
:param count: The position of this comparison.
:return: A new value with the bits merged in.
:raises UnicodeDecodeError: if marked bits don't match.
"""
if byte & self.mask == self.value:
value <<= self.bits
value |= byte & self.mask2
else:
raise UnicodeDecodeError(
NAME, data, i, i + count, "invalid {}-byte sequence".format(self.count)
)
return value
|
python
|
def apply(self, byte, value, data, i, count):
if byte & self.mask == self.value:
value <<= self.bits
value |= byte & self.mask2
else:
raise UnicodeDecodeError(
NAME, data, i, i + count, "invalid {}-byte sequence".format(self.count)
)
return value
|
[
"def",
"apply",
"(",
"self",
",",
"byte",
",",
"value",
",",
"data",
",",
"i",
",",
"count",
")",
":",
"if",
"byte",
"&",
"self",
".",
"mask",
"==",
"self",
".",
"value",
":",
"value",
"<<=",
"self",
".",
"bits",
"value",
"|=",
"byte",
"&",
"self",
".",
"mask2",
"else",
":",
"raise",
"UnicodeDecodeError",
"(",
"NAME",
",",
"data",
",",
"i",
",",
"i",
"+",
"count",
",",
"\"invalid {}-byte sequence\"",
".",
"format",
"(",
"self",
".",
"count",
")",
")",
"return",
"value"
] |
Apply mask, compare to expected value, shift and return result.
Eventually, this could become a ``reduce`` function.
:param byte: The byte to compare
:param value: The currently accumulated value.
:param data: The data buffer, (array of bytes).
:param i: The position within the data buffer.
:param count: The position of this comparison.
:return: A new value with the bits merged in.
:raises UnicodeDecodeError: if marked bits don't match.
|
[
"Apply",
"mask",
"compare",
"to",
"expected",
"value",
"shift",
"and",
"return",
"result",
".",
"Eventually",
"this",
"could",
"become",
"a",
"reduce",
"function",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/modifiedutf8.py#L55-L75
|
tcalmant/python-javaobj
|
javaobj/core.py
|
load
|
def load(file_object, *transformers, **kwargs):
"""
Deserializes Java primitive data and objects serialized using
ObjectOutputStream from a file-like object.
:param file_object: A file-like object
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused
trailing bytes are remaining
:return: The deserialized object
"""
# Read keyword argument
ignore_remaining_data = kwargs.get("ignore_remaining_data", False)
marshaller = JavaObjectUnmarshaller(
file_object, kwargs.get("use_numpy_arrays", False)
)
# Add custom transformers first
for transformer in transformers:
marshaller.add_transformer(transformer)
marshaller.add_transformer(DefaultObjectTransformer())
# Read the file object
return marshaller.readObject(ignore_remaining_data=ignore_remaining_data)
|
python
|
def load(file_object, *transformers, **kwargs):
ignore_remaining_data = kwargs.get("ignore_remaining_data", False)
marshaller = JavaObjectUnmarshaller(
file_object, kwargs.get("use_numpy_arrays", False)
)
for transformer in transformers:
marshaller.add_transformer(transformer)
marshaller.add_transformer(DefaultObjectTransformer())
return marshaller.readObject(ignore_remaining_data=ignore_remaining_data)
|
[
"def",
"load",
"(",
"file_object",
",",
"*",
"transformers",
",",
"*",
"*",
"kwargs",
")",
":",
"# Read keyword argument",
"ignore_remaining_data",
"=",
"kwargs",
".",
"get",
"(",
"\"ignore_remaining_data\"",
",",
"False",
")",
"marshaller",
"=",
"JavaObjectUnmarshaller",
"(",
"file_object",
",",
"kwargs",
".",
"get",
"(",
"\"use_numpy_arrays\"",
",",
"False",
")",
")",
"# Add custom transformers first",
"for",
"transformer",
"in",
"transformers",
":",
"marshaller",
".",
"add_transformer",
"(",
"transformer",
")",
"marshaller",
".",
"add_transformer",
"(",
"DefaultObjectTransformer",
"(",
")",
")",
"# Read the file object",
"return",
"marshaller",
".",
"readObject",
"(",
"ignore_remaining_data",
"=",
"ignore_remaining_data",
")"
] |
Deserializes Java primitive data and objects serialized using
ObjectOutputStream from a file-like object.
:param file_object: A file-like object
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused
trailing bytes are remaining
:return: The deserialized object
|
[
"Deserializes",
"Java",
"primitive",
"data",
"and",
"objects",
"serialized",
"using",
"ObjectOutputStream",
"from",
"a",
"file",
"-",
"like",
"object",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L101-L125
|
tcalmant/python-javaobj
|
javaobj/core.py
|
loads
|
def loads(string, *transformers, **kwargs):
"""
Deserializes Java objects and primitive data serialized using
ObjectOutputStream from a string.
:param string: A Java data string
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused
trailing bytes are remaining
:return: The deserialized object
"""
# Read keyword argument
ignore_remaining_data = kwargs.get("ignore_remaining_data", False)
# Reuse the load method (avoid code duplication)
return load(
BytesIO(string), *transformers, ignore_remaining_data=ignore_remaining_data
)
|
python
|
def loads(string, *transformers, **kwargs):
ignore_remaining_data = kwargs.get("ignore_remaining_data", False)
return load(
BytesIO(string), *transformers, ignore_remaining_data=ignore_remaining_data
)
|
[
"def",
"loads",
"(",
"string",
",",
"*",
"transformers",
",",
"*",
"*",
"kwargs",
")",
":",
"# Read keyword argument",
"ignore_remaining_data",
"=",
"kwargs",
".",
"get",
"(",
"\"ignore_remaining_data\"",
",",
"False",
")",
"# Reuse the load method (avoid code duplication)",
"return",
"load",
"(",
"BytesIO",
"(",
"string",
")",
",",
"*",
"transformers",
",",
"ignore_remaining_data",
"=",
"ignore_remaining_data",
")"
] |
Deserializes Java objects and primitive data serialized using
ObjectOutputStream from a string.
:param string: A Java data string
:param transformers: Custom transformers to use
:param ignore_remaining_data: If True, don't log an error when unused
trailing bytes are remaining
:return: The deserialized object
|
[
"Deserializes",
"Java",
"objects",
"and",
"primitive",
"data",
"serialized",
"using",
"ObjectOutputStream",
"from",
"a",
"string",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L128-L145
|
tcalmant/python-javaobj
|
javaobj/core.py
|
dumps
|
def dumps(obj, *transformers):
"""
Serializes Java primitive data and objects unmarshaled by load(s) before
into string.
:param obj: A Python primitive object, or one loaded using load(s)
:param transformers: Custom transformers to use
:return: The serialized data as a string
"""
marshaller = JavaObjectMarshaller()
# Add custom transformers
for transformer in transformers:
marshaller.add_transformer(transformer)
return marshaller.dump(obj)
|
python
|
def dumps(obj, *transformers):
marshaller = JavaObjectMarshaller()
for transformer in transformers:
marshaller.add_transformer(transformer)
return marshaller.dump(obj)
|
[
"def",
"dumps",
"(",
"obj",
",",
"*",
"transformers",
")",
":",
"marshaller",
"=",
"JavaObjectMarshaller",
"(",
")",
"# Add custom transformers",
"for",
"transformer",
"in",
"transformers",
":",
"marshaller",
".",
"add_transformer",
"(",
"transformer",
")",
"return",
"marshaller",
".",
"dump",
"(",
"obj",
")"
] |
Serializes Java primitive data and objects unmarshaled by load(s) before
into string.
:param obj: A Python primitive object, or one loaded using load(s)
:param transformers: Custom transformers to use
:return: The serialized data as a string
|
[
"Serializes",
"Java",
"primitive",
"data",
"and",
"objects",
"unmarshaled",
"by",
"load",
"(",
"s",
")",
"before",
"into",
"string",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L148-L162
|
tcalmant/python-javaobj
|
javaobj/core.py
|
read
|
def read(data, fmt_str):
"""
Reads input bytes and extract the given structure. Returns both the read
elements and the remaining data
:param data: Data as bytes
:param fmt_str: Struct unpack format string
:return: A tuple (results as tuple, remaining data)
"""
size = struct.calcsize(fmt_str)
return struct.unpack(fmt_str, data[:size]), data[size:]
|
python
|
def read(data, fmt_str):
size = struct.calcsize(fmt_str)
return struct.unpack(fmt_str, data[:size]), data[size:]
|
[
"def",
"read",
"(",
"data",
",",
"fmt_str",
")",
":",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt_str",
")",
"return",
"struct",
".",
"unpack",
"(",
"fmt_str",
",",
"data",
"[",
":",
"size",
"]",
")",
",",
"data",
"[",
"size",
":",
"]"
] |
Reads input bytes and extract the given structure. Returns both the read
elements and the remaining data
:param data: Data as bytes
:param fmt_str: Struct unpack format string
:return: A tuple (results as tuple, remaining data)
|
[
"Reads",
"input",
"bytes",
"and",
"extract",
"the",
"given",
"structure",
".",
"Returns",
"both",
"the",
"read",
"elements",
"and",
"the",
"remaining",
"data"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1666-L1676
|
tcalmant/python-javaobj
|
javaobj/core.py
|
read_string
|
def read_string(data, length_fmt="H"):
"""
Reads a serialized string
:param data: Bytes where to read the string from
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
"""
(length,), data = read(data, ">{0}".format(length_fmt))
ba, data = data[:length], data[length:]
return to_unicode(ba), data
|
python
|
def read_string(data, length_fmt="H"):
(length,), data = read(data, ">{0}".format(length_fmt))
ba, data = data[:length], data[length:]
return to_unicode(ba), data
|
[
"def",
"read_string",
"(",
"data",
",",
"length_fmt",
"=",
"\"H\"",
")",
":",
"(",
"length",
",",
")",
",",
"data",
"=",
"read",
"(",
"data",
",",
"\">{0}\"",
".",
"format",
"(",
"length_fmt",
")",
")",
"ba",
",",
"data",
"=",
"data",
"[",
":",
"length",
"]",
",",
"data",
"[",
"length",
":",
"]",
"return",
"to_unicode",
"(",
"ba",
")",
",",
"data"
] |
Reads a serialized string
:param data: Bytes where to read the string from
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
|
[
"Reads",
"a",
"serialized",
"string"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1679-L1689
|
tcalmant/python-javaobj
|
javaobj/core.py
|
OpCodeDebug.flags
|
def flags(flags):
"""
Returns the names of the class description flags found in the given
integer
:param flags: A class description flag entry
:return: The flags names as a single string
"""
names = sorted(
descr for key, descr in OpCodeDebug.STREAM_CONSTANT.items() if key & flags
)
return ", ".join(names)
|
python
|
def flags(flags):
names = sorted(
descr for key, descr in OpCodeDebug.STREAM_CONSTANT.items() if key & flags
)
return ", ".join(names)
|
[
"def",
"flags",
"(",
"flags",
")",
":",
"names",
"=",
"sorted",
"(",
"descr",
"for",
"key",
",",
"descr",
"in",
"OpCodeDebug",
".",
"STREAM_CONSTANT",
".",
"items",
"(",
")",
"if",
"key",
"&",
"flags",
")",
"return",
"\", \"",
".",
"join",
"(",
"names",
")"
] |
Returns the names of the class description flags found in the given
integer
:param flags: A class description flag entry
:return: The flags names as a single string
|
[
"Returns",
"the",
"names",
"of",
"the",
"class",
"description",
"flags",
"found",
"in",
"the",
"given",
"integer"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L457-L468
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._readStreamHeader
|
def _readStreamHeader(self):
"""
Reads the magic header of a Java serialization stream
:raise IOError: Invalid magic header (not a Java stream)
"""
(magic, version) = self._readStruct(">HH")
if magic != self.STREAM_MAGIC or version != self.STREAM_VERSION:
raise IOError(
"The stream is not java serialized object. "
"Invalid stream header: {0:04X}{1:04X}".format(magic, version)
)
|
python
|
def _readStreamHeader(self):
(magic, version) = self._readStruct(">HH")
if magic != self.STREAM_MAGIC or version != self.STREAM_VERSION:
raise IOError(
"The stream is not java serialized object. "
"Invalid stream header: {0:04X}{1:04X}".format(magic, version)
)
|
[
"def",
"_readStreamHeader",
"(",
"self",
")",
":",
"(",
"magic",
",",
"version",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">HH\"",
")",
"if",
"magic",
"!=",
"self",
".",
"STREAM_MAGIC",
"or",
"version",
"!=",
"self",
".",
"STREAM_VERSION",
":",
"raise",
"IOError",
"(",
"\"The stream is not java serialized object. \"",
"\"Invalid stream header: {0:04X}{1:04X}\"",
".",
"format",
"(",
"magic",
",",
"version",
")",
")"
] |
Reads the magic header of a Java serialization stream
:raise IOError: Invalid magic header (not a Java stream)
|
[
"Reads",
"the",
"magic",
"header",
"of",
"a",
"Java",
"serialization",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L559-L570
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._read_and_exec_opcode
|
def _read_and_exec_opcode(self, ident=0, expect=None):
"""
Reads the next opcode, and executes its handler
:param ident: Log identation level
:param expect: A list of expected opcodes
:return: A tuple: (opcode, result of the handler)
:raise IOError: Read opcode is not one of the expected ones
:raise RuntimeError: Unknown opcode
"""
position = self.object_stream.tell()
(opid,) = self._readStruct(">B")
log_debug(
"OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})".format(
opid, OpCodeDebug.op_id(opid), position
),
ident,
)
if expect and opid not in expect:
raise IOError(
"Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})".format(
opid, OpCodeDebug.op_id(opid), position
)
)
try:
handler = self.opmap[opid]
except KeyError:
raise RuntimeError(
"Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})".format(
opid, position
)
)
else:
return opid, handler(ident=ident)
|
python
|
def _read_and_exec_opcode(self, ident=0, expect=None):
position = self.object_stream.tell()
(opid,) = self._readStruct(">B")
log_debug(
"OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})".format(
opid, OpCodeDebug.op_id(opid), position
),
ident,
)
if expect and opid not in expect:
raise IOError(
"Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})".format(
opid, OpCodeDebug.op_id(opid), position
)
)
try:
handler = self.opmap[opid]
except KeyError:
raise RuntimeError(
"Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})".format(
opid, position
)
)
else:
return opid, handler(ident=ident)
|
[
"def",
"_read_and_exec_opcode",
"(",
"self",
",",
"ident",
"=",
"0",
",",
"expect",
"=",
"None",
")",
":",
"position",
"=",
"self",
".",
"object_stream",
".",
"tell",
"(",
")",
"(",
"opid",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">B\"",
")",
"log_debug",
"(",
"\"OpCode: 0x{0:X} -- {1} (at offset 0x{2:X})\"",
".",
"format",
"(",
"opid",
",",
"OpCodeDebug",
".",
"op_id",
"(",
"opid",
")",
",",
"position",
")",
",",
"ident",
",",
")",
"if",
"expect",
"and",
"opid",
"not",
"in",
"expect",
":",
"raise",
"IOError",
"(",
"\"Unexpected opcode 0x{0:X} -- {1} (at offset 0x{2:X})\"",
".",
"format",
"(",
"opid",
",",
"OpCodeDebug",
".",
"op_id",
"(",
"opid",
")",
",",
"position",
")",
")",
"try",
":",
"handler",
"=",
"self",
".",
"opmap",
"[",
"opid",
"]",
"except",
"KeyError",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown OpCode in the stream: 0x{0:X} (at offset 0x{1:X})\"",
".",
"format",
"(",
"opid",
",",
"position",
")",
")",
"else",
":",
"return",
"opid",
",",
"handler",
"(",
"ident",
"=",
"ident",
")"
] |
Reads the next opcode, and executes its handler
:param ident: Log identation level
:param expect: A list of expected opcodes
:return: A tuple: (opcode, result of the handler)
:raise IOError: Read opcode is not one of the expected ones
:raise RuntimeError: Unknown opcode
|
[
"Reads",
"the",
"next",
"opcode",
"and",
"executes",
"its",
"handler"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L572-L607
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._readString
|
def _readString(self, length_fmt="H"):
"""
Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream
"""
(length,) = self._readStruct(">{0}".format(length_fmt))
ba = self.object_stream.read(length)
return to_unicode(ba)
|
python
|
def _readString(self, length_fmt="H"):
(length,) = self._readStruct(">{0}".format(length_fmt))
ba = self.object_stream.read(length)
return to_unicode(ba)
|
[
"def",
"_readString",
"(",
"self",
",",
"length_fmt",
"=",
"\"H\"",
")",
":",
"(",
"length",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">{0}\"",
".",
"format",
"(",
"length_fmt",
")",
")",
"ba",
"=",
"self",
".",
"object_stream",
".",
"read",
"(",
"length",
")",
"return",
"to_unicode",
"(",
"ba",
")"
] |
Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream
|
[
"Reads",
"a",
"serialized",
"string"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L625-L635
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller.do_classdesc
|
def do_classdesc(self, parent=None, ident=0):
"""
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
"""
# TC_CLASSDESC className serialVersionUID newHandle classDescInfo
# classDescInfo:
# classDescFlags fields classAnnotation superClassDesc
# classDescFlags:
# (byte) // Defined in Terminal Symbols and Constants
# fields:
# (short)<count> fieldDesc[count]
# fieldDesc:
# primitiveDesc
# objectDesc
# primitiveDesc:
# prim_typecode fieldName
# objectDesc:
# obj_typecode fieldName className1
clazz = JavaClass()
log_debug("[classdesc]", ident)
class_name = self._readString()
clazz.name = class_name
log_debug("Class name: %s" % class_name, ident)
# serialVersionUID is a Java (signed) long => 8 bytes
serialVersionUID, classDescFlags = self._readStruct(">qB")
clazz.serialVersionUID = serialVersionUID
clazz.flags = classDescFlags
self._add_reference(clazz, ident)
log_debug(
"Serial: 0x{0:X} / {0:d} - classDescFlags: 0x{1:X} {2}".format(
serialVersionUID, classDescFlags, OpCodeDebug.flags(classDescFlags)
),
ident,
)
(length,) = self._readStruct(">H")
log_debug("Fields num: 0x{0:X}".format(length), ident)
clazz.fields_names = []
clazz.fields_types = []
for fieldId in range(length):
(typecode,) = self._readStruct(">B")
field_name = self._readString()
field_type = self._convert_char_to_type(typecode)
log_debug("> Reading field {0}".format(field_name), ident)
if field_type == self.TYPE_ARRAY:
_, field_type = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
if type(field_type) is not JavaString:
raise AssertionError(
"Field type must be a JavaString, "
"not {0}".format(type(field_type))
)
elif field_type == self.TYPE_OBJECT:
_, field_type = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
if type(field_type) is JavaClass:
# FIXME: ugly trick
field_type = JavaString(field_type.name)
if type(field_type) is not JavaString:
raise AssertionError(
"Field type must be a JavaString, "
"not {0}".format(type(field_type))
)
log_debug(
"< FieldName: 0x{0:X} Name:{1} Type:{2} ID:{3}".format(
typecode, field_name, field_type, fieldId
),
ident,
)
assert field_name is not None
assert field_type is not None
clazz.fields_names.append(field_name)
clazz.fields_types.append(field_type)
if parent:
parent.__fields = clazz.fields_names
parent.__types = clazz.fields_types
# classAnnotation
(opid,) = self._readStruct(">B")
log_debug(
"OpCode: 0x{0:X} -- {1} (classAnnotation)".format(
opid, OpCodeDebug.op_id(opid)
),
ident,
)
if opid != self.TC_ENDBLOCKDATA:
raise NotImplementedError("classAnnotation isn't implemented yet")
# superClassDesc
log_debug("Reading Super Class of {0}".format(clazz.name), ident)
_, superclassdesc = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_CLASSDESC, self.TC_NULL, self.TC_REFERENCE)
)
log_debug(
"Super Class for {0}: {1}".format(clazz.name, str(superclassdesc)), ident
)
clazz.superclass = superclassdesc
return clazz
|
python
|
def do_classdesc(self, parent=None, ident=0):
clazz = JavaClass()
log_debug("[classdesc]", ident)
class_name = self._readString()
clazz.name = class_name
log_debug("Class name: %s" % class_name, ident)
serialVersionUID, classDescFlags = self._readStruct(">qB")
clazz.serialVersionUID = serialVersionUID
clazz.flags = classDescFlags
self._add_reference(clazz, ident)
log_debug(
"Serial: 0x{0:X} / {0:d} - classDescFlags: 0x{1:X} {2}".format(
serialVersionUID, classDescFlags, OpCodeDebug.flags(classDescFlags)
),
ident,
)
(length,) = self._readStruct(">H")
log_debug("Fields num: 0x{0:X}".format(length), ident)
clazz.fields_names = []
clazz.fields_types = []
for fieldId in range(length):
(typecode,) = self._readStruct(">B")
field_name = self._readString()
field_type = self._convert_char_to_type(typecode)
log_debug("> Reading field {0}".format(field_name), ident)
if field_type == self.TYPE_ARRAY:
_, field_type = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
if type(field_type) is not JavaString:
raise AssertionError(
"Field type must be a JavaString, "
"not {0}".format(type(field_type))
)
elif field_type == self.TYPE_OBJECT:
_, field_type = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
if type(field_type) is JavaClass:
field_type = JavaString(field_type.name)
if type(field_type) is not JavaString:
raise AssertionError(
"Field type must be a JavaString, "
"not {0}".format(type(field_type))
)
log_debug(
"< FieldName: 0x{0:X} Name:{1} Type:{2} ID:{3}".format(
typecode, field_name, field_type, fieldId
),
ident,
)
assert field_name is not None
assert field_type is not None
clazz.fields_names.append(field_name)
clazz.fields_types.append(field_type)
if parent:
parent.__fields = clazz.fields_names
parent.__types = clazz.fields_types
(opid,) = self._readStruct(">B")
log_debug(
"OpCode: 0x{0:X} -- {1} (classAnnotation)".format(
opid, OpCodeDebug.op_id(opid)
),
ident,
)
if opid != self.TC_ENDBLOCKDATA:
raise NotImplementedError("classAnnotation isn't implemented yet")
log_debug("Reading Super Class of {0}".format(clazz.name), ident)
_, superclassdesc = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_CLASSDESC, self.TC_NULL, self.TC_REFERENCE)
)
log_debug(
"Super Class for {0}: {1}".format(clazz.name, str(superclassdesc)), ident
)
clazz.superclass = superclassdesc
return clazz
|
[
"def",
"do_classdesc",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"# TC_CLASSDESC className serialVersionUID newHandle classDescInfo",
"# classDescInfo:",
"# classDescFlags fields classAnnotation superClassDesc",
"# classDescFlags:",
"# (byte) // Defined in Terminal Symbols and Constants",
"# fields:",
"# (short)<count> fieldDesc[count]",
"# fieldDesc:",
"# primitiveDesc",
"# objectDesc",
"# primitiveDesc:",
"# prim_typecode fieldName",
"# objectDesc:",
"# obj_typecode fieldName className1",
"clazz",
"=",
"JavaClass",
"(",
")",
"log_debug",
"(",
"\"[classdesc]\"",
",",
"ident",
")",
"class_name",
"=",
"self",
".",
"_readString",
"(",
")",
"clazz",
".",
"name",
"=",
"class_name",
"log_debug",
"(",
"\"Class name: %s\"",
"%",
"class_name",
",",
"ident",
")",
"# serialVersionUID is a Java (signed) long => 8 bytes",
"serialVersionUID",
",",
"classDescFlags",
"=",
"self",
".",
"_readStruct",
"(",
"\">qB\"",
")",
"clazz",
".",
"serialVersionUID",
"=",
"serialVersionUID",
"clazz",
".",
"flags",
"=",
"classDescFlags",
"self",
".",
"_add_reference",
"(",
"clazz",
",",
"ident",
")",
"log_debug",
"(",
"\"Serial: 0x{0:X} / {0:d} - classDescFlags: 0x{1:X} {2}\"",
".",
"format",
"(",
"serialVersionUID",
",",
"classDescFlags",
",",
"OpCodeDebug",
".",
"flags",
"(",
"classDescFlags",
")",
")",
",",
"ident",
",",
")",
"(",
"length",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">H\"",
")",
"log_debug",
"(",
"\"Fields num: 0x{0:X}\"",
".",
"format",
"(",
"length",
")",
",",
"ident",
")",
"clazz",
".",
"fields_names",
"=",
"[",
"]",
"clazz",
".",
"fields_types",
"=",
"[",
"]",
"for",
"fieldId",
"in",
"range",
"(",
"length",
")",
":",
"(",
"typecode",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">B\"",
")",
"field_name",
"=",
"self",
".",
"_readString",
"(",
")",
"field_type",
"=",
"self",
".",
"_convert_char_to_type",
"(",
"typecode",
")",
"log_debug",
"(",
"\"> Reading field {0}\"",
".",
"format",
"(",
"field_name",
")",
",",
"ident",
")",
"if",
"field_type",
"==",
"self",
".",
"TYPE_ARRAY",
":",
"_",
",",
"field_type",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_STRING",
",",
"self",
".",
"TC_REFERENCE",
")",
")",
"if",
"type",
"(",
"field_type",
")",
"is",
"not",
"JavaString",
":",
"raise",
"AssertionError",
"(",
"\"Field type must be a JavaString, \"",
"\"not {0}\"",
".",
"format",
"(",
"type",
"(",
"field_type",
")",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_OBJECT",
":",
"_",
",",
"field_type",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_STRING",
",",
"self",
".",
"TC_REFERENCE",
")",
")",
"if",
"type",
"(",
"field_type",
")",
"is",
"JavaClass",
":",
"# FIXME: ugly trick",
"field_type",
"=",
"JavaString",
"(",
"field_type",
".",
"name",
")",
"if",
"type",
"(",
"field_type",
")",
"is",
"not",
"JavaString",
":",
"raise",
"AssertionError",
"(",
"\"Field type must be a JavaString, \"",
"\"not {0}\"",
".",
"format",
"(",
"type",
"(",
"field_type",
")",
")",
")",
"log_debug",
"(",
"\"< FieldName: 0x{0:X} Name:{1} Type:{2} ID:{3}\"",
".",
"format",
"(",
"typecode",
",",
"field_name",
",",
"field_type",
",",
"fieldId",
")",
",",
"ident",
",",
")",
"assert",
"field_name",
"is",
"not",
"None",
"assert",
"field_type",
"is",
"not",
"None",
"clazz",
".",
"fields_names",
".",
"append",
"(",
"field_name",
")",
"clazz",
".",
"fields_types",
".",
"append",
"(",
"field_type",
")",
"if",
"parent",
":",
"parent",
".",
"__fields",
"=",
"clazz",
".",
"fields_names",
"parent",
".",
"__types",
"=",
"clazz",
".",
"fields_types",
"# classAnnotation",
"(",
"opid",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">B\"",
")",
"log_debug",
"(",
"\"OpCode: 0x{0:X} -- {1} (classAnnotation)\"",
".",
"format",
"(",
"opid",
",",
"OpCodeDebug",
".",
"op_id",
"(",
"opid",
")",
")",
",",
"ident",
",",
")",
"if",
"opid",
"!=",
"self",
".",
"TC_ENDBLOCKDATA",
":",
"raise",
"NotImplementedError",
"(",
"\"classAnnotation isn't implemented yet\"",
")",
"# superClassDesc",
"log_debug",
"(",
"\"Reading Super Class of {0}\"",
".",
"format",
"(",
"clazz",
".",
"name",
")",
",",
"ident",
")",
"_",
",",
"superclassdesc",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_CLASSDESC",
",",
"self",
".",
"TC_NULL",
",",
"self",
".",
"TC_REFERENCE",
")",
")",
"log_debug",
"(",
"\"Super Class for {0}: {1}\"",
".",
"format",
"(",
"clazz",
".",
"name",
",",
"str",
"(",
"superclassdesc",
")",
")",
",",
"ident",
")",
"clazz",
".",
"superclass",
"=",
"superclassdesc",
"return",
"clazz"
] |
Handles a TC_CLASSDESC opcode
:param parent:
:param ident: Log indentation level
:return: A JavaClass object
|
[
"Handles",
"a",
"TC_CLASSDESC",
"opcode"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L637-L753
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller.do_string
|
def do_string(self, parent=None, ident=0):
"""
Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string
"""
log_debug("[string]", ident)
ba = JavaString(self._readString())
self._add_reference(ba, ident)
return ba
|
python
|
def do_string(self, parent=None, ident=0):
log_debug("[string]", ident)
ba = JavaString(self._readString())
self._add_reference(ba, ident)
return ba
|
[
"def",
"do_string",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"log_debug",
"(",
"\"[string]\"",
",",
"ident",
")",
"ba",
"=",
"JavaString",
"(",
"self",
".",
"_readString",
"(",
")",
")",
"self",
".",
"_add_reference",
"(",
"ba",
",",
"ident",
")",
"return",
"ba"
] |
Handles a TC_STRING opcode
:param parent:
:param ident: Log indentation level
:return: A string
|
[
"Handles",
"a",
"TC_STRING",
"opcode"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L941-L952
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller.do_array
|
def do_array(self, parent=None, ident=0):
"""
Handles a TC_ARRAY opcode
:param parent:
:param ident: Log indentation level
:return: A list of deserialized objects
"""
# TC_ARRAY classDesc newHandle (int)<size> values[size]
log_debug("[array]", ident)
_, classdesc = self._read_and_exec_opcode(
ident=ident + 1,
expect=(
self.TC_CLASSDESC,
self.TC_PROXYCLASSDESC,
self.TC_NULL,
self.TC_REFERENCE,
),
)
array = JavaArray(classdesc)
self._add_reference(array, ident)
(size,) = self._readStruct(">i")
log_debug("size: {0}".format(size), ident)
type_char = classdesc.name[0]
assert type_char == self.TYPE_ARRAY
type_char = classdesc.name[1]
if type_char == self.TYPE_OBJECT or type_char == self.TYPE_ARRAY:
for _ in range(size):
_, res = self._read_and_exec_opcode(ident=ident + 1)
log_debug("Object value: {0}".format(res), ident)
array.append(res)
elif type_char == self.TYPE_BYTE:
array = JavaByteArray(self.object_stream.read(size), classdesc)
elif self.use_numpy_arrays:
import numpy
array = numpy.fromfile(
self.object_stream,
dtype=JavaObjectConstants.NUMPY_TYPE_MAP[type_char],
count=size,
)
else:
for _ in range(size):
res = self._read_value(type_char, ident)
log_debug("Native value: {0}".format(repr(res)), ident)
array.append(res)
return array
|
python
|
def do_array(self, parent=None, ident=0):
log_debug("[array]", ident)
_, classdesc = self._read_and_exec_opcode(
ident=ident + 1,
expect=(
self.TC_CLASSDESC,
self.TC_PROXYCLASSDESC,
self.TC_NULL,
self.TC_REFERENCE,
),
)
array = JavaArray(classdesc)
self._add_reference(array, ident)
(size,) = self._readStruct(">i")
log_debug("size: {0}".format(size), ident)
type_char = classdesc.name[0]
assert type_char == self.TYPE_ARRAY
type_char = classdesc.name[1]
if type_char == self.TYPE_OBJECT or type_char == self.TYPE_ARRAY:
for _ in range(size):
_, res = self._read_and_exec_opcode(ident=ident + 1)
log_debug("Object value: {0}".format(res), ident)
array.append(res)
elif type_char == self.TYPE_BYTE:
array = JavaByteArray(self.object_stream.read(size), classdesc)
elif self.use_numpy_arrays:
import numpy
array = numpy.fromfile(
self.object_stream,
dtype=JavaObjectConstants.NUMPY_TYPE_MAP[type_char],
count=size,
)
else:
for _ in range(size):
res = self._read_value(type_char, ident)
log_debug("Native value: {0}".format(repr(res)), ident)
array.append(res)
return array
|
[
"def",
"do_array",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"# TC_ARRAY classDesc newHandle (int)<size> values[size]",
"log_debug",
"(",
"\"[array]\"",
",",
"ident",
")",
"_",
",",
"classdesc",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_CLASSDESC",
",",
"self",
".",
"TC_PROXYCLASSDESC",
",",
"self",
".",
"TC_NULL",
",",
"self",
".",
"TC_REFERENCE",
",",
")",
",",
")",
"array",
"=",
"JavaArray",
"(",
"classdesc",
")",
"self",
".",
"_add_reference",
"(",
"array",
",",
"ident",
")",
"(",
"size",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">i\"",
")",
"log_debug",
"(",
"\"size: {0}\"",
".",
"format",
"(",
"size",
")",
",",
"ident",
")",
"type_char",
"=",
"classdesc",
".",
"name",
"[",
"0",
"]",
"assert",
"type_char",
"==",
"self",
".",
"TYPE_ARRAY",
"type_char",
"=",
"classdesc",
".",
"name",
"[",
"1",
"]",
"if",
"type_char",
"==",
"self",
".",
"TYPE_OBJECT",
"or",
"type_char",
"==",
"self",
".",
"TYPE_ARRAY",
":",
"for",
"_",
"in",
"range",
"(",
"size",
")",
":",
"_",
",",
"res",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
")",
"log_debug",
"(",
"\"Object value: {0}\"",
".",
"format",
"(",
"res",
")",
",",
"ident",
")",
"array",
".",
"append",
"(",
"res",
")",
"elif",
"type_char",
"==",
"self",
".",
"TYPE_BYTE",
":",
"array",
"=",
"JavaByteArray",
"(",
"self",
".",
"object_stream",
".",
"read",
"(",
"size",
")",
",",
"classdesc",
")",
"elif",
"self",
".",
"use_numpy_arrays",
":",
"import",
"numpy",
"array",
"=",
"numpy",
".",
"fromfile",
"(",
"self",
".",
"object_stream",
",",
"dtype",
"=",
"JavaObjectConstants",
".",
"NUMPY_TYPE_MAP",
"[",
"type_char",
"]",
",",
"count",
"=",
"size",
",",
")",
"else",
":",
"for",
"_",
"in",
"range",
"(",
"size",
")",
":",
"res",
"=",
"self",
".",
"_read_value",
"(",
"type_char",
",",
"ident",
")",
"log_debug",
"(",
"\"Native value: {0}\"",
".",
"format",
"(",
"repr",
"(",
"res",
")",
")",
",",
"ident",
")",
"array",
".",
"append",
"(",
"res",
")",
"return",
"array"
] |
Handles a TC_ARRAY opcode
:param parent:
:param ident: Log indentation level
:return: A list of deserialized objects
|
[
"Handles",
"a",
"TC_ARRAY",
"opcode"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L967-L1019
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller.do_reference
|
def do_reference(self, parent=None, ident=0):
"""
Handles a TC_REFERENCE opcode
:param parent:
:param ident: Log indentation level
:return: The referenced object
"""
(handle,) = self._readStruct(">L")
log_debug("## Reference handle: 0x{0:X}".format(handle), ident)
ref = self.references[handle - self.BASE_REFERENCE_IDX]
log_debug("###-> Type: {0} - Value: {1}".format(type(ref), ref), ident)
return ref
|
python
|
def do_reference(self, parent=None, ident=0):
(handle,) = self._readStruct(">L")
log_debug("
ref = self.references[handle - self.BASE_REFERENCE_IDX]
log_debug("
return ref
|
[
"def",
"do_reference",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"(",
"handle",
",",
")",
"=",
"self",
".",
"_readStruct",
"(",
"\">L\"",
")",
"log_debug",
"(",
"\"## Reference handle: 0x{0:X}\"",
".",
"format",
"(",
"handle",
")",
",",
"ident",
")",
"ref",
"=",
"self",
".",
"references",
"[",
"handle",
"-",
"self",
".",
"BASE_REFERENCE_IDX",
"]",
"log_debug",
"(",
"\"###-> Type: {0} - Value: {1}\"",
".",
"format",
"(",
"type",
"(",
"ref",
")",
",",
"ref",
")",
",",
"ident",
")",
"return",
"ref"
] |
Handles a TC_REFERENCE opcode
:param parent:
:param ident: Log indentation level
:return: The referenced object
|
[
"Handles",
"a",
"TC_REFERENCE",
"opcode"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1021-L1033
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller.do_enum
|
def do_enum(self, parent=None, ident=0):
"""
Handles a TC_ENUM opcode
:param parent:
:param ident: Log indentation level
:return: A JavaEnum object
"""
# TC_ENUM classDesc newHandle enumConstantName
enum = JavaEnum()
_, classdesc = self._read_and_exec_opcode(
ident=ident + 1,
expect=(
self.TC_CLASSDESC,
self.TC_PROXYCLASSDESC,
self.TC_NULL,
self.TC_REFERENCE,
),
)
enum.classdesc = classdesc
self._add_reference(enum, ident)
_, enumConstantName = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
enum.constant = enumConstantName
return enum
|
python
|
def do_enum(self, parent=None, ident=0):
enum = JavaEnum()
_, classdesc = self._read_and_exec_opcode(
ident=ident + 1,
expect=(
self.TC_CLASSDESC,
self.TC_PROXYCLASSDESC,
self.TC_NULL,
self.TC_REFERENCE,
),
)
enum.classdesc = classdesc
self._add_reference(enum, ident)
_, enumConstantName = self._read_and_exec_opcode(
ident=ident + 1, expect=(self.TC_STRING, self.TC_REFERENCE)
)
enum.constant = enumConstantName
return enum
|
[
"def",
"do_enum",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"ident",
"=",
"0",
")",
":",
"# TC_ENUM classDesc newHandle enumConstantName",
"enum",
"=",
"JavaEnum",
"(",
")",
"_",
",",
"classdesc",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_CLASSDESC",
",",
"self",
".",
"TC_PROXYCLASSDESC",
",",
"self",
".",
"TC_NULL",
",",
"self",
".",
"TC_REFERENCE",
",",
")",
",",
")",
"enum",
".",
"classdesc",
"=",
"classdesc",
"self",
".",
"_add_reference",
"(",
"enum",
",",
"ident",
")",
"_",
",",
"enumConstantName",
"=",
"self",
".",
"_read_and_exec_opcode",
"(",
"ident",
"=",
"ident",
"+",
"1",
",",
"expect",
"=",
"(",
"self",
".",
"TC_STRING",
",",
"self",
".",
"TC_REFERENCE",
")",
")",
"enum",
".",
"constant",
"=",
"enumConstantName",
"return",
"enum"
] |
Handles a TC_ENUM opcode
:param parent:
:param ident: Log indentation level
:return: A JavaEnum object
|
[
"Handles",
"a",
"TC_ENUM",
"opcode"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1046-L1071
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._create_hexdump
|
def _create_hexdump(src, start_offset=0, length=16):
"""
Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string
"""
FILTER = "".join((len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256))
pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n".format(length * 3)
# Convert raw data to str (Python 3 compatibility)
src = to_str(src, "latin-1")
result = []
for i in range(0, len(src), length):
s = src[i : i + length]
hexa = " ".join("{0:02X}".format(ord(x)) for x in s)
printable = s.translate(FILTER)
result.append(pattern.format(i + start_offset, hexa, printable))
return "".join(result)
|
python
|
def _create_hexdump(src, start_offset=0, length=16):
FILTER = "".join((len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256))
pattern = "{{0:04X}} {{1:<{0}}} {{2}}\n".format(length * 3)
src = to_str(src, "latin-1")
result = []
for i in range(0, len(src), length):
s = src[i : i + length]
hexa = " ".join("{0:02X}".format(ord(x)) for x in s)
printable = s.translate(FILTER)
result.append(pattern.format(i + start_offset, hexa, printable))
return "".join(result)
|
[
"def",
"_create_hexdump",
"(",
"src",
",",
"start_offset",
"=",
"0",
",",
"length",
"=",
"16",
")",
":",
"FILTER",
"=",
"\"\"",
".",
"join",
"(",
"(",
"len",
"(",
"repr",
"(",
"chr",
"(",
"x",
")",
")",
")",
"==",
"3",
")",
"and",
"chr",
"(",
"x",
")",
"or",
"\".\"",
"for",
"x",
"in",
"range",
"(",
"256",
")",
")",
"pattern",
"=",
"\"{{0:04X}} {{1:<{0}}} {{2}}\\n\"",
".",
"format",
"(",
"length",
"*",
"3",
")",
"# Convert raw data to str (Python 3 compatibility)",
"src",
"=",
"to_str",
"(",
"src",
",",
"\"latin-1\"",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"src",
")",
",",
"length",
")",
":",
"s",
"=",
"src",
"[",
"i",
":",
"i",
"+",
"length",
"]",
"hexa",
"=",
"\" \"",
".",
"join",
"(",
"\"{0:02X}\"",
".",
"format",
"(",
"ord",
"(",
"x",
")",
")",
"for",
"x",
"in",
"s",
")",
"printable",
"=",
"s",
".",
"translate",
"(",
"FILTER",
")",
"result",
".",
"append",
"(",
"pattern",
".",
"format",
"(",
"i",
"+",
"start_offset",
",",
"hexa",
",",
"printable",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"result",
")"
] |
Prepares an hexadecimal dump string
:param src: A string containing binary data
:param start_offset: The start offset of the source
:param length: Length of a dump line
:return: A dump string
|
[
"Prepares",
"an",
"hexadecimal",
"dump",
"string"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1074-L1096
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._convert_char_to_type
|
def _convert_char_to_type(self, type_char):
"""
Ensures a read character is a typecode.
:param type_char: Read typecode
:return: The typecode as a string (using chr)
:raise RuntimeError: Unknown typecode
"""
typecode = type_char
if type(type_char) is int:
typecode = chr(type_char)
if typecode in self.TYPECODES_LIST:
return typecode
else:
raise RuntimeError(
"Typecode {0} ({1}) isn't supported.".format(type_char, typecode)
)
|
python
|
def _convert_char_to_type(self, type_char):
typecode = type_char
if type(type_char) is int:
typecode = chr(type_char)
if typecode in self.TYPECODES_LIST:
return typecode
else:
raise RuntimeError(
"Typecode {0} ({1}) isn't supported.".format(type_char, typecode)
)
|
[
"def",
"_convert_char_to_type",
"(",
"self",
",",
"type_char",
")",
":",
"typecode",
"=",
"type_char",
"if",
"type",
"(",
"type_char",
")",
"is",
"int",
":",
"typecode",
"=",
"chr",
"(",
"type_char",
")",
"if",
"typecode",
"in",
"self",
".",
"TYPECODES_LIST",
":",
"return",
"typecode",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Typecode {0} ({1}) isn't supported.\"",
".",
"format",
"(",
"type_char",
",",
"typecode",
")",
")"
] |
Ensures a read character is a typecode.
:param type_char: Read typecode
:return: The typecode as a string (using chr)
:raise RuntimeError: Unknown typecode
|
[
"Ensures",
"a",
"read",
"character",
"is",
"a",
"typecode",
"."
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1140-L1157
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._add_reference
|
def _add_reference(self, obj, ident=0):
"""
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
"""
log_debug(
"## New reference handle 0x{0:X}: {1} -> {2}".format(
len(self.references) + self.BASE_REFERENCE_IDX,
type(obj).__name__,
repr(obj),
),
ident,
)
self.references.append(obj)
|
python
|
def _add_reference(self, obj, ident=0):
log_debug(
"
len(self.references) + self.BASE_REFERENCE_IDX,
type(obj).__name__,
repr(obj),
),
ident,
)
self.references.append(obj)
|
[
"def",
"_add_reference",
"(",
"self",
",",
"obj",
",",
"ident",
"=",
"0",
")",
":",
"log_debug",
"(",
"\"## New reference handle 0x{0:X}: {1} -> {2}\"",
".",
"format",
"(",
"len",
"(",
"self",
".",
"references",
")",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"type",
"(",
"obj",
")",
".",
"__name__",
",",
"repr",
"(",
"obj",
")",
",",
")",
",",
"ident",
",",
")",
"self",
".",
"references",
".",
"append",
"(",
"obj",
")"
] |
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
|
[
"Adds",
"a",
"read",
"reference",
"to",
"the",
"marshaler",
"storage"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1159-L1174
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectUnmarshaller._oops_dump_state
|
def _oops_dump_state(self, ignore_remaining_data=False):
"""
Log a deserialization error
:param ignore_remaining_data: If True, don't log an error when
unused trailing bytes are remaining
"""
log_error("==Oops state dump" + "=" * (30 - 17))
log_error("References: {0}".format(self.references))
log_error("Stream seeking back at -16 byte (2nd line is an actual position!):")
# Do not use a keyword argument
self.object_stream.seek(-16, os.SEEK_CUR)
position = self.object_stream.tell()
the_rest = self.object_stream.read()
if not ignore_remaining_data and len(the_rest):
log_error(
"Warning!!!!: Stream still has {0} bytes left:\n{1}".format(
len(the_rest), self._create_hexdump(the_rest, position)
)
)
log_error("=" * 30)
|
python
|
def _oops_dump_state(self, ignore_remaining_data=False):
log_error("==Oops state dump" + "=" * (30 - 17))
log_error("References: {0}".format(self.references))
log_error("Stream seeking back at -16 byte (2nd line is an actual position!):")
self.object_stream.seek(-16, os.SEEK_CUR)
position = self.object_stream.tell()
the_rest = self.object_stream.read()
if not ignore_remaining_data and len(the_rest):
log_error(
"Warning!!!!: Stream still has {0} bytes left:\n{1}".format(
len(the_rest), self._create_hexdump(the_rest, position)
)
)
log_error("=" * 30)
|
[
"def",
"_oops_dump_state",
"(",
"self",
",",
"ignore_remaining_data",
"=",
"False",
")",
":",
"log_error",
"(",
"\"==Oops state dump\"",
"+",
"\"=\"",
"*",
"(",
"30",
"-",
"17",
")",
")",
"log_error",
"(",
"\"References: {0}\"",
".",
"format",
"(",
"self",
".",
"references",
")",
")",
"log_error",
"(",
"\"Stream seeking back at -16 byte (2nd line is an actual position!):\"",
")",
"# Do not use a keyword argument",
"self",
".",
"object_stream",
".",
"seek",
"(",
"-",
"16",
",",
"os",
".",
"SEEK_CUR",
")",
"position",
"=",
"self",
".",
"object_stream",
".",
"tell",
"(",
")",
"the_rest",
"=",
"self",
".",
"object_stream",
".",
"read",
"(",
")",
"if",
"not",
"ignore_remaining_data",
"and",
"len",
"(",
"the_rest",
")",
":",
"log_error",
"(",
"\"Warning!!!!: Stream still has {0} bytes left:\\n{1}\"",
".",
"format",
"(",
"len",
"(",
"the_rest",
")",
",",
"self",
".",
"_create_hexdump",
"(",
"the_rest",
",",
"position",
")",
")",
")",
"log_error",
"(",
"\"=\"",
"*",
"30",
")"
] |
Log a deserialization error
:param ignore_remaining_data: If True, don't log an error when
unused trailing bytes are remaining
|
[
"Log",
"a",
"deserialization",
"error"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1176-L1199
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.dump
|
def dump(self, obj):
"""
Dumps the given object in the Java serialization format
"""
self.references = []
self.object_obj = obj
self.object_stream = BytesIO()
self._writeStreamHeader()
self.writeObject(obj)
return self.object_stream.getvalue()
|
python
|
def dump(self, obj):
self.references = []
self.object_obj = obj
self.object_stream = BytesIO()
self._writeStreamHeader()
self.writeObject(obj)
return self.object_stream.getvalue()
|
[
"def",
"dump",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"references",
"=",
"[",
"]",
"self",
".",
"object_obj",
"=",
"obj",
"self",
".",
"object_stream",
"=",
"BytesIO",
"(",
")",
"self",
".",
"_writeStreamHeader",
"(",
")",
"self",
".",
"writeObject",
"(",
"obj",
")",
"return",
"self",
".",
"object_stream",
".",
"getvalue",
"(",
")"
] |
Dumps the given object in the Java serialization format
|
[
"Dumps",
"the",
"given",
"object",
"in",
"the",
"Java",
"serialization",
"format"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1229-L1238
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.writeObject
|
def writeObject(self, obj):
"""
Appends an object to the serialization stream
:param obj: A string or a deserialized Java object
:raise RuntimeError: Unsupported type
"""
log_debug("Writing object of type {0}".format(type(obj).__name__))
if isinstance(obj, JavaArray):
# Deserialized Java array
self.write_array(obj)
elif isinstance(obj, JavaEnum):
# Deserialized Java Enum
self.write_enum(obj)
elif isinstance(obj, JavaObject):
# Deserialized Java object
self.write_object(obj)
elif isinstance(obj, JavaString):
# Deserialized String
self.write_string(obj)
elif isinstance(obj, JavaClass):
# Java class
self.write_class(obj)
elif obj is None:
# Null
self.write_null()
elif type(obj) is str:
# String value
self.write_blockdata(obj)
else:
# Unhandled type
raise RuntimeError(
"Object serialization of type {0} is not "
"supported.".format(type(obj))
)
|
python
|
def writeObject(self, obj):
log_debug("Writing object of type {0}".format(type(obj).__name__))
if isinstance(obj, JavaArray):
self.write_array(obj)
elif isinstance(obj, JavaEnum):
self.write_enum(obj)
elif isinstance(obj, JavaObject):
self.write_object(obj)
elif isinstance(obj, JavaString):
self.write_string(obj)
elif isinstance(obj, JavaClass):
self.write_class(obj)
elif obj is None:
self.write_null()
elif type(obj) is str:
self.write_blockdata(obj)
else:
raise RuntimeError(
"Object serialization of type {0} is not "
"supported.".format(type(obj))
)
|
[
"def",
"writeObject",
"(",
"self",
",",
"obj",
")",
":",
"log_debug",
"(",
"\"Writing object of type {0}\"",
".",
"format",
"(",
"type",
"(",
"obj",
")",
".",
"__name__",
")",
")",
"if",
"isinstance",
"(",
"obj",
",",
"JavaArray",
")",
":",
"# Deserialized Java array",
"self",
".",
"write_array",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"JavaEnum",
")",
":",
"# Deserialized Java Enum",
"self",
".",
"write_enum",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"JavaObject",
")",
":",
"# Deserialized Java object",
"self",
".",
"write_object",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"JavaString",
")",
":",
"# Deserialized String",
"self",
".",
"write_string",
"(",
"obj",
")",
"elif",
"isinstance",
"(",
"obj",
",",
"JavaClass",
")",
":",
"# Java class",
"self",
".",
"write_class",
"(",
"obj",
")",
"elif",
"obj",
"is",
"None",
":",
"# Null",
"self",
".",
"write_null",
"(",
")",
"elif",
"type",
"(",
"obj",
")",
"is",
"str",
":",
"# String value",
"self",
".",
"write_blockdata",
"(",
"obj",
")",
"else",
":",
"# Unhandled type",
"raise",
"RuntimeError",
"(",
"\"Object serialization of type {0} is not \"",
"\"supported.\"",
".",
"format",
"(",
"type",
"(",
"obj",
")",
")",
")"
] |
Appends an object to the serialization stream
:param obj: A string or a deserialized Java object
:raise RuntimeError: Unsupported type
|
[
"Appends",
"an",
"object",
"to",
"the",
"serialization",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1246-L1280
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller._writeString
|
def _writeString(self, obj, use_reference=True):
"""
Appends a string to the serialization stream
:param obj: String to serialize
:param use_reference: If True, allow writing a reference
"""
# TODO: Convert to "modified UTF-8"
# http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8
string = to_bytes(obj, "utf-8")
if use_reference and isinstance(obj, JavaString):
try:
idx = self.references.index(obj)
except ValueError:
# First appearance of the string
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for string: %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
self._writeStruct(">H", 2, (len(string),))
self.object_stream.write(string)
else:
# Write a reference to the previous type
logging.debug(
"*** Reusing ref 0x%X for string: %s",
idx + self.BASE_REFERENCE_IDX,
obj,
)
self.write_reference(idx)
else:
self._writeStruct(">H", 2, (len(string),))
self.object_stream.write(string)
|
python
|
def _writeString(self, obj, use_reference=True):
string = to_bytes(obj, "utf-8")
if use_reference and isinstance(obj, JavaString):
try:
idx = self.references.index(obj)
except ValueError:
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for string: %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
self._writeStruct(">H", 2, (len(string),))
self.object_stream.write(string)
else:
logging.debug(
"*** Reusing ref 0x%X for string: %s",
idx + self.BASE_REFERENCE_IDX,
obj,
)
self.write_reference(idx)
else:
self._writeStruct(">H", 2, (len(string),))
self.object_stream.write(string)
|
[
"def",
"_writeString",
"(",
"self",
",",
"obj",
",",
"use_reference",
"=",
"True",
")",
":",
"# TODO: Convert to \"modified UTF-8\"",
"# http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8",
"string",
"=",
"to_bytes",
"(",
"obj",
",",
"\"utf-8\"",
")",
"if",
"use_reference",
"and",
"isinstance",
"(",
"obj",
",",
"JavaString",
")",
":",
"try",
":",
"idx",
"=",
"self",
".",
"references",
".",
"index",
"(",
"obj",
")",
"except",
"ValueError",
":",
"# First appearance of the string",
"self",
".",
"references",
".",
"append",
"(",
"obj",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for string: %s\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
",",
")",
"self",
".",
"_writeStruct",
"(",
"\">H\"",
",",
"2",
",",
"(",
"len",
"(",
"string",
")",
",",
")",
")",
"self",
".",
"object_stream",
".",
"write",
"(",
"string",
")",
"else",
":",
"# Write a reference to the previous type",
"logging",
".",
"debug",
"(",
"\"*** Reusing ref 0x%X for string: %s\"",
",",
"idx",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
",",
")",
"self",
".",
"write_reference",
"(",
"idx",
")",
"else",
":",
"self",
".",
"_writeStruct",
"(",
"\">H\"",
",",
"2",
",",
"(",
"len",
"(",
"string",
")",
",",
")",
")",
"self",
".",
"object_stream",
".",
"write",
"(",
"string",
")"
] |
Appends a string to the serialization stream
:param obj: String to serialize
:param use_reference: If True, allow writing a reference
|
[
"Appends",
"a",
"string",
"to",
"the",
"serialization",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1293-L1328
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_string
|
def write_string(self, obj, use_reference=True):
"""
Writes a Java string with the TC_STRING type marker
:param obj: The string to print
:param use_reference: If True, allow writing a reference
"""
if use_reference and isinstance(obj, JavaString):
try:
idx = self.references.index(obj)
except ValueError:
# String is not referenced: let _writeString store it
self._writeStruct(">B", 1, (self.TC_STRING,))
self._writeString(obj, use_reference)
else:
# Reuse the referenced string
logging.debug(
"*** Reusing ref 0x%X for String: %s",
idx + self.BASE_REFERENCE_IDX,
obj,
)
self.write_reference(idx)
else:
# Don't use references
self._writeStruct(">B", 1, (self.TC_STRING,))
self._writeString(obj, use_reference)
|
python
|
def write_string(self, obj, use_reference=True):
if use_reference and isinstance(obj, JavaString):
try:
idx = self.references.index(obj)
except ValueError:
self._writeStruct(">B", 1, (self.TC_STRING,))
self._writeString(obj, use_reference)
else:
logging.debug(
"*** Reusing ref 0x%X for String: %s",
idx + self.BASE_REFERENCE_IDX,
obj,
)
self.write_reference(idx)
else:
self._writeStruct(">B", 1, (self.TC_STRING,))
self._writeString(obj, use_reference)
|
[
"def",
"write_string",
"(",
"self",
",",
"obj",
",",
"use_reference",
"=",
"True",
")",
":",
"if",
"use_reference",
"and",
"isinstance",
"(",
"obj",
",",
"JavaString",
")",
":",
"try",
":",
"idx",
"=",
"self",
".",
"references",
".",
"index",
"(",
"obj",
")",
"except",
"ValueError",
":",
"# String is not referenced: let _writeString store it",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_STRING",
",",
")",
")",
"self",
".",
"_writeString",
"(",
"obj",
",",
"use_reference",
")",
"else",
":",
"# Reuse the referenced string",
"logging",
".",
"debug",
"(",
"\"*** Reusing ref 0x%X for String: %s\"",
",",
"idx",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
",",
")",
"self",
".",
"write_reference",
"(",
"idx",
")",
"else",
":",
"# Don't use references",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_STRING",
",",
")",
")",
"self",
".",
"_writeString",
"(",
"obj",
",",
"use_reference",
")"
] |
Writes a Java string with the TC_STRING type marker
:param obj: The string to print
:param use_reference: If True, allow writing a reference
|
[
"Writes",
"a",
"Java",
"string",
"with",
"the",
"TC_STRING",
"type",
"marker"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1330-L1355
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_enum
|
def write_enum(self, obj):
"""
Writes an Enum value
:param obj: A JavaEnum object
"""
# FIXME: the output doesn't have the same references as the real
# serializable form
self._writeStruct(">B", 1, (self.TC_ENUM,))
try:
idx = self.references.index(obj)
except ValueError:
# New reference
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for enum: %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
self.write_classdesc(obj.get_class())
else:
self.write_reference(idx)
self.write_string(obj.constant)
|
python
|
def write_enum(self, obj):
self._writeStruct(">B", 1, (self.TC_ENUM,))
try:
idx = self.references.index(obj)
except ValueError:
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for enum: %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
self.write_classdesc(obj.get_class())
else:
self.write_reference(idx)
self.write_string(obj.constant)
|
[
"def",
"write_enum",
"(",
"self",
",",
"obj",
")",
":",
"# FIXME: the output doesn't have the same references as the real",
"# serializable form",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_ENUM",
",",
")",
")",
"try",
":",
"idx",
"=",
"self",
".",
"references",
".",
"index",
"(",
"obj",
")",
"except",
"ValueError",
":",
"# New reference",
"self",
".",
"references",
".",
"append",
"(",
"obj",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for enum: %s\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
",",
")",
"self",
".",
"write_classdesc",
"(",
"obj",
".",
"get_class",
"(",
")",
")",
"else",
":",
"self",
".",
"write_reference",
"(",
"idx",
")",
"self",
".",
"write_string",
"(",
"obj",
".",
"constant",
")"
] |
Writes an Enum value
:param obj: A JavaEnum object
|
[
"Writes",
"an",
"Enum",
"value"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1357-L1382
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_blockdata
|
def write_blockdata(self, obj, parent=None):
"""
Appends a block of data to the serialization stream
:param obj: String form of the data block
"""
if type(obj) is str:
# Latin-1: keep bytes as is
obj = to_bytes(obj, "latin-1")
length = len(obj)
if length <= 256:
# Small block data
# TC_BLOCKDATA (unsigned byte)<size> (byte)[size]
self._writeStruct(">B", 1, (self.TC_BLOCKDATA,))
self._writeStruct(">B", 1, (length,))
else:
# Large block data
# TC_BLOCKDATALONG (unsigned int)<size> (byte)[size]
self._writeStruct(">B", 1, (self.TC_BLOCKDATALONG,))
self._writeStruct(">I", 1, (length,))
self.object_stream.write(obj)
|
python
|
def write_blockdata(self, obj, parent=None):
if type(obj) is str:
obj = to_bytes(obj, "latin-1")
length = len(obj)
if length <= 256:
self._writeStruct(">B", 1, (self.TC_BLOCKDATA,))
self._writeStruct(">B", 1, (length,))
else:
self._writeStruct(">B", 1, (self.TC_BLOCKDATALONG,))
self._writeStruct(">I", 1, (length,))
self.object_stream.write(obj)
|
[
"def",
"write_blockdata",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"if",
"type",
"(",
"obj",
")",
"is",
"str",
":",
"# Latin-1: keep bytes as is",
"obj",
"=",
"to_bytes",
"(",
"obj",
",",
"\"latin-1\"",
")",
"length",
"=",
"len",
"(",
"obj",
")",
"if",
"length",
"<=",
"256",
":",
"# Small block data",
"# TC_BLOCKDATA (unsigned byte)<size> (byte)[size]",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_BLOCKDATA",
",",
")",
")",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"length",
",",
")",
")",
"else",
":",
"# Large block data",
"# TC_BLOCKDATALONG (unsigned int)<size> (byte)[size]",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_BLOCKDATALONG",
",",
")",
")",
"self",
".",
"_writeStruct",
"(",
"\">I\"",
",",
"1",
",",
"(",
"length",
",",
")",
")",
"self",
".",
"object_stream",
".",
"write",
"(",
"obj",
")"
] |
Appends a block of data to the serialization stream
:param obj: String form of the data block
|
[
"Appends",
"a",
"block",
"of",
"data",
"to",
"the",
"serialization",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1384-L1406
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_object
|
def write_object(self, obj, parent=None):
"""
Writes an object header to the serialization stream
:param obj: Not yet used
:param parent: Not yet used
"""
# Transform object
for transformer in self.object_transformers:
tmp_object = transformer.transform(obj)
if tmp_object is not obj:
obj = tmp_object
break
self._writeStruct(">B", 1, (self.TC_OBJECT,))
cls = obj.get_class()
self.write_classdesc(cls)
# Add reference
self.references.append([])
logging.debug(
"*** Adding ref 0x%X for object %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
all_names = collections.deque()
all_types = collections.deque()
tmpcls = cls
while tmpcls:
all_names.extendleft(reversed(tmpcls.fields_names))
all_types.extendleft(reversed(tmpcls.fields_types))
tmpcls = tmpcls.superclass
del tmpcls
logging.debug("<=> Field names: %s", all_names)
logging.debug("<=> Field types: %s", all_types)
for field_name, field_type in zip(all_names, all_types):
try:
logging.debug(
"Writing field %s (%s): %s",
field_name,
field_type,
getattr(obj, field_name),
)
self._write_value(field_type, getattr(obj, field_name))
except AttributeError as ex:
log_error(
"No attribute {0} for object {1}\nDir: {2}".format(
ex, repr(obj), dir(obj)
)
)
raise
del all_names, all_types
if (
cls.flags & self.SC_SERIALIZABLE
and cls.flags & self.SC_WRITE_METHOD
or cls.flags & self.SC_EXTERNALIZABLE
and cls.flags & self.SC_BLOCK_DATA
):
for annotation in obj.annotations:
log_debug(
"Write annotation {0} for {1}".format(repr(annotation), repr(obj))
)
if annotation is None:
self.write_null()
else:
self.writeObject(annotation)
self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
|
python
|
def write_object(self, obj, parent=None):
for transformer in self.object_transformers:
tmp_object = transformer.transform(obj)
if tmp_object is not obj:
obj = tmp_object
break
self._writeStruct(">B", 1, (self.TC_OBJECT,))
cls = obj.get_class()
self.write_classdesc(cls)
self.references.append([])
logging.debug(
"*** Adding ref 0x%X for object %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj,
)
all_names = collections.deque()
all_types = collections.deque()
tmpcls = cls
while tmpcls:
all_names.extendleft(reversed(tmpcls.fields_names))
all_types.extendleft(reversed(tmpcls.fields_types))
tmpcls = tmpcls.superclass
del tmpcls
logging.debug("<=> Field names: %s", all_names)
logging.debug("<=> Field types: %s", all_types)
for field_name, field_type in zip(all_names, all_types):
try:
logging.debug(
"Writing field %s (%s): %s",
field_name,
field_type,
getattr(obj, field_name),
)
self._write_value(field_type, getattr(obj, field_name))
except AttributeError as ex:
log_error(
"No attribute {0} for object {1}\nDir: {2}".format(
ex, repr(obj), dir(obj)
)
)
raise
del all_names, all_types
if (
cls.flags & self.SC_SERIALIZABLE
and cls.flags & self.SC_WRITE_METHOD
or cls.flags & self.SC_EXTERNALIZABLE
and cls.flags & self.SC_BLOCK_DATA
):
for annotation in obj.annotations:
log_debug(
"Write annotation {0} for {1}".format(repr(annotation), repr(obj))
)
if annotation is None:
self.write_null()
else:
self.writeObject(annotation)
self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
|
[
"def",
"write_object",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"# Transform object",
"for",
"transformer",
"in",
"self",
".",
"object_transformers",
":",
"tmp_object",
"=",
"transformer",
".",
"transform",
"(",
"obj",
")",
"if",
"tmp_object",
"is",
"not",
"obj",
":",
"obj",
"=",
"tmp_object",
"break",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_OBJECT",
",",
")",
")",
"cls",
"=",
"obj",
".",
"get_class",
"(",
")",
"self",
".",
"write_classdesc",
"(",
"cls",
")",
"# Add reference",
"self",
".",
"references",
".",
"append",
"(",
"[",
"]",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for object %s\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
",",
")",
"all_names",
"=",
"collections",
".",
"deque",
"(",
")",
"all_types",
"=",
"collections",
".",
"deque",
"(",
")",
"tmpcls",
"=",
"cls",
"while",
"tmpcls",
":",
"all_names",
".",
"extendleft",
"(",
"reversed",
"(",
"tmpcls",
".",
"fields_names",
")",
")",
"all_types",
".",
"extendleft",
"(",
"reversed",
"(",
"tmpcls",
".",
"fields_types",
")",
")",
"tmpcls",
"=",
"tmpcls",
".",
"superclass",
"del",
"tmpcls",
"logging",
".",
"debug",
"(",
"\"<=> Field names: %s\"",
",",
"all_names",
")",
"logging",
".",
"debug",
"(",
"\"<=> Field types: %s\"",
",",
"all_types",
")",
"for",
"field_name",
",",
"field_type",
"in",
"zip",
"(",
"all_names",
",",
"all_types",
")",
":",
"try",
":",
"logging",
".",
"debug",
"(",
"\"Writing field %s (%s): %s\"",
",",
"field_name",
",",
"field_type",
",",
"getattr",
"(",
"obj",
",",
"field_name",
")",
",",
")",
"self",
".",
"_write_value",
"(",
"field_type",
",",
"getattr",
"(",
"obj",
",",
"field_name",
")",
")",
"except",
"AttributeError",
"as",
"ex",
":",
"log_error",
"(",
"\"No attribute {0} for object {1}\\nDir: {2}\"",
".",
"format",
"(",
"ex",
",",
"repr",
"(",
"obj",
")",
",",
"dir",
"(",
"obj",
")",
")",
")",
"raise",
"del",
"all_names",
",",
"all_types",
"if",
"(",
"cls",
".",
"flags",
"&",
"self",
".",
"SC_SERIALIZABLE",
"and",
"cls",
".",
"flags",
"&",
"self",
".",
"SC_WRITE_METHOD",
"or",
"cls",
".",
"flags",
"&",
"self",
".",
"SC_EXTERNALIZABLE",
"and",
"cls",
".",
"flags",
"&",
"self",
".",
"SC_BLOCK_DATA",
")",
":",
"for",
"annotation",
"in",
"obj",
".",
"annotations",
":",
"log_debug",
"(",
"\"Write annotation {0} for {1}\"",
".",
"format",
"(",
"repr",
"(",
"annotation",
")",
",",
"repr",
"(",
"obj",
")",
")",
")",
"if",
"annotation",
"is",
"None",
":",
"self",
".",
"write_null",
"(",
")",
"else",
":",
"self",
".",
"writeObject",
"(",
"annotation",
")",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_ENDBLOCKDATA",
",",
")",
")"
] |
Writes an object header to the serialization stream
:param obj: Not yet used
:param parent: Not yet used
|
[
"Writes",
"an",
"object",
"header",
"to",
"the",
"serialization",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1414-L1484
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_class
|
def write_class(self, obj, parent=None):
"""
Writes a class to the stream
:param obj: A JavaClass object
:param parent:
"""
self._writeStruct(">B", 1, (self.TC_CLASS,))
self.write_classdesc(obj)
|
python
|
def write_class(self, obj, parent=None):
self._writeStruct(">B", 1, (self.TC_CLASS,))
self.write_classdesc(obj)
|
[
"def",
"write_class",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_CLASS",
",",
")",
")",
"self",
".",
"write_classdesc",
"(",
"obj",
")"
] |
Writes a class to the stream
:param obj: A JavaClass object
:param parent:
|
[
"Writes",
"a",
"class",
"to",
"the",
"stream"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1486-L1494
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_classdesc
|
def write_classdesc(self, obj, parent=None):
"""
Writes a class description
:param obj: Class description to write
:param parent:
"""
if obj not in self.references:
# Add reference
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for classdesc %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj.name,
)
self._writeStruct(">B", 1, (self.TC_CLASSDESC,))
self._writeString(obj.name)
self._writeStruct(">qB", 1, (obj.serialVersionUID, obj.flags))
self._writeStruct(">H", 1, (len(obj.fields_names),))
for field_name, field_type in zip(obj.fields_names, obj.fields_types):
self._writeStruct(">B", 1, (self._convert_type_to_char(field_type),))
self._writeString(field_name)
if field_type[0] in (self.TYPE_OBJECT, self.TYPE_ARRAY):
try:
idx = self.references.index(field_type)
except ValueError:
# First appearance of the type
self.references.append(field_type)
logging.debug(
"*** Adding ref 0x%X for field type %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
field_type,
)
self.write_string(field_type, False)
else:
# Write a reference to the previous type
logging.debug(
"*** Reusing ref 0x%X for %s (%s)",
idx + self.BASE_REFERENCE_IDX,
field_type,
field_name,
)
self.write_reference(idx)
self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
if obj.superclass:
self.write_classdesc(obj.superclass)
else:
self.write_null()
else:
# Use reference
self.write_reference(self.references.index(obj))
|
python
|
def write_classdesc(self, obj, parent=None):
if obj not in self.references:
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for classdesc %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
obj.name,
)
self._writeStruct(">B", 1, (self.TC_CLASSDESC,))
self._writeString(obj.name)
self._writeStruct(">qB", 1, (obj.serialVersionUID, obj.flags))
self._writeStruct(">H", 1, (len(obj.fields_names),))
for field_name, field_type in zip(obj.fields_names, obj.fields_types):
self._writeStruct(">B", 1, (self._convert_type_to_char(field_type),))
self._writeString(field_name)
if field_type[0] in (self.TYPE_OBJECT, self.TYPE_ARRAY):
try:
idx = self.references.index(field_type)
except ValueError:
self.references.append(field_type)
logging.debug(
"*** Adding ref 0x%X for field type %s",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
field_type,
)
self.write_string(field_type, False)
else:
logging.debug(
"*** Reusing ref 0x%X for %s (%s)",
idx + self.BASE_REFERENCE_IDX,
field_type,
field_name,
)
self.write_reference(idx)
self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))
if obj.superclass:
self.write_classdesc(obj.superclass)
else:
self.write_null()
else:
self.write_reference(self.references.index(obj))
|
[
"def",
"write_classdesc",
"(",
"self",
",",
"obj",
",",
"parent",
"=",
"None",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"references",
":",
"# Add reference",
"self",
".",
"references",
".",
"append",
"(",
"obj",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for classdesc %s\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"obj",
".",
"name",
",",
")",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_CLASSDESC",
",",
")",
")",
"self",
".",
"_writeString",
"(",
"obj",
".",
"name",
")",
"self",
".",
"_writeStruct",
"(",
"\">qB\"",
",",
"1",
",",
"(",
"obj",
".",
"serialVersionUID",
",",
"obj",
".",
"flags",
")",
")",
"self",
".",
"_writeStruct",
"(",
"\">H\"",
",",
"1",
",",
"(",
"len",
"(",
"obj",
".",
"fields_names",
")",
",",
")",
")",
"for",
"field_name",
",",
"field_type",
"in",
"zip",
"(",
"obj",
".",
"fields_names",
",",
"obj",
".",
"fields_types",
")",
":",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"_convert_type_to_char",
"(",
"field_type",
")",
",",
")",
")",
"self",
".",
"_writeString",
"(",
"field_name",
")",
"if",
"field_type",
"[",
"0",
"]",
"in",
"(",
"self",
".",
"TYPE_OBJECT",
",",
"self",
".",
"TYPE_ARRAY",
")",
":",
"try",
":",
"idx",
"=",
"self",
".",
"references",
".",
"index",
"(",
"field_type",
")",
"except",
"ValueError",
":",
"# First appearance of the type",
"self",
".",
"references",
".",
"append",
"(",
"field_type",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for field type %s\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"field_type",
",",
")",
"self",
".",
"write_string",
"(",
"field_type",
",",
"False",
")",
"else",
":",
"# Write a reference to the previous type",
"logging",
".",
"debug",
"(",
"\"*** Reusing ref 0x%X for %s (%s)\"",
",",
"idx",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
"field_type",
",",
"field_name",
",",
")",
"self",
".",
"write_reference",
"(",
"idx",
")",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_ENDBLOCKDATA",
",",
")",
")",
"if",
"obj",
".",
"superclass",
":",
"self",
".",
"write_classdesc",
"(",
"obj",
".",
"superclass",
")",
"else",
":",
"self",
".",
"write_null",
"(",
")",
"else",
":",
"# Use reference",
"self",
".",
"write_reference",
"(",
"self",
".",
"references",
".",
"index",
"(",
"obj",
")",
")"
] |
Writes a class description
:param obj: Class description to write
:param parent:
|
[
"Writes",
"a",
"class",
"description"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1496-L1550
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_reference
|
def write_reference(self, ref_index):
"""
Writes a reference
:param ref_index: Local index (0-based) to the reference
"""
self._writeStruct(
">BL", 1, (self.TC_REFERENCE, ref_index + self.BASE_REFERENCE_IDX)
)
|
python
|
def write_reference(self, ref_index):
self._writeStruct(
">BL", 1, (self.TC_REFERENCE, ref_index + self.BASE_REFERENCE_IDX)
)
|
[
"def",
"write_reference",
"(",
"self",
",",
"ref_index",
")",
":",
"self",
".",
"_writeStruct",
"(",
"\">BL\"",
",",
"1",
",",
"(",
"self",
".",
"TC_REFERENCE",
",",
"ref_index",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
")",
")"
] |
Writes a reference
:param ref_index: Local index (0-based) to the reference
|
[
"Writes",
"a",
"reference",
":",
"param",
"ref_index",
":",
"Local",
"index",
"(",
"0",
"-",
"based",
")",
"to",
"the",
"reference"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1552-L1559
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller.write_array
|
def write_array(self, obj):
"""
Writes a JavaArray
:param obj: A JavaArray object
"""
classdesc = obj.get_class()
self._writeStruct(">B", 1, (self.TC_ARRAY,))
self.write_classdesc(classdesc)
self._writeStruct(">i", 1, (len(obj),))
# Add reference
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for array []",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
)
type_char = classdesc.name[0]
assert type_char == self.TYPE_ARRAY
type_char = classdesc.name[1]
if type_char == self.TYPE_OBJECT:
for o in obj:
self._write_value(classdesc.name[1:], o)
elif type_char == self.TYPE_ARRAY:
for a in obj:
self.write_array(a)
else:
log_debug("Write array of type %s" % type_char)
for v in obj:
log_debug("Writing: %s" % v)
self._write_value(type_char, v)
|
python
|
def write_array(self, obj):
classdesc = obj.get_class()
self._writeStruct(">B", 1, (self.TC_ARRAY,))
self.write_classdesc(classdesc)
self._writeStruct(">i", 1, (len(obj),))
self.references.append(obj)
logging.debug(
"*** Adding ref 0x%X for array []",
len(self.references) - 1 + self.BASE_REFERENCE_IDX,
)
type_char = classdesc.name[0]
assert type_char == self.TYPE_ARRAY
type_char = classdesc.name[1]
if type_char == self.TYPE_OBJECT:
for o in obj:
self._write_value(classdesc.name[1:], o)
elif type_char == self.TYPE_ARRAY:
for a in obj:
self.write_array(a)
else:
log_debug("Write array of type %s" % type_char)
for v in obj:
log_debug("Writing: %s" % v)
self._write_value(type_char, v)
|
[
"def",
"write_array",
"(",
"self",
",",
"obj",
")",
":",
"classdesc",
"=",
"obj",
".",
"get_class",
"(",
")",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"self",
".",
"TC_ARRAY",
",",
")",
")",
"self",
".",
"write_classdesc",
"(",
"classdesc",
")",
"self",
".",
"_writeStruct",
"(",
"\">i\"",
",",
"1",
",",
"(",
"len",
"(",
"obj",
")",
",",
")",
")",
"# Add reference",
"self",
".",
"references",
".",
"append",
"(",
"obj",
")",
"logging",
".",
"debug",
"(",
"\"*** Adding ref 0x%X for array []\"",
",",
"len",
"(",
"self",
".",
"references",
")",
"-",
"1",
"+",
"self",
".",
"BASE_REFERENCE_IDX",
",",
")",
"type_char",
"=",
"classdesc",
".",
"name",
"[",
"0",
"]",
"assert",
"type_char",
"==",
"self",
".",
"TYPE_ARRAY",
"type_char",
"=",
"classdesc",
".",
"name",
"[",
"1",
"]",
"if",
"type_char",
"==",
"self",
".",
"TYPE_OBJECT",
":",
"for",
"o",
"in",
"obj",
":",
"self",
".",
"_write_value",
"(",
"classdesc",
".",
"name",
"[",
"1",
":",
"]",
",",
"o",
")",
"elif",
"type_char",
"==",
"self",
".",
"TYPE_ARRAY",
":",
"for",
"a",
"in",
"obj",
":",
"self",
".",
"write_array",
"(",
"a",
")",
"else",
":",
"log_debug",
"(",
"\"Write array of type %s\"",
"%",
"type_char",
")",
"for",
"v",
"in",
"obj",
":",
"log_debug",
"(",
"\"Writing: %s\"",
"%",
"v",
")",
"self",
".",
"_write_value",
"(",
"type_char",
",",
"v",
")"
] |
Writes a JavaArray
:param obj: A JavaArray object
|
[
"Writes",
"a",
"JavaArray"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1561-L1593
|
tcalmant/python-javaobj
|
javaobj/core.py
|
JavaObjectMarshaller._write_value
|
def _write_value(self, field_type, value):
"""
Writes an item of an array
:param field_type: Value type
:param value: The value itself
"""
if len(field_type) > 1:
# We don't need details for arrays and objects
field_type = field_type[0]
if field_type == self.TYPE_BOOLEAN:
self._writeStruct(">B", 1, (1 if value else 0,))
elif field_type == self.TYPE_BYTE:
self._writeStruct(">b", 1, (value,))
elif field_type == self.TYPE_CHAR:
self._writeStruct(">H", 1, (ord(value),))
elif field_type == self.TYPE_SHORT:
self._writeStruct(">h", 1, (value,))
elif field_type == self.TYPE_INTEGER:
self._writeStruct(">i", 1, (value,))
elif field_type == self.TYPE_LONG:
self._writeStruct(">q", 1, (value,))
elif field_type == self.TYPE_FLOAT:
self._writeStruct(">f", 1, (value,))
elif field_type == self.TYPE_DOUBLE:
self._writeStruct(">d", 1, (value,))
elif field_type == self.TYPE_OBJECT or field_type == self.TYPE_ARRAY:
if value is None:
self.write_null()
elif isinstance(value, JavaEnum):
self.write_enum(value)
elif isinstance(value, (JavaArray, JavaByteArray)):
self.write_array(value)
elif isinstance(value, JavaObject):
self.write_object(value)
elif isinstance(value, JavaString):
self.write_string(value)
elif isinstance(value, str):
self.write_blockdata(value)
else:
raise RuntimeError("Unknown typecode: {0}".format(field_type))
else:
raise RuntimeError("Unknown typecode: {0}".format(field_type))
|
python
|
def _write_value(self, field_type, value):
if len(field_type) > 1:
field_type = field_type[0]
if field_type == self.TYPE_BOOLEAN:
self._writeStruct(">B", 1, (1 if value else 0,))
elif field_type == self.TYPE_BYTE:
self._writeStruct(">b", 1, (value,))
elif field_type == self.TYPE_CHAR:
self._writeStruct(">H", 1, (ord(value),))
elif field_type == self.TYPE_SHORT:
self._writeStruct(">h", 1, (value,))
elif field_type == self.TYPE_INTEGER:
self._writeStruct(">i", 1, (value,))
elif field_type == self.TYPE_LONG:
self._writeStruct(">q", 1, (value,))
elif field_type == self.TYPE_FLOAT:
self._writeStruct(">f", 1, (value,))
elif field_type == self.TYPE_DOUBLE:
self._writeStruct(">d", 1, (value,))
elif field_type == self.TYPE_OBJECT or field_type == self.TYPE_ARRAY:
if value is None:
self.write_null()
elif isinstance(value, JavaEnum):
self.write_enum(value)
elif isinstance(value, (JavaArray, JavaByteArray)):
self.write_array(value)
elif isinstance(value, JavaObject):
self.write_object(value)
elif isinstance(value, JavaString):
self.write_string(value)
elif isinstance(value, str):
self.write_blockdata(value)
else:
raise RuntimeError("Unknown typecode: {0}".format(field_type))
else:
raise RuntimeError("Unknown typecode: {0}".format(field_type))
|
[
"def",
"_write_value",
"(",
"self",
",",
"field_type",
",",
"value",
")",
":",
"if",
"len",
"(",
"field_type",
")",
">",
"1",
":",
"# We don't need details for arrays and objects",
"field_type",
"=",
"field_type",
"[",
"0",
"]",
"if",
"field_type",
"==",
"self",
".",
"TYPE_BOOLEAN",
":",
"self",
".",
"_writeStruct",
"(",
"\">B\"",
",",
"1",
",",
"(",
"1",
"if",
"value",
"else",
"0",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_BYTE",
":",
"self",
".",
"_writeStruct",
"(",
"\">b\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_CHAR",
":",
"self",
".",
"_writeStruct",
"(",
"\">H\"",
",",
"1",
",",
"(",
"ord",
"(",
"value",
")",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_SHORT",
":",
"self",
".",
"_writeStruct",
"(",
"\">h\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_INTEGER",
":",
"self",
".",
"_writeStruct",
"(",
"\">i\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_LONG",
":",
"self",
".",
"_writeStruct",
"(",
"\">q\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_FLOAT",
":",
"self",
".",
"_writeStruct",
"(",
"\">f\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_DOUBLE",
":",
"self",
".",
"_writeStruct",
"(",
"\">d\"",
",",
"1",
",",
"(",
"value",
",",
")",
")",
"elif",
"field_type",
"==",
"self",
".",
"TYPE_OBJECT",
"or",
"field_type",
"==",
"self",
".",
"TYPE_ARRAY",
":",
"if",
"value",
"is",
"None",
":",
"self",
".",
"write_null",
"(",
")",
"elif",
"isinstance",
"(",
"value",
",",
"JavaEnum",
")",
":",
"self",
".",
"write_enum",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"(",
"JavaArray",
",",
"JavaByteArray",
")",
")",
":",
"self",
".",
"write_array",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"JavaObject",
")",
":",
"self",
".",
"write_object",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"JavaString",
")",
":",
"self",
".",
"write_string",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"self",
".",
"write_blockdata",
"(",
"value",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown typecode: {0}\"",
".",
"format",
"(",
"field_type",
")",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Unknown typecode: {0}\"",
".",
"format",
"(",
"field_type",
")",
")"
] |
Writes an item of an array
:param field_type: Value type
:param value: The value itself
|
[
"Writes",
"an",
"item",
"of",
"an",
"array"
] |
train
|
https://github.com/tcalmant/python-javaobj/blob/e042c2cbf1ce9de659b6cb9290b5ccd5442514d1/javaobj/core.py#L1595-L1638
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.