Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
run
( async_fn, *args, clock=None, instruments=(), restrict_keyboard_interrupt_to_checkpoints=False, )
Run a Trio-flavored async function, and return the result. Calling:: run(async_fn, *args) is the equivalent of:: await async_fn(*args) except that :func:`run` can (and must) be called from a synchronous context. This is Trio's main entry point. Almost every other function in Trio requires that you be inside a call to :func:`run`. Args: async_fn: An async function. args: Positional arguments to be passed to *async_fn*. If you need to pass keyword arguments, then use :func:`functools.partial`. clock: ``None`` to use the default system-specific monotonic clock; otherwise, an object implementing the :class:`trio.abc.Clock` interface, like (for example) a :class:`trio.testing.MockClock` instance. instruments (list of :class:`trio.abc.Instrument` objects): Any instrumentation you want to apply to this run. This can also be modified during the run; see :ref:`instrumentation`. restrict_keyboard_interrupt_to_checkpoints (bool): What happens if the user hits control-C while :func:`run` is running? If this argument is False (the default), then you get the standard Python behavior: a :exc:`KeyboardInterrupt` exception will immediately interrupt whatever task is running (or if no task is running, then Trio will wake up a task to be interrupted). Alternatively, if you set this argument to True, then :exc:`KeyboardInterrupt` delivery will be delayed: it will be *only* be raised at :ref:`checkpoints <checkpoints>`, like a :exc:`Cancelled` exception. The default behavior is nice because it means that even if you accidentally write an infinite loop that never executes any checkpoints, then you can still break out of it using control-C. The alternative behavior is nice if you're paranoid about a :exc:`KeyboardInterrupt` at just the wrong place leaving your program in an inconsistent state, because it means that you only have to worry about :exc:`KeyboardInterrupt` at the exact same places where you already have to worry about :exc:`Cancelled`. This setting has no effect if your program has registered a custom SIGINT handler, or if :func:`run` is called from anywhere but the main thread (this is a Python limitation), or if you use :func:`open_signal_receiver` to catch SIGINT. Returns: Whatever ``async_fn`` returns. Raises: TrioInternalError: if an unexpected error is encountered inside Trio's internal machinery. This is a bug and you should `let us know <https://github.com/python-trio/trio/issues>`__. Anything else: if ``async_fn`` raises an exception, then :func:`run` propagates it.
Run a Trio-flavored async function, and return the result.
def run( async_fn, *args, clock=None, instruments=(), restrict_keyboard_interrupt_to_checkpoints=False, ): """Run a Trio-flavored async function, and return the result. Calling:: run(async_fn, *args) is the equivalent of:: await async_fn(*args) except that :func:`run` can (and must) be called from a synchronous context. This is Trio's main entry point. Almost every other function in Trio requires that you be inside a call to :func:`run`. Args: async_fn: An async function. args: Positional arguments to be passed to *async_fn*. If you need to pass keyword arguments, then use :func:`functools.partial`. clock: ``None`` to use the default system-specific monotonic clock; otherwise, an object implementing the :class:`trio.abc.Clock` interface, like (for example) a :class:`trio.testing.MockClock` instance. instruments (list of :class:`trio.abc.Instrument` objects): Any instrumentation you want to apply to this run. This can also be modified during the run; see :ref:`instrumentation`. restrict_keyboard_interrupt_to_checkpoints (bool): What happens if the user hits control-C while :func:`run` is running? If this argument is False (the default), then you get the standard Python behavior: a :exc:`KeyboardInterrupt` exception will immediately interrupt whatever task is running (or if no task is running, then Trio will wake up a task to be interrupted). Alternatively, if you set this argument to True, then :exc:`KeyboardInterrupt` delivery will be delayed: it will be *only* be raised at :ref:`checkpoints <checkpoints>`, like a :exc:`Cancelled` exception. The default behavior is nice because it means that even if you accidentally write an infinite loop that never executes any checkpoints, then you can still break out of it using control-C. The alternative behavior is nice if you're paranoid about a :exc:`KeyboardInterrupt` at just the wrong place leaving your program in an inconsistent state, because it means that you only have to worry about :exc:`KeyboardInterrupt` at the exact same places where you already have to worry about :exc:`Cancelled`. This setting has no effect if your program has registered a custom SIGINT handler, or if :func:`run` is called from anywhere but the main thread (this is a Python limitation), or if you use :func:`open_signal_receiver` to catch SIGINT. Returns: Whatever ``async_fn`` returns. Raises: TrioInternalError: if an unexpected error is encountered inside Trio's internal machinery. This is a bug and you should `let us know <https://github.com/python-trio/trio/issues>`__. Anything else: if ``async_fn`` raises an exception, then :func:`run` propagates it. """ __tracebackhide__ = True runner = setup_runner( clock, instruments, restrict_keyboard_interrupt_to_checkpoints ) gen = unrolled_run(runner, async_fn, args) next_send = None while True: try: timeout = gen.send(next_send) except StopIteration: break next_send = runner.io_manager.get_events(timeout) # Inlined copy of runner.main_task_outcome.unwrap() to avoid # cluttering every single Trio traceback with an extra frame. if isinstance(runner.main_task_outcome, Value): return runner.main_task_outcome.value else: raise runner.main_task_outcome.error
[ "def", "run", "(", "async_fn", ",", "*", "args", ",", "clock", "=", "None", ",", "instruments", "=", "(", ")", ",", "restrict_keyboard_interrupt_to_checkpoints", "=", "False", ",", ")", ":", "__tracebackhide__", "=", "True", "runner", "=", "setup_runner", "(", "clock", ",", "instruments", ",", "restrict_keyboard_interrupt_to_checkpoints", ")", "gen", "=", "unrolled_run", "(", "runner", ",", "async_fn", ",", "args", ")", "next_send", "=", "None", "while", "True", ":", "try", ":", "timeout", "=", "gen", ".", "send", "(", "next_send", ")", "except", "StopIteration", ":", "break", "next_send", "=", "runner", ".", "io_manager", ".", "get_events", "(", "timeout", ")", "# Inlined copy of runner.main_task_outcome.unwrap() to avoid", "# cluttering every single Trio traceback with an extra frame.", "if", "isinstance", "(", "runner", ".", "main_task_outcome", ",", "Value", ")", ":", "return", "runner", ".", "main_task_outcome", ".", "value", "else", ":", "raise", "runner", ".", "main_task_outcome", ".", "error" ]
[ 1842, 0 ]
[ 1936, 44 ]
python
en
['en', 'en', 'en']
True
start_guest_run
( async_fn, *args, run_sync_soon_threadsafe, done_callback, run_sync_soon_not_threadsafe=None, host_uses_signal_set_wakeup_fd=False, clock=None, instruments=(), restrict_keyboard_interrupt_to_checkpoints=False, )
Start a "guest" run of Trio on top of some other "host" event loop. Each host loop can only have one guest run at a time. You should always let the Trio run finish before stopping the host loop; if not, it may leave Trio's internal data structures in an inconsistent state. You might be able to get away with it if you immediately exit the program, but it's safest not to go there in the first place. Generally, the best way to do this is wrap this in a function that starts the host loop and then immediately starts the guest run, and then shuts down the host when the guest run completes. Args: run_sync_soon_threadsafe: An arbitrary callable, which will be passed a function as its sole argument:: def my_run_sync_soon_threadsafe(fn): ... This callable should schedule ``fn()`` to be run by the host on its next pass through its loop. **Must support being called from arbitrary threads.** done_callback: An arbitrary callable:: def my_done_callback(run_outcome): ... When the Trio run has finished, Trio will invoke this callback to let you know. The argument is an `outcome.Outcome`, reporting what would have been returned or raised by `trio.run`. This function can do anything you want, but commonly you'll want it to shut down the host loop, unwrap the outcome, etc. run_sync_soon_not_threadsafe: Like ``run_sync_soon_threadsafe``, but will only be called from inside the host loop's main thread. Optional, but if your host loop allows you to implement this more efficiently than ``run_sync_soon_threadsafe`` then passing it will make things a bit faster. host_uses_signal_set_wakeup_fd (bool): Pass `True` if your host loop uses `signal.set_wakeup_fd`, and `False` otherwise. For more details, see :ref:`guest-run-implementation`. For the meaning of other arguments, see `trio.run`.
Start a "guest" run of Trio on top of some other "host" event loop.
def start_guest_run( async_fn, *args, run_sync_soon_threadsafe, done_callback, run_sync_soon_not_threadsafe=None, host_uses_signal_set_wakeup_fd=False, clock=None, instruments=(), restrict_keyboard_interrupt_to_checkpoints=False, ): """Start a "guest" run of Trio on top of some other "host" event loop. Each host loop can only have one guest run at a time. You should always let the Trio run finish before stopping the host loop; if not, it may leave Trio's internal data structures in an inconsistent state. You might be able to get away with it if you immediately exit the program, but it's safest not to go there in the first place. Generally, the best way to do this is wrap this in a function that starts the host loop and then immediately starts the guest run, and then shuts down the host when the guest run completes. Args: run_sync_soon_threadsafe: An arbitrary callable, which will be passed a function as its sole argument:: def my_run_sync_soon_threadsafe(fn): ... This callable should schedule ``fn()`` to be run by the host on its next pass through its loop. **Must support being called from arbitrary threads.** done_callback: An arbitrary callable:: def my_done_callback(run_outcome): ... When the Trio run has finished, Trio will invoke this callback to let you know. The argument is an `outcome.Outcome`, reporting what would have been returned or raised by `trio.run`. This function can do anything you want, but commonly you'll want it to shut down the host loop, unwrap the outcome, etc. run_sync_soon_not_threadsafe: Like ``run_sync_soon_threadsafe``, but will only be called from inside the host loop's main thread. Optional, but if your host loop allows you to implement this more efficiently than ``run_sync_soon_threadsafe`` then passing it will make things a bit faster. host_uses_signal_set_wakeup_fd (bool): Pass `True` if your host loop uses `signal.set_wakeup_fd`, and `False` otherwise. For more details, see :ref:`guest-run-implementation`. For the meaning of other arguments, see `trio.run`. """ runner = setup_runner( clock, instruments, restrict_keyboard_interrupt_to_checkpoints ) runner.is_guest = True runner.guest_tick_scheduled = True if run_sync_soon_not_threadsafe is None: run_sync_soon_not_threadsafe = run_sync_soon_threadsafe guest_state = GuestState( runner=runner, run_sync_soon_threadsafe=run_sync_soon_threadsafe, run_sync_soon_not_threadsafe=run_sync_soon_not_threadsafe, done_callback=done_callback, unrolled_run_gen=unrolled_run( runner, async_fn, args, host_uses_signal_set_wakeup_fd=host_uses_signal_set_wakeup_fd, ), ) run_sync_soon_not_threadsafe(guest_state.guest_tick)
[ "def", "start_guest_run", "(", "async_fn", ",", "*", "args", ",", "run_sync_soon_threadsafe", ",", "done_callback", ",", "run_sync_soon_not_threadsafe", "=", "None", ",", "host_uses_signal_set_wakeup_fd", "=", "False", ",", "clock", "=", "None", ",", "instruments", "=", "(", ")", ",", "restrict_keyboard_interrupt_to_checkpoints", "=", "False", ",", ")", ":", "runner", "=", "setup_runner", "(", "clock", ",", "instruments", ",", "restrict_keyboard_interrupt_to_checkpoints", ")", "runner", ".", "is_guest", "=", "True", "runner", ".", "guest_tick_scheduled", "=", "True", "if", "run_sync_soon_not_threadsafe", "is", "None", ":", "run_sync_soon_not_threadsafe", "=", "run_sync_soon_threadsafe", "guest_state", "=", "GuestState", "(", "runner", "=", "runner", ",", "run_sync_soon_threadsafe", "=", "run_sync_soon_threadsafe", ",", "run_sync_soon_not_threadsafe", "=", "run_sync_soon_not_threadsafe", ",", "done_callback", "=", "done_callback", ",", "unrolled_run_gen", "=", "unrolled_run", "(", "runner", ",", "async_fn", ",", "args", ",", "host_uses_signal_set_wakeup_fd", "=", "host_uses_signal_set_wakeup_fd", ",", ")", ",", ")", "run_sync_soon_not_threadsafe", "(", "guest_state", ".", "guest_tick", ")" ]
[ 1939, 0 ]
[ 2020, 56 ]
python
en
['en', 'en', 'en']
True
current_task
()
Return the :class:`Task` object representing the current task. Returns: Task: the :class:`Task` that called :func:`current_task`.
Return the :class:`Task` object representing the current task.
def current_task(): """Return the :class:`Task` object representing the current task. Returns: Task: the :class:`Task` that called :func:`current_task`. """ try: return GLOBAL_RUN_CONTEXT.task except AttributeError: raise RuntimeError("must be called from async context") from None
[ "def", "current_task", "(", ")", ":", "try", ":", "return", "GLOBAL_RUN_CONTEXT", ".", "task", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "\"must be called from async context\"", ")", "from", "None" ]
[ 2264, 0 ]
[ 2275, 73 ]
python
en
['en', 'en', 'en']
True
current_effective_deadline
()
Returns the current effective deadline for the current task. This function examines all the cancellation scopes that are currently in effect (taking into account shielding), and returns the deadline that will expire first. One example of where this might be is useful is if your code is trying to decide whether to begin an expensive operation like an RPC call, but wants to skip it if it knows that it can't possibly complete in the available time. Another example would be if you're using a protocol like gRPC that `propagates timeout information to the remote peer <http://www.grpc.io/docs/guides/concepts.html#deadlines>`__; this function gives a way to fetch that information so you can send it along. If this is called in a context where a cancellation is currently active (i.e., a blocking call will immediately raise :exc:`Cancelled`), then returned deadline is ``-inf``. If it is called in a context where no scopes have a deadline set, it returns ``inf``. Returns: float: the effective deadline, as an absolute time.
Returns the current effective deadline for the current task.
def current_effective_deadline(): """Returns the current effective deadline for the current task. This function examines all the cancellation scopes that are currently in effect (taking into account shielding), and returns the deadline that will expire first. One example of where this might be is useful is if your code is trying to decide whether to begin an expensive operation like an RPC call, but wants to skip it if it knows that it can't possibly complete in the available time. Another example would be if you're using a protocol like gRPC that `propagates timeout information to the remote peer <http://www.grpc.io/docs/guides/concepts.html#deadlines>`__; this function gives a way to fetch that information so you can send it along. If this is called in a context where a cancellation is currently active (i.e., a blocking call will immediately raise :exc:`Cancelled`), then returned deadline is ``-inf``. If it is called in a context where no scopes have a deadline set, it returns ``inf``. Returns: float: the effective deadline, as an absolute time. """ return current_task()._cancel_status.effective_deadline()
[ "def", "current_effective_deadline", "(", ")", ":", "return", "current_task", "(", ")", ".", "_cancel_status", ".", "effective_deadline", "(", ")" ]
[ 2278, 0 ]
[ 2302, 61 ]
python
en
['en', 'en', 'en']
True
checkpoint
()
A pure :ref:`checkpoint <checkpoints>`. This checks for cancellation and allows other tasks to be scheduled, without otherwise blocking. Note that the scheduler has the option of ignoring this and continuing to run the current task if it decides this is appropriate (e.g. for increased efficiency). Equivalent to ``await trio.sleep(0)`` (which is implemented by calling :func:`checkpoint`.)
A pure :ref:`checkpoint <checkpoints>`.
async def checkpoint(): """A pure :ref:`checkpoint <checkpoints>`. This checks for cancellation and allows other tasks to be scheduled, without otherwise blocking. Note that the scheduler has the option of ignoring this and continuing to run the current task if it decides this is appropriate (e.g. for increased efficiency). Equivalent to ``await trio.sleep(0)`` (which is implemented by calling :func:`checkpoint`.) """ # The scheduler is what checks timeouts and converts them into # cancellations. So by doing the schedule point first, we ensure that the # cancel point has the most up-to-date info. await cancel_shielded_checkpoint() task = current_task() task._cancel_points += 1 if task._cancel_status.effectively_cancelled or ( task is task._runner.main_task and task._runner.ki_pending ): with CancelScope(deadline=-inf): await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED)
[ "async", "def", "checkpoint", "(", ")", ":", "# The scheduler is what checks timeouts and converts them into", "# cancellations. So by doing the schedule point first, we ensure that the", "# cancel point has the most up-to-date info.", "await", "cancel_shielded_checkpoint", "(", ")", "task", "=", "current_task", "(", ")", "task", ".", "_cancel_points", "+=", "1", "if", "task", ".", "_cancel_status", ".", "effectively_cancelled", "or", "(", "task", "is", "task", ".", "_runner", ".", "main_task", "and", "task", ".", "_runner", ".", "ki_pending", ")", ":", "with", "CancelScope", "(", "deadline", "=", "-", "inf", ")", ":", "await", "_core", ".", "wait_task_rescheduled", "(", "lambda", "_", ":", "_core", ".", "Abort", ".", "SUCCEEDED", ")" ]
[ 2305, 0 ]
[ 2329, 78 ]
python
en
['en', 'en', 'en']
True
checkpoint_if_cancelled
()
Issue a :ref:`checkpoint <checkpoints>` if the calling context has been cancelled. Equivalent to (but potentially more efficient than):: if trio.current_deadline() == -inf: await trio.lowlevel.checkpoint() This is either a no-op, or else it allow other tasks to be scheduled and then raises :exc:`trio.Cancelled`. Typically used together with :func:`cancel_shielded_checkpoint`.
Issue a :ref:`checkpoint <checkpoints>` if the calling context has been cancelled.
async def checkpoint_if_cancelled(): """Issue a :ref:`checkpoint <checkpoints>` if the calling context has been cancelled. Equivalent to (but potentially more efficient than):: if trio.current_deadline() == -inf: await trio.lowlevel.checkpoint() This is either a no-op, or else it allow other tasks to be scheduled and then raises :exc:`trio.Cancelled`. Typically used together with :func:`cancel_shielded_checkpoint`. """ task = current_task() if task._cancel_status.effectively_cancelled or ( task is task._runner.main_task and task._runner.ki_pending ): await _core.checkpoint() assert False # pragma: no cover task._cancel_points += 1
[ "async", "def", "checkpoint_if_cancelled", "(", ")", ":", "task", "=", "current_task", "(", ")", "if", "task", ".", "_cancel_status", ".", "effectively_cancelled", "or", "(", "task", "is", "task", ".", "_runner", ".", "main_task", "and", "task", ".", "_runner", ".", "ki_pending", ")", ":", "await", "_core", ".", "checkpoint", "(", ")", "assert", "False", "# pragma: no cover", "task", ".", "_cancel_points", "+=", "1" ]
[ 2332, 0 ]
[ 2353, 28 ]
python
en
['en', 'en', 'en']
True
Nursery.child_tasks
(self)
(`frozenset`): Contains all the child :class:`~trio.lowlevel.Task` objects which are still running.
(`frozenset`): Contains all the child :class:`~trio.lowlevel.Task` objects which are still running.
def child_tasks(self): """(`frozenset`): Contains all the child :class:`~trio.lowlevel.Task` objects which are still running.""" return frozenset(self._children)
[ "def", "child_tasks", "(", "self", ")", ":", "return", "frozenset", "(", "self", ".", "_children", ")" ]
[ 883, 4 ]
[ 886, 40 ]
python
en
['en', 'en', 'en']
True
Nursery.parent_task
(self)
(`~trio.lowlevel.Task`): The Task that opened this nursery.
(`~trio.lowlevel.Task`): The Task that opened this nursery.
def parent_task(self): "(`~trio.lowlevel.Task`): The Task that opened this nursery." return self._parent_task
[ "def", "parent_task", "(", "self", ")", ":", "return", "self", ".", "_parent_task" ]
[ 889, 4 ]
[ 891, 32 ]
python
en
['en', 'en', 'en']
True
Nursery._nested_child_finished
(self, nested_child_exc)
Returns MultiError instance if there are pending exceptions.
Returns MultiError instance if there are pending exceptions.
async def _nested_child_finished(self, nested_child_exc): """Returns MultiError instance if there are pending exceptions.""" if nested_child_exc is not None: self._add_exc(nested_child_exc) self._nested_child_running = False self._check_nursery_closed() if not self._closed: # If we get cancelled (or have an exception injected, like # KeyboardInterrupt), then save that, but still wait until our # children finish. def aborted(raise_cancel): self._add_exc(capture(raise_cancel).error) return Abort.FAILED self._parent_waiting_in_aexit = True await wait_task_rescheduled(aborted) else: # Nothing to wait for, so just execute a checkpoint -- but we # still need to mix any exception (e.g. from an external # cancellation) in with the rest of our exceptions. try: await checkpoint() except BaseException as exc: self._add_exc(exc) popped = self._parent_task._child_nurseries.pop() assert popped is self if self._pending_excs: return MultiError(self._pending_excs)
[ "async", "def", "_nested_child_finished", "(", "self", ",", "nested_child_exc", ")", ":", "if", "nested_child_exc", "is", "not", "None", ":", "self", ".", "_add_exc", "(", "nested_child_exc", ")", "self", ".", "_nested_child_running", "=", "False", "self", ".", "_check_nursery_closed", "(", ")", "if", "not", "self", ".", "_closed", ":", "# If we get cancelled (or have an exception injected, like", "# KeyboardInterrupt), then save that, but still wait until our", "# children finish.", "def", "aborted", "(", "raise_cancel", ")", ":", "self", ".", "_add_exc", "(", "capture", "(", "raise_cancel", ")", ".", "error", ")", "return", "Abort", ".", "FAILED", "self", ".", "_parent_waiting_in_aexit", "=", "True", "await", "wait_task_rescheduled", "(", "aborted", ")", "else", ":", "# Nothing to wait for, so just execute a checkpoint -- but we", "# still need to mix any exception (e.g. from an external", "# cancellation) in with the rest of our exceptions.", "try", ":", "await", "checkpoint", "(", ")", "except", "BaseException", "as", "exc", ":", "self", ".", "_add_exc", "(", "exc", ")", "popped", "=", "self", ".", "_parent_task", ".", "_child_nurseries", ".", "pop", "(", ")", "assert", "popped", "is", "self", "if", "self", ".", "_pending_excs", ":", "return", "MultiError", "(", "self", ".", "_pending_excs", ")" ]
[ 910, 4 ]
[ 939, 49 ]
python
en
['en', 'en', 'en']
True
Nursery.start_soon
(self, async_fn, *args, name=None)
Creates a child task, scheduling ``await async_fn(*args)``. This and :meth:`start` are the two fundamental methods for creating concurrent tasks in Trio. Note that this is *not* an async function and you don't use await when calling it. It sets up the new task, but then returns immediately, *before* it has a chance to run. The new task won’t actually get a chance to do anything until some later point when you execute a checkpoint and the scheduler decides to run it. If you want to run a function and immediately wait for its result, then you don't need a nursery; just use ``await async_fn(*args)``. If you want to wait for the task to initialize itself before continuing, see :meth:`start`. It's possible to pass a nursery object into another task, which allows that task to start new child tasks in the first task's nursery. The child task inherits its parent nursery's cancel scopes. Args: async_fn: An async callable. args: Positional arguments for ``async_fn``. If you want to pass keyword arguments, use :func:`functools.partial`. name: The name for this task. Only used for debugging/introspection (e.g. ``repr(task_obj)``). If this isn't a string, :meth:`start_soon` will try to make it one. A common use case is if you're wrapping a function before spawning a new task, you might pass the original function as the ``name=`` to make debugging easier. Raises: RuntimeError: If this nursery is no longer open (i.e. its ``async with`` block has exited).
Creates a child task, scheduling ``await async_fn(*args)``.
def start_soon(self, async_fn, *args, name=None): """Creates a child task, scheduling ``await async_fn(*args)``. This and :meth:`start` are the two fundamental methods for creating concurrent tasks in Trio. Note that this is *not* an async function and you don't use await when calling it. It sets up the new task, but then returns immediately, *before* it has a chance to run. The new task won’t actually get a chance to do anything until some later point when you execute a checkpoint and the scheduler decides to run it. If you want to run a function and immediately wait for its result, then you don't need a nursery; just use ``await async_fn(*args)``. If you want to wait for the task to initialize itself before continuing, see :meth:`start`. It's possible to pass a nursery object into another task, which allows that task to start new child tasks in the first task's nursery. The child task inherits its parent nursery's cancel scopes. Args: async_fn: An async callable. args: Positional arguments for ``async_fn``. If you want to pass keyword arguments, use :func:`functools.partial`. name: The name for this task. Only used for debugging/introspection (e.g. ``repr(task_obj)``). If this isn't a string, :meth:`start_soon` will try to make it one. A common use case is if you're wrapping a function before spawning a new task, you might pass the original function as the ``name=`` to make debugging easier. Raises: RuntimeError: If this nursery is no longer open (i.e. its ``async with`` block has exited). """ GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name)
[ "def", "start_soon", "(", "self", ",", "async_fn", ",", "*", "args", ",", "name", "=", "None", ")", ":", "GLOBAL_RUN_CONTEXT", ".", "runner", ".", "spawn_impl", "(", "async_fn", ",", "args", ",", "self", ",", "name", ")" ]
[ 941, 4 ]
[ 982, 72 ]
python
en
['en', 'en', 'en']
True
Nursery.start
(self, async_fn, *args, name=None)
r"""Creates and initalizes a child task. Like :meth:`start_soon`, but blocks until the new task has finished initializing itself, and optionally returns some information from it. The ``async_fn`` must accept a ``task_status`` keyword argument, and it must make sure that it (or someone) eventually calls ``task_status.started()``. The conventional way to define ``async_fn`` is like:: async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED): ... task_status.started() ... :attr:`trio.TASK_STATUS_IGNORED` is a special global object with a do-nothing ``started`` method. This way your function supports being called either like ``await nursery.start(async_fn, arg1, arg2)`` or directly like ``await async_fn(arg1, arg2)``, and either way it can call ``task_status.started()`` without worrying about which mode it's in. Defining your function like this will make it obvious to readers that it supports being used in both modes. Before the child calls ``task_status.started()``, it's effectively run underneath the call to :meth:`start`: if it raises an exception then that exception is reported by :meth:`start`, and does *not* propagate out of the nursery. If :meth:`start` is cancelled, then the child task is also cancelled. When the child calls ``task_status.started()``, it's moved out from underneath :meth:`start` and into the given nursery. If the child task passes a value to ``task_status.started(value)``, then :meth:`start` returns this value. Otherwise it returns ``None``.
r"""Creates and initalizes a child task.
async def start(self, async_fn, *args, name=None): r"""Creates and initalizes a child task. Like :meth:`start_soon`, but blocks until the new task has finished initializing itself, and optionally returns some information from it. The ``async_fn`` must accept a ``task_status`` keyword argument, and it must make sure that it (or someone) eventually calls ``task_status.started()``. The conventional way to define ``async_fn`` is like:: async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED): ... task_status.started() ... :attr:`trio.TASK_STATUS_IGNORED` is a special global object with a do-nothing ``started`` method. This way your function supports being called either like ``await nursery.start(async_fn, arg1, arg2)`` or directly like ``await async_fn(arg1, arg2)``, and either way it can call ``task_status.started()`` without worrying about which mode it's in. Defining your function like this will make it obvious to readers that it supports being used in both modes. Before the child calls ``task_status.started()``, it's effectively run underneath the call to :meth:`start`: if it raises an exception then that exception is reported by :meth:`start`, and does *not* propagate out of the nursery. If :meth:`start` is cancelled, then the child task is also cancelled. When the child calls ``task_status.started()``, it's moved out from underneath :meth:`start` and into the given nursery. If the child task passes a value to ``task_status.started(value)``, then :meth:`start` returns this value. Otherwise it returns ``None``. """ if self._closed: raise RuntimeError("Nursery is closed to new arrivals") try: self._pending_starts += 1 async with open_nursery() as old_nursery: task_status = _TaskStatus(old_nursery, self) thunk = functools.partial(async_fn, task_status=task_status) task = GLOBAL_RUN_CONTEXT.runner.spawn_impl( thunk, args, old_nursery, name ) task._eventual_parent_nursery = self # Wait for either _TaskStatus.started or an exception to # cancel this nursery: # If we get here, then the child either got reparented or exited # normally. The complicated logic is all in _TaskStatus.started(). # (Any exceptions propagate directly out of the above.) if not task_status._called_started: raise RuntimeError("child exited without calling task_status.started()") return task_status._value finally: self._pending_starts -= 1 self._check_nursery_closed()
[ "async", "def", "start", "(", "self", ",", "async_fn", ",", "*", "args", ",", "name", "=", "None", ")", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"Nursery is closed to new arrivals\"", ")", "try", ":", "self", ".", "_pending_starts", "+=", "1", "async", "with", "open_nursery", "(", ")", "as", "old_nursery", ":", "task_status", "=", "_TaskStatus", "(", "old_nursery", ",", "self", ")", "thunk", "=", "functools", ".", "partial", "(", "async_fn", ",", "task_status", "=", "task_status", ")", "task", "=", "GLOBAL_RUN_CONTEXT", ".", "runner", ".", "spawn_impl", "(", "thunk", ",", "args", ",", "old_nursery", ",", "name", ")", "task", ".", "_eventual_parent_nursery", "=", "self", "# Wait for either _TaskStatus.started or an exception to", "# cancel this nursery:", "# If we get here, then the child either got reparented or exited", "# normally. The complicated logic is all in _TaskStatus.started().", "# (Any exceptions propagate directly out of the above.)", "if", "not", "task_status", ".", "_called_started", ":", "raise", "RuntimeError", "(", "\"child exited without calling task_status.started()\"", ")", "return", "task_status", ".", "_value", "finally", ":", "self", ".", "_pending_starts", "-=", "1", "self", ".", "_check_nursery_closed", "(", ")" ]
[ 984, 4 ]
[ 1046, 40 ]
python
en
['en', 'en', 'en']
True
CalculateVariables
(default_variables, params)
Calculate additional variables for use in the build (called by gyp).
Calculate additional variables for use in the build (called by gyp).
def CalculateVariables(default_variables, params): """Calculate additional variables for use in the build (called by gyp).""" flavor = gyp.common.GetFlavor(params) if flavor == 'mac': default_variables.setdefault('OS', 'mac') default_variables.setdefault('SHARED_LIB_SUFFIX', '.dylib') default_variables.setdefault('SHARED_LIB_DIR', generator_default_variables['PRODUCT_DIR']) default_variables.setdefault('LIB_DIR', generator_default_variables['PRODUCT_DIR']) # Copy additional generator configuration data from Xcode, which is shared # by the Mac Make generator. import gyp.generator.xcode as xcode_generator global generator_additional_non_configuration_keys generator_additional_non_configuration_keys = getattr(xcode_generator, 'generator_additional_non_configuration_keys', []) global generator_additional_path_sections generator_additional_path_sections = getattr(xcode_generator, 'generator_additional_path_sections', []) global generator_extra_sources_for_rules generator_extra_sources_for_rules = getattr(xcode_generator, 'generator_extra_sources_for_rules', []) COMPILABLE_EXTENSIONS.update({'.m': 'objc', '.mm' : 'objcxx'}) else: operating_system = flavor if flavor == 'android': operating_system = 'linux' # Keep this legacy behavior for now. default_variables.setdefault('OS', operating_system) if flavor == 'aix': default_variables.setdefault('SHARED_LIB_SUFFIX', '.a') else: default_variables.setdefault('SHARED_LIB_SUFFIX', '.so') default_variables.setdefault('SHARED_LIB_DIR','$(builddir)/lib.$(TOOLSET)') default_variables.setdefault('LIB_DIR', '$(obj).$(TOOLSET)')
[ "def", "CalculateVariables", "(", "default_variables", ",", "params", ")", ":", "flavor", "=", "gyp", ".", "common", ".", "GetFlavor", "(", "params", ")", "if", "flavor", "==", "'mac'", ":", "default_variables", ".", "setdefault", "(", "'OS'", ",", "'mac'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.dylib'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", "# Copy additional generator configuration data from Xcode, which is shared", "# by the Mac Make generator.", "import", "gyp", ".", "generator", ".", "xcode", "as", "xcode_generator", "global", "generator_additional_non_configuration_keys", "generator_additional_non_configuration_keys", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_non_configuration_keys'", ",", "[", "]", ")", "global", "generator_additional_path_sections", "generator_additional_path_sections", "=", "getattr", "(", "xcode_generator", ",", "'generator_additional_path_sections'", ",", "[", "]", ")", "global", "generator_extra_sources_for_rules", "generator_extra_sources_for_rules", "=", "getattr", "(", "xcode_generator", ",", "'generator_extra_sources_for_rules'", ",", "[", "]", ")", "COMPILABLE_EXTENSIONS", ".", "update", "(", "{", "'.m'", ":", "'objc'", ",", "'.mm'", ":", "'objcxx'", "}", ")", "else", ":", "operating_system", "=", "flavor", "if", "flavor", "==", "'android'", ":", "operating_system", "=", "'linux'", "# Keep this legacy behavior for now.", "default_variables", ".", "setdefault", "(", "'OS'", ",", "operating_system", ")", "if", "flavor", "==", "'aix'", ":", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.a'", ")", "else", ":", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_SUFFIX'", ",", "'.so'", ")", "default_variables", ".", "setdefault", "(", "'SHARED_LIB_DIR'", ",", "'$(builddir)/lib.$(TOOLSET)'", ")", "default_variables", ".", "setdefault", "(", "'LIB_DIR'", ",", "'$(obj).$(TOOLSET)'", ")" ]
[ 65, 0 ]
[ 99, 64 ]
python
en
['en', 'en', 'en']
True
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) android_ndk_version = generator_flags.get('android_ndk_version', None) # Android NDK requires a strict link order. if android_ndk_version: global generator_wants_sorted_dependencies generator_wants_sorted_dependencies = True output_dir = params['options'].generator_output or \ params['options'].toplevel_dir builddir_name = generator_flags.get('output_dir', 'out') qualified_out_dir = os.path.normpath(os.path.join( output_dir, builddir_name, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': params['options'].toplevel_dir, 'qualified_out_dir': qualified_out_dir, }
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "android_ndk_version", "=", "generator_flags", ".", "get", "(", "'android_ndk_version'", ",", "None", ")", "# Android NDK requires a strict link order.", "if", "android_ndk_version", ":", "global", "generator_wants_sorted_dependencies", "generator_wants_sorted_dependencies", "=", "True", "output_dir", "=", "params", "[", "'options'", "]", ".", "generator_output", "or", "params", "[", "'options'", "]", ".", "toplevel_dir", "builddir_name", "=", "generator_flags", ".", "get", "(", "'output_dir'", ",", "'out'", ")", "qualified_out_dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "builddir_name", ",", "'gypfiles'", ")", ")", "global", "generator_filelist_paths", "generator_filelist_paths", "=", "{", "'toplevel'", ":", "params", "[", "'options'", "]", ".", "toplevel_dir", ",", "'qualified_out_dir'", ":", "qualified_out_dir", ",", "}" ]
[ 102, 0 ]
[ 122, 3 ]
python
en
['en', 'en', 'en']
True
Compilable
(filename)
Return true if the file is compilable (should be in OBJS).
Return true if the file is compilable (should be in OBJS).
def Compilable(filename): """Return true if the file is compilable (should be in OBJS).""" for res in (filename.endswith(e) for e in COMPILABLE_EXTENSIONS): if res: return True return False
[ "def", "Compilable", "(", "filename", ")", ":", "for", "res", "in", "(", "filename", ".", "endswith", "(", "e", ")", "for", "e", "in", "COMPILABLE_EXTENSIONS", ")", ":", "if", "res", ":", "return", "True", "return", "False" ]
[ 582, 0 ]
[ 587, 14 ]
python
en
['en', 'en', 'en']
True
Linkable
(filename)
Return true if the file is linkable (should be on the link line).
Return true if the file is linkable (should be on the link line).
def Linkable(filename): """Return true if the file is linkable (should be on the link line).""" return filename.endswith('.o')
[ "def", "Linkable", "(", "filename", ")", ":", "return", "filename", ".", "endswith", "(", "'.o'", ")" ]
[ 590, 0 ]
[ 592, 32 ]
python
en
['en', 'en', 'en']
True
Target
(filename)
Translate a compilable filename to its .o target.
Translate a compilable filename to its .o target.
def Target(filename): """Translate a compilable filename to its .o target.""" return os.path.splitext(filename)[0] + '.o'
[ "def", "Target", "(", "filename", ")", ":", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", "+", "'.o'" ]
[ 595, 0 ]
[ 597, 45 ]
python
en
['en', 'en', 'en']
True
EscapeShellArgument
(s)
Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python
def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'"
[ "def", "EscapeShellArgument", "(", "s", ")", ":", "return", "\"'\"", "+", "s", ".", "replace", "(", "\"'\"", ",", "\"'\\\\''\"", ")", "+", "\"'\"" ]
[ 600, 0 ]
[ 605, 44 ]
python
en
['en', 'en', 'en']
True
EscapeMakeVariableExpansion
(s)
Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.
Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.
def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$')
[ "def", "EscapeMakeVariableExpansion", "(", "s", ")", ":", "return", "s", ".", "replace", "(", "'$'", ",", "'$$'", ")" ]
[ 608, 0 ]
[ 611, 29 ]
python
en
['en', 'en', 'en']
True
EscapeCppDefine
(s)
Escapes a CPP define so that it will reach the compiler unaltered.
Escapes a CPP define so that it will reach the compiler unaltered.
def EscapeCppDefine(s): """Escapes a CPP define so that it will reach the compiler unaltered.""" s = EscapeShellArgument(s) s = EscapeMakeVariableExpansion(s) # '#' characters must be escaped even embedded in a string, else Make will # treat it as the start of a comment. return s.replace('#', r'\#')
[ "def", "EscapeCppDefine", "(", "s", ")", ":", "s", "=", "EscapeShellArgument", "(", "s", ")", "s", "=", "EscapeMakeVariableExpansion", "(", "s", ")", "# '#' characters must be escaped even embedded in a string, else Make will", "# treat it as the start of a comment.", "return", "s", ".", "replace", "(", "'#'", ",", "r'\\#'", ")" ]
[ 614, 0 ]
[ 620, 30 ]
python
en
['en', 'en', 'en']
True
QuoteIfNecessary
(string)
TODO: Should this ideally be replaced with one or more of the above functions?
TODO: Should this ideally be replaced with one or more of the above functions?
def QuoteIfNecessary(string): """TODO: Should this ideally be replaced with one or more of the above functions?""" if '"' in string: string = '"' + string.replace('"', '\\"') + '"' return string
[ "def", "QuoteIfNecessary", "(", "string", ")", ":", "if", "'\"'", "in", "string", ":", "string", "=", "'\"'", "+", "string", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "+", "'\"'", "return", "string" ]
[ 623, 0 ]
[ 628, 15 ]
python
en
['en', 'en', 'en']
True
StringToMakefileVariable
(string)
Convert a string to a value that is acceptable as a make variable name.
Convert a string to a value that is acceptable as a make variable name.
def StringToMakefileVariable(string): """Convert a string to a value that is acceptable as a make variable name.""" return re.sub('[^a-zA-Z0-9_]', '_', string)
[ "def", "StringToMakefileVariable", "(", "string", ")", ":", "return", "re", ".", "sub", "(", "'[^a-zA-Z0-9_]'", ",", "'_'", ",", "string", ")" ]
[ 631, 0 ]
[ 633, 45 ]
python
en
['en', 'en', 'en']
True
Sourceify
(path)
Convert a path to its source directory form.
Convert a path to its source directory form.
def Sourceify(path): """Convert a path to its source directory form.""" if '$(' in path: return path if os.path.isabs(path): return path return srcdir_prefix + path
[ "def", "Sourceify", "(", "path", ")", ":", "if", "'$('", "in", "path", ":", "return", "path", "if", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "path", "return", "srcdir_prefix", "+", "path" ]
[ 637, 0 ]
[ 643, 29 ]
python
en
['en', 'en', 'en']
True
SourceifyAndQuoteSpaces
(path)
Convert a path to its source directory form and quote spaces.
Convert a path to its source directory form and quote spaces.
def SourceifyAndQuoteSpaces(path): """Convert a path to its source directory form and quote spaces.""" return QuoteSpaces(Sourceify(path))
[ "def", "SourceifyAndQuoteSpaces", "(", "path", ")", ":", "return", "QuoteSpaces", "(", "Sourceify", "(", "path", ")", ")" ]
[ 649, 0 ]
[ 651, 37 ]
python
en
['en', 'en', 'en']
True
_ValidateSourcesForOSX
(spec, all_sources)
Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target.
Makes sure if duplicate basenames are not specified in the source list.
def _ValidateSourcesForOSX(spec, all_sources): """Makes sure if duplicate basenames are not specified in the source list. Arguments: spec: The target dictionary containing the properties of the target. """ if spec.get('type', None) != 'static_library': return basenames = {} for source in all_sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % spec['target_name'] + error + 'libtool on OS X will generate' + ' warnings for them.') raise GypError('Duplicate basenames in sources section, see list above')
[ "def", "_ValidateSourcesForOSX", "(", "spec", ",", "all_sources", ")", ":", "if", "spec", ".", "get", "(", "'type'", ",", "None", ")", "!=", "'static_library'", ":", "return", "basenames", "=", "{", "}", "for", "source", "in", "all_sources", ":", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "source", ")", "is_compiled_file", "=", "ext", "in", "[", "'.c'", ",", "'.cc'", ",", "'.cpp'", ",", "'.cxx'", ",", "'.m'", ",", "'.mm'", ",", "'.s'", ",", "'.S'", "]", "if", "not", "is_compiled_file", ":", "continue", "basename", "=", "os", ".", "path", ".", "basename", "(", "name", ")", "# Don't include extension.", "basenames", ".", "setdefault", "(", "basename", ",", "[", "]", ")", ".", "append", "(", "source", ")", "error", "=", "''", "for", "basename", ",", "files", "in", "basenames", ".", "iteritems", "(", ")", ":", "if", "len", "(", "files", ")", ">", "1", ":", "error", "+=", "' %s: %s\\n'", "%", "(", "basename", ",", "' '", ".", "join", "(", "files", ")", ")", "if", "error", ":", "print", "(", "'static library %s has several files with the same basename:\\n'", "%", "spec", "[", "'target_name'", "]", "+", "error", "+", "'libtool on OS X will generate'", "+", "' warnings for them.'", ")", "raise", "GypError", "(", "'Duplicate basenames in sources section, see list above'", ")" ]
[ 654, 0 ]
[ 682, 76 ]
python
en
['en', 'en', 'en']
True
WriteAutoRegenerationRule
(params, root_makefile, makefile_name, build_files)
Write the target to regenerate the Makefile.
Write the target to regenerate the Makefile.
def WriteAutoRegenerationRule(params, root_makefile, makefile_name, build_files): """Write the target to regenerate the Makefile.""" options = params['options'] build_files_args = [gyp.common.RelativePath(filename, options.toplevel_dir) for filename in params['build_files_arg']] gyp_binary = gyp.common.FixIfRelativePath(params['gyp_binary'], options.toplevel_dir) if not gyp_binary.startswith(os.sep): gyp_binary = os.path.join('.', gyp_binary) root_makefile.write( "quiet_cmd_regen_makefile = ACTION Regenerating $@\n" "cmd_regen_makefile = cd $(srcdir); %(cmd)s\n" "%(makefile_name)s: %(deps)s\n" "\t$(call do_cmd,regen_makefile)\n\n" % { 'makefile_name': makefile_name, 'deps': ' '.join(map(SourceifyAndQuoteSpaces, build_files)), 'cmd': gyp.common.EncodePOSIXShellList( [gyp_binary, '-fmake'] + gyp.RegenerateFlags(options) + build_files_args)})
[ "def", "WriteAutoRegenerationRule", "(", "params", ",", "root_makefile", ",", "makefile_name", ",", "build_files", ")", ":", "options", "=", "params", "[", "'options'", "]", "build_files_args", "=", "[", "gyp", ".", "common", ".", "RelativePath", "(", "filename", ",", "options", ".", "toplevel_dir", ")", "for", "filename", "in", "params", "[", "'build_files_arg'", "]", "]", "gyp_binary", "=", "gyp", ".", "common", ".", "FixIfRelativePath", "(", "params", "[", "'gyp_binary'", "]", ",", "options", ".", "toplevel_dir", ")", "if", "not", "gyp_binary", ".", "startswith", "(", "os", ".", "sep", ")", ":", "gyp_binary", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "gyp_binary", ")", "root_makefile", ".", "write", "(", "\"quiet_cmd_regen_makefile = ACTION Regenerating $@\\n\"", "\"cmd_regen_makefile = cd $(srcdir); %(cmd)s\\n\"", "\"%(makefile_name)s: %(deps)s\\n\"", "\"\\t$(call do_cmd,regen_makefile)\\n\\n\"", "%", "{", "'makefile_name'", ":", "makefile_name", ",", "'deps'", ":", "' '", ".", "join", "(", "map", "(", "SourceifyAndQuoteSpaces", ",", "build_files", ")", ")", ",", "'cmd'", ":", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "gyp_binary", ",", "'-fmake'", "]", "+", "gyp", ".", "RegenerateFlags", "(", "options", ")", "+", "build_files_args", ")", "}", ")" ]
[ 1962, 0 ]
[ 1984, 40 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.Write
(self, qualified_target, base_path, output_filename, spec, configs, part_of_all)
The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all'
The main entry point: writes a .mk file for a single target.
def Write(self, qualified_target, base_path, output_filename, spec, configs, part_of_all): """The main entry point: writes a .mk file for a single target. Arguments: qualified_target: target we're generating base_path: path relative to source root we're building in, used to resolve target-relative paths output_filename: output .mk file name to write spec, configs: gyp info part_of_all: flag indicating this target is part of 'all' """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) self.qualified_target = qualified_target self.path = base_path self.target = spec['target_name'] self.type = spec['type'] self.toolset = spec['toolset'] self.is_mac_bundle = gyp.xcode_emulation.IsMacBundle(self.flavor, spec) if self.flavor == 'mac': self.xcode_settings = gyp.xcode_emulation.XcodeSettings(spec) else: self.xcode_settings = None deps, link_deps = self.ComputeDeps(spec) # Some of the generation below can add extra output, sources, or # link dependencies. All of the out params of the functions that # follow use names like extra_foo. extra_outputs = [] extra_sources = [] extra_link_deps = [] extra_mac_bundle_resources = [] mac_bundle_deps = [] if self.is_mac_bundle: self.output = self.ComputeMacBundleOutput(spec) self.output_binary = self.ComputeMacBundleBinaryOutput(spec) else: self.output = self.output_binary = self.ComputeOutput(spec) self.is_standalone_static_library = bool( spec.get('standalone_static_library', 0)) self._INSTALLABLE_TARGETS = ('executable', 'loadable_module', 'shared_library') if (self.is_standalone_static_library or self.type in self._INSTALLABLE_TARGETS): self.alias = os.path.basename(self.output) install_path = self._InstallableTargetInstallPath() else: self.alias = self.output install_path = self.output self.WriteLn("TOOLSET := " + self.toolset) self.WriteLn("TARGET := " + self.target) # Actions must come first, since they can generate more OBJs for use below. if 'actions' in spec: self.WriteActions(spec['actions'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) # Rules must be early like actions. if 'rules' in spec: self.WriteRules(spec['rules'], extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all) if 'copies' in spec: self.WriteCopies(spec['copies'], extra_outputs, part_of_all) # Bundle resources. if self.is_mac_bundle: all_mac_bundle_resources = ( spec.get('mac_bundle_resources', []) + extra_mac_bundle_resources) self.WriteMacBundleResources(all_mac_bundle_resources, mac_bundle_deps) self.WriteMacInfoPlist(mac_bundle_deps) # Sources. all_sources = spec.get('sources', []) + extra_sources if all_sources: if self.flavor == 'mac': # libtool on OS X generates warnings for duplicate basenames in the same # target. _ValidateSourcesForOSX(spec, all_sources) self.WriteSources( configs, deps, all_sources, extra_outputs, extra_link_deps, part_of_all, gyp.xcode_emulation.MacPrefixHeader( self.xcode_settings, lambda p: Sourceify(self.Absolutify(p)), self.Pchify)) sources = filter(Compilable, all_sources) if sources: self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT1) extensions = set([os.path.splitext(s)[1] for s in sources]) for ext in extensions: if ext in self.suffix_rules_srcdir: self.WriteLn(self.suffix_rules_srcdir[ext]) self.WriteLn(SHARED_HEADER_SUFFIX_RULES_COMMENT2) for ext in extensions: if ext in self.suffix_rules_objdir1: self.WriteLn(self.suffix_rules_objdir1[ext]) for ext in extensions: if ext in self.suffix_rules_objdir2: self.WriteLn(self.suffix_rules_objdir2[ext]) self.WriteLn('# End of this set of suffix rules') # Add dependency from bundle to bundle binary. if self.is_mac_bundle: mac_bundle_deps.append(self.output_binary) self.WriteTarget(spec, configs, deps, extra_link_deps + link_deps, mac_bundle_deps, extra_outputs, part_of_all) # Update global list of target outputs, used in dependency tracking. target_outputs[qualified_target] = install_path # Update global list of link dependencies. if self.type in ('static_library', 'shared_library'): target_link_deps[qualified_target] = self.output_binary # Currently any versions have the same effect, but in future the behavior # could be different. if self.generator_flags.get('android_ndk_version', None): self.WriteAndroidNdkModuleRule(self.target, all_sources, link_deps) self.fp.close()
[ "def", "Write", "(", "self", ",", "qualified_target", ",", "base_path", ",", "output_filename", ",", "spec", ",", "configs", ",", "part_of_all", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "output_filename", ")", "self", ".", "fp", "=", "open", "(", "output_filename", ",", "'w'", ")", "self", ".", "fp", ".", "write", "(", "header", ")", "self", ".", "qualified_target", "=", "qualified_target", "self", ".", "path", "=", "base_path", "self", ".", "target", "=", "spec", "[", "'target_name'", "]", "self", ".", "type", "=", "spec", "[", "'type'", "]", "self", ".", "toolset", "=", "spec", "[", "'toolset'", "]", "self", ".", "is_mac_bundle", "=", "gyp", ".", "xcode_emulation", ".", "IsMacBundle", "(", "self", ".", "flavor", ",", "spec", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "xcode_settings", "=", "gyp", ".", "xcode_emulation", ".", "XcodeSettings", "(", "spec", ")", "else", ":", "self", ".", "xcode_settings", "=", "None", "deps", ",", "link_deps", "=", "self", ".", "ComputeDeps", "(", "spec", ")", "# Some of the generation below can add extra output, sources, or", "# link dependencies. All of the out params of the functions that", "# follow use names like extra_foo.", "extra_outputs", "=", "[", "]", "extra_sources", "=", "[", "]", "extra_link_deps", "=", "[", "]", "extra_mac_bundle_resources", "=", "[", "]", "mac_bundle_deps", "=", "[", "]", "if", "self", ".", "is_mac_bundle", ":", "self", ".", "output", "=", "self", ".", "ComputeMacBundleOutput", "(", "spec", ")", "self", ".", "output_binary", "=", "self", ".", "ComputeMacBundleBinaryOutput", "(", "spec", ")", "else", ":", "self", ".", "output", "=", "self", ".", "output_binary", "=", "self", ".", "ComputeOutput", "(", "spec", ")", "self", ".", "is_standalone_static_library", "=", "bool", "(", "spec", ".", "get", "(", "'standalone_static_library'", ",", "0", ")", ")", "self", ".", "_INSTALLABLE_TARGETS", "=", "(", "'executable'", ",", "'loadable_module'", ",", "'shared_library'", ")", "if", "(", "self", ".", "is_standalone_static_library", "or", "self", ".", "type", "in", "self", ".", "_INSTALLABLE_TARGETS", ")", ":", "self", ".", "alias", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "output", ")", "install_path", "=", "self", ".", "_InstallableTargetInstallPath", "(", ")", "else", ":", "self", ".", "alias", "=", "self", ".", "output", "install_path", "=", "self", ".", "output", "self", ".", "WriteLn", "(", "\"TOOLSET := \"", "+", "self", ".", "toolset", ")", "self", ".", "WriteLn", "(", "\"TARGET := \"", "+", "self", ".", "target", ")", "# Actions must come first, since they can generate more OBJs for use below.", "if", "'actions'", "in", "spec", ":", "self", ".", "WriteActions", "(", "spec", "[", "'actions'", "]", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", "# Rules must be early like actions.", "if", "'rules'", "in", "spec", ":", "self", ".", "WriteRules", "(", "spec", "[", "'rules'", "]", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", "if", "'copies'", "in", "spec", ":", "self", ".", "WriteCopies", "(", "spec", "[", "'copies'", "]", ",", "extra_outputs", ",", "part_of_all", ")", "# Bundle resources.", "if", "self", ".", "is_mac_bundle", ":", "all_mac_bundle_resources", "=", "(", "spec", ".", "get", "(", "'mac_bundle_resources'", ",", "[", "]", ")", "+", "extra_mac_bundle_resources", ")", "self", ".", "WriteMacBundleResources", "(", "all_mac_bundle_resources", ",", "mac_bundle_deps", ")", "self", ".", "WriteMacInfoPlist", "(", "mac_bundle_deps", ")", "# Sources.", "all_sources", "=", "spec", ".", "get", "(", "'sources'", ",", "[", "]", ")", "+", "extra_sources", "if", "all_sources", ":", "if", "self", ".", "flavor", "==", "'mac'", ":", "# libtool on OS X generates warnings for duplicate basenames in the same", "# target.", "_ValidateSourcesForOSX", "(", "spec", ",", "all_sources", ")", "self", ".", "WriteSources", "(", "configs", ",", "deps", ",", "all_sources", ",", "extra_outputs", ",", "extra_link_deps", ",", "part_of_all", ",", "gyp", ".", "xcode_emulation", ".", "MacPrefixHeader", "(", "self", ".", "xcode_settings", ",", "lambda", "p", ":", "Sourceify", "(", "self", ".", "Absolutify", "(", "p", ")", ")", ",", "self", ".", "Pchify", ")", ")", "sources", "=", "filter", "(", "Compilable", ",", "all_sources", ")", "if", "sources", ":", "self", ".", "WriteLn", "(", "SHARED_HEADER_SUFFIX_RULES_COMMENT1", ")", "extensions", "=", "set", "(", "[", "os", ".", "path", ".", "splitext", "(", "s", ")", "[", "1", "]", "for", "s", "in", "sources", "]", ")", "for", "ext", "in", "extensions", ":", "if", "ext", "in", "self", ".", "suffix_rules_srcdir", ":", "self", ".", "WriteLn", "(", "self", ".", "suffix_rules_srcdir", "[", "ext", "]", ")", "self", ".", "WriteLn", "(", "SHARED_HEADER_SUFFIX_RULES_COMMENT2", ")", "for", "ext", "in", "extensions", ":", "if", "ext", "in", "self", ".", "suffix_rules_objdir1", ":", "self", ".", "WriteLn", "(", "self", ".", "suffix_rules_objdir1", "[", "ext", "]", ")", "for", "ext", "in", "extensions", ":", "if", "ext", "in", "self", ".", "suffix_rules_objdir2", ":", "self", ".", "WriteLn", "(", "self", ".", "suffix_rules_objdir2", "[", "ext", "]", ")", "self", ".", "WriteLn", "(", "'# End of this set of suffix rules'", ")", "# Add dependency from bundle to bundle binary.", "if", "self", ".", "is_mac_bundle", ":", "mac_bundle_deps", ".", "append", "(", "self", ".", "output_binary", ")", "self", ".", "WriteTarget", "(", "spec", ",", "configs", ",", "deps", ",", "extra_link_deps", "+", "link_deps", ",", "mac_bundle_deps", ",", "extra_outputs", ",", "part_of_all", ")", "# Update global list of target outputs, used in dependency tracking.", "target_outputs", "[", "qualified_target", "]", "=", "install_path", "# Update global list of link dependencies.", "if", "self", ".", "type", "in", "(", "'static_library'", ",", "'shared_library'", ")", ":", "target_link_deps", "[", "qualified_target", "]", "=", "self", ".", "output_binary", "# Currently any versions have the same effect, but in future the behavior", "# could be different.", "if", "self", ".", "generator_flags", ".", "get", "(", "'android_ndk_version'", ",", "None", ")", ":", "self", ".", "WriteAndroidNdkModuleRule", "(", "self", ".", "target", ",", "all_sources", ",", "link_deps", ")", "self", ".", "fp", ".", "close", "(", ")" ]
[ 727, 2 ]
[ 857, 19 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteSubMake
(self, output_filename, makefile_path, targets, build_dir)
Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project
Write a "sub-project" Makefile.
def WriteSubMake(self, output_filename, makefile_path, targets, build_dir): """Write a "sub-project" Makefile. This is a small, wrapper Makefile that calls the top-level Makefile to build the targets from a single gyp file (i.e. a sub-project). Arguments: output_filename: sub-project Makefile name to write makefile_path: path to the top-level Makefile targets: list of "all" targets for this sub-project build_dir: build output directory, relative to the sub-project """ gyp.common.EnsureDirExists(output_filename) self.fp = open(output_filename, 'w') self.fp.write(header) # For consistency with other builders, put sub-project build output in the # sub-project dir (see test/subdirectory/gyptest-subdir-all.py). self.WriteLn('export builddir_name ?= %s' % os.path.join(os.path.dirname(output_filename), build_dir)) self.WriteLn('.PHONY: all') self.WriteLn('all:') if makefile_path: makefile_path = ' -C ' + makefile_path self.WriteLn('\t$(MAKE)%s %s' % (makefile_path, ' '.join(targets))) self.fp.close()
[ "def", "WriteSubMake", "(", "self", ",", "output_filename", ",", "makefile_path", ",", "targets", ",", "build_dir", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "output_filename", ")", "self", ".", "fp", "=", "open", "(", "output_filename", ",", "'w'", ")", "self", ".", "fp", ".", "write", "(", "header", ")", "# For consistency with other builders, put sub-project build output in the", "# sub-project dir (see test/subdirectory/gyptest-subdir-all.py).", "self", ".", "WriteLn", "(", "'export builddir_name ?= %s'", "%", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "output_filename", ")", ",", "build_dir", ")", ")", "self", ".", "WriteLn", "(", "'.PHONY: all'", ")", "self", ".", "WriteLn", "(", "'all:'", ")", "if", "makefile_path", ":", "makefile_path", "=", "' -C '", "+", "makefile_path", "self", ".", "WriteLn", "(", "'\\t$(MAKE)%s %s'", "%", "(", "makefile_path", ",", "' '", ".", "join", "(", "targets", ")", ")", ")", "self", ".", "fp", ".", "close", "(", ")" ]
[ 860, 2 ]
[ 884, 19 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteActions
(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all)
Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'actions' from the gyp input.
def WriteActions(self, actions, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for action in actions: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs if int(action.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs # Write the actual command. action_commands = action['action'] if self.flavor == 'mac': action_commands = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action_commands] command = gyp.common.EncodePOSIXShellList(action_commands) if 'message' in action: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, action['message'])) else: self.WriteLn('quiet_cmd_%s = ACTION %s $@' % (name, name)) if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd %s; ' % Sourceify(self.path or '.') # command and cd_action get written to a toplevel variable called # cmd_foo. Toplevel variables can't handle things that change per # makefile like $(TARGET), so hardcode the target. command = command.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the action runs an executable from this # build which links to shared libs from this build. # actions run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn('cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:' '$(builddir)/lib.target:$$LD_LIBRARY_PATH; ' 'export LD_LIBRARY_PATH; ' '%s%s' % (name, cd_action, command)) self.WriteLn() outputs = map(self.Absolutify, outputs) # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the obj # variable for the action rule with an absolute version so that the output # goes in the right place. # Only write the 'obj' and 'builddir' rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. # Same for environment. self.WriteLn("%s: obj := $(abs_obj)" % QuoteSpaces(outputs[0])) self.WriteLn("%s: builddir := $(abs_builddir)" % QuoteSpaces(outputs[0])) self.WriteSortedXcodeEnv(outputs[0], self.GetSortedXcodeEnv()) for input in inputs: assert ' ' not in input, ( "Spaces in action input filenames not supported (%s)" % input) for output in outputs: assert ' ' not in output, ( "Spaces in action output filenames not supported (%s)" % output) # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] self.WriteDoCmd(outputs, map(Sourceify, map(self.Absolutify, inputs)), part_of_all=part_of_all, command=name) # Stuff the outputs in a variable so we can refer to them later. outputs_variable = 'action_%s_outputs' % name self.WriteLn('%s := %s' % (outputs_variable, ' '.join(outputs))) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn() self.WriteLn()
[ "def", "WriteActions", "(", "self", ",", "actions", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", ")", "for", "action", "in", "actions", ":", "name", "=", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "qualified_target", ",", "action", "[", "'action_name'", "]", ")", ")", "self", ".", "WriteLn", "(", "'### Rules for action \"%s\":'", "%", "action", "[", "'action_name'", "]", ")", "inputs", "=", "action", "[", "'inputs'", "]", "outputs", "=", "action", "[", "'outputs'", "]", "# Build up a list of outputs.", "# Collect the output dirs we'll need.", "dirs", "=", "set", "(", ")", "for", "out", "in", "outputs", ":", "dir", "=", "os", ".", "path", ".", "split", "(", "out", ")", "[", "0", "]", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "if", "int", "(", "action", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", "+=", "outputs", "if", "int", "(", "action", ".", "get", "(", "'process_outputs_as_mac_bundle_resources'", ",", "False", ")", ")", ":", "extra_mac_bundle_resources", "+=", "outputs", "# Write the actual command.", "action_commands", "=", "action", "[", "'action'", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "action_commands", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "command", ",", "env", ")", "for", "command", "in", "action_commands", "]", "command", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "action_commands", ")", "if", "'message'", "in", "action", ":", "self", ".", "WriteLn", "(", "'quiet_cmd_%s = ACTION %s $@'", "%", "(", "name", ",", "action", "[", "'message'", "]", ")", ")", "else", ":", "self", ".", "WriteLn", "(", "'quiet_cmd_%s = ACTION %s $@'", "%", "(", "name", ",", "name", ")", ")", "if", "len", "(", "dirs", ")", ">", "0", ":", "command", "=", "'mkdir -p %s'", "%", "' '", ".", "join", "(", "dirs", ")", "+", "'; '", "+", "command", "cd_action", "=", "'cd %s; '", "%", "Sourceify", "(", "self", ".", "path", "or", "'.'", ")", "# command and cd_action get written to a toplevel variable called", "# cmd_foo. Toplevel variables can't handle things that change per", "# makefile like $(TARGET), so hardcode the target.", "command", "=", "command", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "cd_action", "=", "cd_action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "# Set LD_LIBRARY_PATH in case the action runs an executable from this", "# build which links to shared libs from this build.", "# actions run on the host, so they should in theory only use host", "# libraries, but until everything is made cross-compile safe, also use", "# target libraries.", "# TODO(piman): when everything is cross-compile safe, remove lib.target", "self", ".", "WriteLn", "(", "'cmd_%s = LD_LIBRARY_PATH=$(builddir)/lib.host:'", "'$(builddir)/lib.target:$$LD_LIBRARY_PATH; '", "'export LD_LIBRARY_PATH; '", "'%s%s'", "%", "(", "name", ",", "cd_action", ",", "command", ")", ")", "self", ".", "WriteLn", "(", ")", "outputs", "=", "map", "(", "self", ".", "Absolutify", ",", "outputs", ")", "# The makefile rules are all relative to the top dir, but the gyp actions", "# are defined relative to their containing dir. This replaces the obj", "# variable for the action rule with an absolute version so that the output", "# goes in the right place.", "# Only write the 'obj' and 'builddir' rules for the \"primary\" output (:1);", "# it's superfluous for the \"extra outputs\", and this avoids accidentally", "# writing duplicate dummy rules for those outputs.", "# Same for environment.", "self", ".", "WriteLn", "(", "\"%s: obj := $(abs_obj)\"", "%", "QuoteSpaces", "(", "outputs", "[", "0", "]", ")", ")", "self", ".", "WriteLn", "(", "\"%s: builddir := $(abs_builddir)\"", "%", "QuoteSpaces", "(", "outputs", "[", "0", "]", ")", ")", "self", ".", "WriteSortedXcodeEnv", "(", "outputs", "[", "0", "]", ",", "self", ".", "GetSortedXcodeEnv", "(", ")", ")", "for", "input", "in", "inputs", ":", "assert", "' '", "not", "in", "input", ",", "(", "\"Spaces in action input filenames not supported (%s)\"", "%", "input", ")", "for", "output", "in", "outputs", ":", "assert", "' '", "not", "in", "output", ",", "(", "\"Spaces in action output filenames not supported (%s)\"", "%", "output", ")", "# See the comment in WriteCopies about expanding env vars.", "outputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "o", ",", "env", ")", "for", "o", "in", "outputs", "]", "inputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "i", ",", "env", ")", "for", "i", "in", "inputs", "]", "self", ".", "WriteDoCmd", "(", "outputs", ",", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "inputs", ")", ")", ",", "part_of_all", "=", "part_of_all", ",", "command", "=", "name", ")", "# Stuff the outputs in a variable so we can refer to them later.", "outputs_variable", "=", "'action_%s_outputs'", "%", "name", "self", ".", "WriteLn", "(", "'%s := %s'", "%", "(", "outputs_variable", ",", "' '", ".", "join", "(", "outputs", ")", ")", ")", "extra_outputs", ".", "append", "(", "'$(%s)'", "%", "outputs_variable", ")", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", ")" ]
[ 887, 2 ]
[ 984, 18 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteRules
(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all)
Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'rules' from the gyp input.
def WriteRules(self, rules, extra_sources, extra_outputs, extra_mac_bundle_resources, part_of_all): """Write Makefile code for any 'rules' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these rules (used to make other pieces dependent on these rules) part_of_all: flag indicating this target is part of 'all' """ env = self.GetSortedXcodeEnv() for rule in rules: name = StringToMakefileVariable('%s_%s' % (self.qualified_target, rule['rule_name'])) count = 0 self.WriteLn('### Generated for rule %s:' % name) all_outputs = [] for rule_source in rule.get('rule_sources', []): dirs = set() (rule_source_dirname, rule_source_basename) = os.path.split(rule_source) (rule_source_root, rule_source_ext) = \ os.path.splitext(rule_source_basename) outputs = [self.ExpandInputRoot(out, rule_source_root, rule_source_dirname) for out in rule['outputs']] for out in outputs: dir = os.path.dirname(out) if dir: dirs.add(dir) if int(rule.get('process_outputs_as_sources', False)): extra_sources += outputs if int(rule.get('process_outputs_as_mac_bundle_resources', False)): extra_mac_bundle_resources += outputs inputs = map(Sourceify, map(self.Absolutify, [rule_source] + rule.get('inputs', []))) actions = ['$(call do_cmd,%s_%d)' % (name, count)] if name == 'resources_grit': # HACK: This is ugly. Grit intentionally doesn't touch the # timestamp of its output file when the file doesn't change, # which is fine in hash-based dependency systems like scons # and forge, but not kosher in the make world. After some # discussion, hacking around it here seems like the least # amount of pain. actions += ['@touch --no-create $@'] # See the comment in WriteCopies about expanding env vars. outputs = [gyp.xcode_emulation.ExpandEnvVars(o, env) for o in outputs] inputs = [gyp.xcode_emulation.ExpandEnvVars(i, env) for i in inputs] outputs = map(self.Absolutify, outputs) all_outputs += outputs # Only write the 'obj' and 'builddir' rules for the "primary" output # (:1); it's superfluous for the "extra outputs", and this avoids # accidentally writing duplicate dummy rules for those outputs. self.WriteLn('%s: obj := $(abs_obj)' % outputs[0]) self.WriteLn('%s: builddir := $(abs_builddir)' % outputs[0]) self.WriteMakeRule(outputs, inputs, actions, command="%s_%d" % (name, count)) # Spaces in rule filenames are not supported, but rule variables have # spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)'). # The spaces within the variables are valid, so remove the variables # before checking. variables_with_spaces = re.compile(r'\$\([^ ]* \$<\)') for output in outputs: output = re.sub(variables_with_spaces, '', output) assert ' ' not in output, ( "Spaces in rule filenames not yet supported (%s)" % output) self.WriteLn('all_deps += %s' % ' '.join(outputs)) action = [self.ExpandInputRoot(ac, rule_source_root, rule_source_dirname) for ac in rule['action']] mkdirs = '' if len(dirs) > 0: mkdirs = 'mkdir -p %s; ' % ' '.join(dirs) cd_action = 'cd %s; ' % Sourceify(self.path or '.') # action, cd_action, and mkdirs get written to a toplevel variable # called cmd_foo. Toplevel variables can't handle things that change # per makefile like $(TARGET), so hardcode the target. if self.flavor == 'mac': action = [gyp.xcode_emulation.ExpandEnvVars(command, env) for command in action] action = gyp.common.EncodePOSIXShellList(action) action = action.replace('$(TARGET)', self.target) cd_action = cd_action.replace('$(TARGET)', self.target) mkdirs = mkdirs.replace('$(TARGET)', self.target) # Set LD_LIBRARY_PATH in case the rule runs an executable from this # build which links to shared libs from this build. # rules run on the host, so they should in theory only use host # libraries, but until everything is made cross-compile safe, also use # target libraries. # TODO(piman): when everything is cross-compile safe, remove lib.target self.WriteLn( "cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=" "$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; " "export LD_LIBRARY_PATH; " "%(cd_action)s%(mkdirs)s%(action)s" % { 'action': action, 'cd_action': cd_action, 'count': count, 'mkdirs': mkdirs, 'name': name, }) self.WriteLn( 'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@' % { 'count': count, 'name': name, }) self.WriteLn() count += 1 outputs_variable = 'rule_%s_outputs' % name self.WriteList(all_outputs, outputs_variable) extra_outputs.append('$(%s)' % outputs_variable) self.WriteLn('### Finished generating for rule: %s' % name) self.WriteLn() self.WriteLn('### Finished generating for all rules') self.WriteLn('')
[ "def", "WriteRules", "(", "self", ",", "rules", ",", "extra_sources", ",", "extra_outputs", ",", "extra_mac_bundle_resources", ",", "part_of_all", ")", ":", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", ")", "for", "rule", "in", "rules", ":", "name", "=", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "qualified_target", ",", "rule", "[", "'rule_name'", "]", ")", ")", "count", "=", "0", "self", ".", "WriteLn", "(", "'### Generated for rule %s:'", "%", "name", ")", "all_outputs", "=", "[", "]", "for", "rule_source", "in", "rule", ".", "get", "(", "'rule_sources'", ",", "[", "]", ")", ":", "dirs", "=", "set", "(", ")", "(", "rule_source_dirname", ",", "rule_source_basename", ")", "=", "os", ".", "path", ".", "split", "(", "rule_source", ")", "(", "rule_source_root", ",", "rule_source_ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "rule_source_basename", ")", "outputs", "=", "[", "self", ".", "ExpandInputRoot", "(", "out", ",", "rule_source_root", ",", "rule_source_dirname", ")", "for", "out", "in", "rule", "[", "'outputs'", "]", "]", "for", "out", "in", "outputs", ":", "dir", "=", "os", ".", "path", ".", "dirname", "(", "out", ")", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", "+=", "outputs", "if", "int", "(", "rule", ".", "get", "(", "'process_outputs_as_mac_bundle_resources'", ",", "False", ")", ")", ":", "extra_mac_bundle_resources", "+=", "outputs", "inputs", "=", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "[", "rule_source", "]", "+", "rule", ".", "get", "(", "'inputs'", ",", "[", "]", ")", ")", ")", "actions", "=", "[", "'$(call do_cmd,%s_%d)'", "%", "(", "name", ",", "count", ")", "]", "if", "name", "==", "'resources_grit'", ":", "# HACK: This is ugly. Grit intentionally doesn't touch the", "# timestamp of its output file when the file doesn't change,", "# which is fine in hash-based dependency systems like scons", "# and forge, but not kosher in the make world. After some", "# discussion, hacking around it here seems like the least", "# amount of pain.", "actions", "+=", "[", "'@touch --no-create $@'", "]", "# See the comment in WriteCopies about expanding env vars.", "outputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "o", ",", "env", ")", "for", "o", "in", "outputs", "]", "inputs", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "i", ",", "env", ")", "for", "i", "in", "inputs", "]", "outputs", "=", "map", "(", "self", ".", "Absolutify", ",", "outputs", ")", "all_outputs", "+=", "outputs", "# Only write the 'obj' and 'builddir' rules for the \"primary\" output", "# (:1); it's superfluous for the \"extra outputs\", and this avoids", "# accidentally writing duplicate dummy rules for those outputs.", "self", ".", "WriteLn", "(", "'%s: obj := $(abs_obj)'", "%", "outputs", "[", "0", "]", ")", "self", ".", "WriteLn", "(", "'%s: builddir := $(abs_builddir)'", "%", "outputs", "[", "0", "]", ")", "self", ".", "WriteMakeRule", "(", "outputs", ",", "inputs", ",", "actions", ",", "command", "=", "\"%s_%d\"", "%", "(", "name", ",", "count", ")", ")", "# Spaces in rule filenames are not supported, but rule variables have", "# spaces in them (e.g. RULE_INPUT_PATH expands to '$(abspath $<)').", "# The spaces within the variables are valid, so remove the variables", "# before checking.", "variables_with_spaces", "=", "re", ".", "compile", "(", "r'\\$\\([^ ]* \\$<\\)'", ")", "for", "output", "in", "outputs", ":", "output", "=", "re", ".", "sub", "(", "variables_with_spaces", ",", "''", ",", "output", ")", "assert", "' '", "not", "in", "output", ",", "(", "\"Spaces in rule filenames not yet supported (%s)\"", "%", "output", ")", "self", ".", "WriteLn", "(", "'all_deps += %s'", "%", "' '", ".", "join", "(", "outputs", ")", ")", "action", "=", "[", "self", ".", "ExpandInputRoot", "(", "ac", ",", "rule_source_root", ",", "rule_source_dirname", ")", "for", "ac", "in", "rule", "[", "'action'", "]", "]", "mkdirs", "=", "''", "if", "len", "(", "dirs", ")", ">", "0", ":", "mkdirs", "=", "'mkdir -p %s; '", "%", "' '", ".", "join", "(", "dirs", ")", "cd_action", "=", "'cd %s; '", "%", "Sourceify", "(", "self", ".", "path", "or", "'.'", ")", "# action, cd_action, and mkdirs get written to a toplevel variable", "# called cmd_foo. Toplevel variables can't handle things that change", "# per makefile like $(TARGET), so hardcode the target.", "if", "self", ".", "flavor", "==", "'mac'", ":", "action", "=", "[", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "command", ",", "env", ")", "for", "command", "in", "action", "]", "action", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "action", ")", "action", "=", "action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "cd_action", "=", "cd_action", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "mkdirs", "=", "mkdirs", ".", "replace", "(", "'$(TARGET)'", ",", "self", ".", "target", ")", "# Set LD_LIBRARY_PATH in case the rule runs an executable from this", "# build which links to shared libs from this build.", "# rules run on the host, so they should in theory only use host", "# libraries, but until everything is made cross-compile safe, also use", "# target libraries.", "# TODO(piman): when everything is cross-compile safe, remove lib.target", "self", ".", "WriteLn", "(", "\"cmd_%(name)s_%(count)d = LD_LIBRARY_PATH=\"", "\"$(builddir)/lib.host:$(builddir)/lib.target:$$LD_LIBRARY_PATH; \"", "\"export LD_LIBRARY_PATH; \"", "\"%(cd_action)s%(mkdirs)s%(action)s\"", "%", "{", "'action'", ":", "action", ",", "'cd_action'", ":", "cd_action", ",", "'count'", ":", "count", ",", "'mkdirs'", ":", "mkdirs", ",", "'name'", ":", "name", ",", "}", ")", "self", ".", "WriteLn", "(", "'quiet_cmd_%(name)s_%(count)d = RULE %(name)s_%(count)d $@'", "%", "{", "'count'", ":", "count", ",", "'name'", ":", "name", ",", "}", ")", "self", ".", "WriteLn", "(", ")", "count", "+=", "1", "outputs_variable", "=", "'rule_%s_outputs'", "%", "name", "self", ".", "WriteList", "(", "all_outputs", ",", "outputs_variable", ")", "extra_outputs", ".", "append", "(", "'$(%s)'", "%", "outputs_variable", ")", "self", ".", "WriteLn", "(", "'### Finished generating for rule: %s'", "%", "name", ")", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", "'### Finished generating for all rules'", ")", "self", ".", "WriteLn", "(", "''", ")" ]
[ 987, 2 ]
[ 1112, 20 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteCopies
(self, copies, extra_outputs, part_of_all)
Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'copies' from the gyp input.
def WriteCopies(self, copies, extra_outputs, part_of_all): """Write Makefile code for any 'copies' from the gyp input. extra_outputs: a list that will be filled in with any outputs of this action (used to make other pieces dependent on this action) part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Generated for copy rule.') variable = StringToMakefileVariable(self.qualified_target + '_copies') outputs = [] for copy in copies: for path in copy['files']: # Absolutify() may call normpath, and will strip trailing slashes. path = Sourceify(self.Absolutify(path)) filename = os.path.split(path)[1] output = Sourceify(self.Absolutify(os.path.join(copy['destination'], filename))) # If the output path has variables in it, which happens in practice for # 'copies', writing the environment as target-local doesn't work, # because the variables are already needed for the target name. # Copying the environment variables into global make variables doesn't # work either, because then the .d files will potentially contain spaces # after variable expansion, and .d file handling cannot handle spaces. # As a workaround, manually expand variables at gyp time. Since 'copies' # can't run scripts, there's no need to write the env then. # WriteDoCmd() will escape spaces for .d files. env = self.GetSortedXcodeEnv() output = gyp.xcode_emulation.ExpandEnvVars(output, env) path = gyp.xcode_emulation.ExpandEnvVars(path, env) self.WriteDoCmd([output], [path], 'copy', part_of_all) outputs.append(output) self.WriteLn('%s = %s' % (variable, ' '.join(map(QuoteSpaces, outputs)))) extra_outputs.append('$(%s)' % variable) self.WriteLn()
[ "def", "WriteCopies", "(", "self", ",", "copies", ",", "extra_outputs", ",", "part_of_all", ")", ":", "self", ".", "WriteLn", "(", "'### Generated for copy rule.'", ")", "variable", "=", "StringToMakefileVariable", "(", "self", ".", "qualified_target", "+", "'_copies'", ")", "outputs", "=", "[", "]", "for", "copy", "in", "copies", ":", "for", "path", "in", "copy", "[", "'files'", "]", ":", "# Absolutify() may call normpath, and will strip trailing slashes.", "path", "=", "Sourceify", "(", "self", ".", "Absolutify", "(", "path", ")", ")", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", "output", "=", "Sourceify", "(", "self", ".", "Absolutify", "(", "os", ".", "path", ".", "join", "(", "copy", "[", "'destination'", "]", ",", "filename", ")", ")", ")", "# If the output path has variables in it, which happens in practice for", "# 'copies', writing the environment as target-local doesn't work,", "# because the variables are already needed for the target name.", "# Copying the environment variables into global make variables doesn't", "# work either, because then the .d files will potentially contain spaces", "# after variable expansion, and .d file handling cannot handle spaces.", "# As a workaround, manually expand variables at gyp time. Since 'copies'", "# can't run scripts, there's no need to write the env then.", "# WriteDoCmd() will escape spaces for .d files.", "env", "=", "self", ".", "GetSortedXcodeEnv", "(", ")", "output", "=", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "output", ",", "env", ")", "path", "=", "gyp", ".", "xcode_emulation", ".", "ExpandEnvVars", "(", "path", ",", "env", ")", "self", ".", "WriteDoCmd", "(", "[", "output", "]", ",", "[", "path", "]", ",", "'copy'", ",", "part_of_all", ")", "outputs", ".", "append", "(", "output", ")", "self", ".", "WriteLn", "(", "'%s = %s'", "%", "(", "variable", ",", "' '", ".", "join", "(", "map", "(", "QuoteSpaces", ",", "outputs", ")", ")", ")", ")", "extra_outputs", ".", "append", "(", "'$(%s)'", "%", "variable", ")", "self", ".", "WriteLn", "(", ")" ]
[ 1115, 2 ]
[ 1150, 18 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteMacBundleResources
(self, resources, bundle_deps)
Writes Makefile code for 'mac_bundle_resources'.
Writes Makefile code for 'mac_bundle_resources'.
def WriteMacBundleResources(self, resources, bundle_deps): """Writes Makefile code for 'mac_bundle_resources'.""" self.WriteLn('### Generated for mac_bundle_resources') for output, res in gyp.xcode_emulation.GetMacBundleResources( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, map(Sourceify, map(self.Absolutify, resources))): _, ext = os.path.splitext(output) if ext != '.xcassets': # Make does not supports '.xcassets' emulation. self.WriteDoCmd([output], [res], 'mac_tool,,,copy-bundle-resource', part_of_all=True) bundle_deps.append(output)
[ "def", "WriteMacBundleResources", "(", "self", ",", "resources", ",", "bundle_deps", ")", ":", "self", ".", "WriteLn", "(", "'### Generated for mac_bundle_resources'", ")", "for", "output", ",", "res", "in", "gyp", ".", "xcode_emulation", ".", "GetMacBundleResources", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "self", ".", "xcode_settings", ",", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "resources", ")", ")", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "output", ")", "if", "ext", "!=", "'.xcassets'", ":", "# Make does not supports '.xcassets' emulation.", "self", ".", "WriteDoCmd", "(", "[", "output", "]", ",", "[", "res", "]", ",", "'mac_tool,,,copy-bundle-resource'", ",", "part_of_all", "=", "True", ")", "bundle_deps", ".", "append", "(", "output", ")" ]
[ 1153, 2 ]
[ 1165, 34 ]
python
en
['da', 'en', 'en']
True
MakefileWriter.WriteMacInfoPlist
(self, bundle_deps)
Write Makefile code for bundle Info.plist files.
Write Makefile code for bundle Info.plist files.
def WriteMacInfoPlist(self, bundle_deps): """Write Makefile code for bundle Info.plist files.""" info_plist, out, defines, extra_env = gyp.xcode_emulation.GetMacInfoPlist( generator_default_variables['PRODUCT_DIR'], self.xcode_settings, lambda p: Sourceify(self.Absolutify(p))) if not info_plist: return if defines: # Create an intermediate file to store preprocessed results. intermediate_plist = ('$(obj).$(TOOLSET)/$(TARGET)/' + os.path.basename(info_plist)) self.WriteList(defines, intermediate_plist + ': INFOPLIST_DEFINES', '-D', quoter=EscapeCppDefine) self.WriteMakeRule([intermediate_plist], [info_plist], ['$(call do_cmd,infoplist)', # "Convert" the plist so that any weird whitespace changes from the # preprocessor do not affect the XML parser in mac_tool. '@plutil -convert xml1 $@ $@']) info_plist = intermediate_plist # plists can contain envvars and substitute them into the file. self.WriteSortedXcodeEnv( out, self.GetSortedXcodeEnv(additional_settings=extra_env)) self.WriteDoCmd([out], [info_plist], 'mac_tool,,,copy-info-plist', part_of_all=True) bundle_deps.append(out)
[ "def", "WriteMacInfoPlist", "(", "self", ",", "bundle_deps", ")", ":", "info_plist", ",", "out", ",", "defines", ",", "extra_env", "=", "gyp", ".", "xcode_emulation", ".", "GetMacInfoPlist", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "self", ".", "xcode_settings", ",", "lambda", "p", ":", "Sourceify", "(", "self", ".", "Absolutify", "(", "p", ")", ")", ")", "if", "not", "info_plist", ":", "return", "if", "defines", ":", "# Create an intermediate file to store preprocessed results.", "intermediate_plist", "=", "(", "'$(obj).$(TOOLSET)/$(TARGET)/'", "+", "os", ".", "path", ".", "basename", "(", "info_plist", ")", ")", "self", ".", "WriteList", "(", "defines", ",", "intermediate_plist", "+", "': INFOPLIST_DEFINES'", ",", "'-D'", ",", "quoter", "=", "EscapeCppDefine", ")", "self", ".", "WriteMakeRule", "(", "[", "intermediate_plist", "]", ",", "[", "info_plist", "]", ",", "[", "'$(call do_cmd,infoplist)'", ",", "# \"Convert\" the plist so that any weird whitespace changes from the", "# preprocessor do not affect the XML parser in mac_tool.", "'@plutil -convert xml1 $@ $@'", "]", ")", "info_plist", "=", "intermediate_plist", "# plists can contain envvars and substitute them into the file.", "self", ".", "WriteSortedXcodeEnv", "(", "out", ",", "self", ".", "GetSortedXcodeEnv", "(", "additional_settings", "=", "extra_env", ")", ")", "self", ".", "WriteDoCmd", "(", "[", "out", "]", ",", "[", "info_plist", "]", ",", "'mac_tool,,,copy-info-plist'", ",", "part_of_all", "=", "True", ")", "bundle_deps", ".", "append", "(", "out", ")" ]
[ 1168, 2 ]
[ 1192, 27 ]
python
da
['da', 'it', 'en']
False
MakefileWriter.WriteSources
(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header)
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target.
def WriteSources(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', quoter=EscapeCppDefine) if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(configname) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get('cflags') cflags_c = config.get('cflags_c') cflags_cc = config.get('cflags_cc') self.WriteLn("# Flags passed to all source files."); self.WriteList(cflags, 'CFLAGS_%s' % configname) self.WriteLn("# Flags passed to only C files."); self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) self.WriteLn("# Flags passed to only C++ files."); self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) if self.flavor == 'mac': self.WriteLn("# Flags passed to only ObjC files."); self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) self.WriteLn("# Flags passed to only ObjC++ files."); self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) includes = config.get('include_dirs') if includes: includes = map(Sourceify, map(self.Absolutify, includes)) self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') compilable = filter(Compilable, sources) objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable))) self.WriteList(objs, 'OBJS') for obj in objs: assert ' ' not in obj, ( "Spaces in object filenames not supported (%s)" % obj) self.WriteLn('# Add to the list of files we specially track ' 'dependencies for.') self.WriteLn('all_deps += $(OBJS)') self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule(['$(OBJS)'], deps, comment = 'Make sure our dependencies are built ' 'before any of us.', order_only = True) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule(['$(OBJS)'], extra_outputs, comment = 'Make sure our actions/rules run ' 'before any of us.', order_only = True) pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) if pchdeps: self.WriteLn('# Dependencies from obj files to their precompiled headers') for source, obj, gch in pchdeps: self.WriteLn('%s: %s' % (obj, gch)) self.WriteLn('# End precompiled header dependencies') if objs: extra_link_deps.append('$(OBJS)') self.WriteLn("""\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""") self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn("$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('c') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('cc') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))") if self.flavor == 'mac': self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('m') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('mm') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))") self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += filter(Linkable, sources) self.WriteLn()
[ "def", "WriteSources", "(", "self", ",", "configs", ",", "deps", ",", "sources", ",", "extra_outputs", ",", "extra_link_deps", ",", "part_of_all", ",", "precompiled_header", ")", ":", "# Write configuration-specific variables for CFLAGS, etc.", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "self", ".", "WriteList", "(", "config", ".", "get", "(", "'defines'", ")", ",", "'DEFS_%s'", "%", "configname", ",", "prefix", "=", "'-D'", ",", "quoter", "=", "EscapeCppDefine", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "cflags", "=", "self", ".", "xcode_settings", ".", "GetCflags", "(", "configname", ")", "cflags_c", "=", "self", ".", "xcode_settings", ".", "GetCflagsC", "(", "configname", ")", "cflags_cc", "=", "self", ".", "xcode_settings", ".", "GetCflagsCC", "(", "configname", ")", "cflags_objc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjC", "(", "configname", ")", "cflags_objcc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjCC", "(", "configname", ")", "else", ":", "cflags", "=", "config", ".", "get", "(", "'cflags'", ")", "cflags_c", "=", "config", ".", "get", "(", "'cflags_c'", ")", "cflags_cc", "=", "config", ".", "get", "(", "'cflags_cc'", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to all source files.\"", ")", "self", ".", "WriteList", "(", "cflags", ",", "'CFLAGS_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C files.\"", ")", "self", ".", "WriteList", "(", "cflags_c", ",", "'CFLAGS_C_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_cc", ",", "'CFLAGS_CC_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC files.\"", ")", "self", ".", "WriteList", "(", "cflags_objc", ",", "'CFLAGS_OBJC_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_objcc", ",", "'CFLAGS_OBJCC_%s'", "%", "configname", ")", "includes", "=", "config", ".", "get", "(", "'include_dirs'", ")", "if", "includes", ":", "includes", "=", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "includes", ")", ")", "self", ".", "WriteList", "(", "includes", ",", "'INCS_%s'", "%", "configname", ",", "prefix", "=", "'-I'", ")", "compilable", "=", "filter", "(", "Compilable", ",", "sources", ")", "objs", "=", "map", "(", "self", ".", "Objectify", ",", "map", "(", "self", ".", "Absolutify", ",", "map", "(", "Target", ",", "compilable", ")", ")", ")", "self", ".", "WriteList", "(", "objs", ",", "'OBJS'", ")", "for", "obj", "in", "objs", ":", "assert", "' '", "not", "in", "obj", ",", "(", "\"Spaces in object filenames not supported (%s)\"", "%", "obj", ")", "self", ".", "WriteLn", "(", "'# Add to the list of files we specially track '", "'dependencies for.'", ")", "self", ".", "WriteLn", "(", "'all_deps += $(OBJS)'", ")", "self", ".", "WriteLn", "(", ")", "# Make sure our dependencies are built first.", "if", "deps", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "deps", ",", "comment", "=", "'Make sure our dependencies are built '", "'before any of us.'", ",", "order_only", "=", "True", ")", "# Make sure the actions and rules run first.", "# If they generate any extra headers etc., the per-.o file dep tracking", "# will catch the proper rebuilds, so order only is still ok here.", "if", "extra_outputs", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "extra_outputs", ",", "comment", "=", "'Make sure our actions/rules run '", "'before any of us.'", ",", "order_only", "=", "True", ")", "pchdeps", "=", "precompiled_header", ".", "GetObjDependencies", "(", "compilable", ",", "objs", ")", "if", "pchdeps", ":", "self", ".", "WriteLn", "(", "'# Dependencies from obj files to their precompiled headers'", ")", "for", "source", ",", "obj", ",", "gch", "in", "pchdeps", ":", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "obj", ",", "gch", ")", ")", "self", ".", "WriteLn", "(", "'# End precompiled header dependencies'", ")", "if", "objs", ":", "extra_link_deps", ".", "append", "(", "'$(OBJS)'", ")", "self", ".", "WriteLn", "(", "\"\"\"\\\n# CFLAGS et al overrides must be target-local.\n# See \"Target-specific Variable Values\" in the GNU Make manual.\"\"\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): TOOLSET := $(TOOLSET)\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'c'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'cc'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE))\"", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'m'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJC_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'mm'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJCC_$(BUILDTYPE))\"", ")", "self", ".", "WritePchTargets", "(", "precompiled_header", ".", "GetPchBuildCommands", "(", ")", ")", "# If there are any object files in our input file list, link them into our", "# output.", "extra_link_deps", "+=", "filter", "(", "Linkable", ",", "sources", ")", "self", ".", "WriteLn", "(", ")" ]
[ 1195, 2 ]
[ 1317, 18 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WritePchTargets
(self, pch_commands)
Writes make rules to compile prefix headers.
Writes make rules to compile prefix headers.
def WritePchTargets(self, pch_commands): """Writes make rules to compile prefix headers.""" if not pch_commands: return for gch, lang_flag, lang, input in pch_commands: extra_flags = { 'c': '$(CFLAGS_C_$(BUILDTYPE))', 'cc': '$(CFLAGS_CC_$(BUILDTYPE))', 'm': '$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))', 'mm': '$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))', }[lang] var_name = { 'c': 'GYP_PCH_CFLAGS', 'cc': 'GYP_PCH_CXXFLAGS', 'm': 'GYP_PCH_OBJCFLAGS', 'mm': 'GYP_PCH_OBJCXXFLAGS', }[lang] self.WriteLn("%s: %s := %s " % (gch, var_name, lang_flag) + "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "$(CFLAGS_$(BUILDTYPE)) " + extra_flags) self.WriteLn('%s: %s FORCE_DO_CMD' % (gch, input)) self.WriteLn('\t@$(call do_cmd,pch_%s,1)' % lang) self.WriteLn('') assert ' ' not in gch, ( "Spaces in gch filenames not supported (%s)" % gch) self.WriteLn('all_deps += %s' % gch) self.WriteLn('')
[ "def", "WritePchTargets", "(", "self", ",", "pch_commands", ")", ":", "if", "not", "pch_commands", ":", "return", "for", "gch", ",", "lang_flag", ",", "lang", ",", "input", "in", "pch_commands", ":", "extra_flags", "=", "{", "'c'", ":", "'$(CFLAGS_C_$(BUILDTYPE))'", ",", "'cc'", ":", "'$(CFLAGS_CC_$(BUILDTYPE))'", ",", "'m'", ":", "'$(CFLAGS_C_$(BUILDTYPE)) $(CFLAGS_OBJC_$(BUILDTYPE))'", ",", "'mm'", ":", "'$(CFLAGS_CC_$(BUILDTYPE)) $(CFLAGS_OBJCC_$(BUILDTYPE))'", ",", "}", "[", "lang", "]", "var_name", "=", "{", "'c'", ":", "'GYP_PCH_CFLAGS'", ",", "'cc'", ":", "'GYP_PCH_CXXFLAGS'", ",", "'m'", ":", "'GYP_PCH_OBJCFLAGS'", ",", "'mm'", ":", "'GYP_PCH_OBJCXXFLAGS'", ",", "}", "[", "lang", "]", "self", ".", "WriteLn", "(", "\"%s: %s := %s \"", "%", "(", "gch", ",", "var_name", ",", "lang_flag", ")", "+", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"$(CFLAGS_$(BUILDTYPE)) \"", "+", "extra_flags", ")", "self", ".", "WriteLn", "(", "'%s: %s FORCE_DO_CMD'", "%", "(", "gch", ",", "input", ")", ")", "self", ".", "WriteLn", "(", "'\\t@$(call do_cmd,pch_%s,1)'", "%", "lang", ")", "self", ".", "WriteLn", "(", "''", ")", "assert", "' '", "not", "in", "gch", ",", "(", "\"Spaces in gch filenames not supported (%s)\"", "%", "gch", ")", "self", ".", "WriteLn", "(", "'all_deps += %s'", "%", "gch", ")", "self", ".", "WriteLn", "(", "''", ")" ]
[ 1319, 2 ]
[ 1349, 22 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.ComputeOutputBasename
(self, spec)
Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so'
Return the 'output basename' of a gyp spec.
def ComputeOutputBasename(self, spec): """Return the 'output basename' of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce 'libfoobar.so' """ assert not self.is_mac_bundle if self.flavor == 'mac' and self.type in ( 'static_library', 'executable', 'shared_library', 'loadable_module'): return self.xcode_settings.GetExecutablePath() target = spec['target_name'] target_prefix = '' target_ext = '' if self.type == 'static_library': if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' target_ext = '.a' elif self.type in ('loadable_module', 'shared_library'): if target[:3] == 'lib': target = target[3:] target_prefix = 'lib' if self.flavor == 'aix': target_ext = '.a' else: target_ext = '.so' elif self.type == 'none': target = '%s.stamp' % target elif self.type != 'executable': print ("ERROR: What output file should be generated?", "type", self.type, "target", target) target_prefix = spec.get('product_prefix', target_prefix) target = spec.get('product_name', target) product_ext = spec.get('product_extension') if product_ext: target_ext = '.' + product_ext return target_prefix + target + target_ext
[ "def", "ComputeOutputBasename", "(", "self", ",", "spec", ")", ":", "assert", "not", "self", ".", "is_mac_bundle", "if", "self", ".", "flavor", "==", "'mac'", "and", "self", ".", "type", "in", "(", "'static_library'", ",", "'executable'", ",", "'shared_library'", ",", "'loadable_module'", ")", ":", "return", "self", ".", "xcode_settings", ".", "GetExecutablePath", "(", ")", "target", "=", "spec", "[", "'target_name'", "]", "target_prefix", "=", "''", "target_ext", "=", "''", "if", "self", ".", "type", "==", "'static_library'", ":", "if", "target", "[", ":", "3", "]", "==", "'lib'", ":", "target", "=", "target", "[", "3", ":", "]", "target_prefix", "=", "'lib'", "target_ext", "=", "'.a'", "elif", "self", ".", "type", "in", "(", "'loadable_module'", ",", "'shared_library'", ")", ":", "if", "target", "[", ":", "3", "]", "==", "'lib'", ":", "target", "=", "target", "[", "3", ":", "]", "target_prefix", "=", "'lib'", "if", "self", ".", "flavor", "==", "'aix'", ":", "target_ext", "=", "'.a'", "else", ":", "target_ext", "=", "'.so'", "elif", "self", ".", "type", "==", "'none'", ":", "target", "=", "'%s.stamp'", "%", "target", "elif", "self", ".", "type", "!=", "'executable'", ":", "print", "(", "\"ERROR: What output file should be generated?\"", ",", "\"type\"", ",", "self", ".", "type", ",", "\"target\"", ",", "target", ")", "target_prefix", "=", "spec", ".", "get", "(", "'product_prefix'", ",", "target_prefix", ")", "target", "=", "spec", ".", "get", "(", "'product_name'", ",", "target", ")", "product_ext", "=", "spec", ".", "get", "(", "'product_extension'", ")", "if", "product_ext", ":", "target_ext", "=", "'.'", "+", "product_ext", "return", "target_prefix", "+", "target", "+", "target_ext" ]
[ 1352, 2 ]
[ 1392, 46 ]
python
en
['en', 'haw', 'en']
True
MakefileWriter.ComputeOutput
(self, spec)
Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so'
Return the 'output' (full output path) of a gyp spec.
def ComputeOutput(self, spec): """Return the 'output' (full output path) of a gyp spec. E.g., the loadable module 'foobar' in directory 'baz' will produce '$(obj)/baz/libfoobar.so' """ assert not self.is_mac_bundle path = os.path.join('$(obj).' + self.toolset, self.path) if self.type == 'executable' or self._InstallImmediately(): path = '$(builddir)' path = spec.get('product_dir', path) return os.path.join(path, self.ComputeOutputBasename(spec))
[ "def", "ComputeOutput", "(", "self", ",", "spec", ")", ":", "assert", "not", "self", ".", "is_mac_bundle", "path", "=", "os", ".", "path", ".", "join", "(", "'$(obj).'", "+", "self", ".", "toolset", ",", "self", ".", "path", ")", "if", "self", ".", "type", "==", "'executable'", "or", "self", ".", "_InstallImmediately", "(", ")", ":", "path", "=", "'$(builddir)'", "path", "=", "spec", ".", "get", "(", "'product_dir'", ",", "path", ")", "return", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "ComputeOutputBasename", "(", "spec", ")", ")" ]
[ 1400, 2 ]
[ 1412, 63 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.ComputeMacBundleOutput
(self, spec)
Return the 'output' (full output path) to a bundle output directory.
Return the 'output' (full output path) to a bundle output directory.
def ComputeMacBundleOutput(self, spec): """Return the 'output' (full output path) to a bundle output directory.""" assert self.is_mac_bundle path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetWrapperName())
[ "def", "ComputeMacBundleOutput", "(", "self", ",", "spec", ")", ":", "assert", "self", ".", "is_mac_bundle", "path", "=", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", "return", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "xcode_settings", ".", "GetWrapperName", "(", ")", ")" ]
[ 1415, 2 ]
[ 1419, 67 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.ComputeMacBundleBinaryOutput
(self, spec)
Return the 'output' (full output path) to the binary in a bundle.
Return the 'output' (full output path) to the binary in a bundle.
def ComputeMacBundleBinaryOutput(self, spec): """Return the 'output' (full output path) to the binary in a bundle.""" path = generator_default_variables['PRODUCT_DIR'] return os.path.join(path, self.xcode_settings.GetExecutablePath())
[ "def", "ComputeMacBundleBinaryOutput", "(", "self", ",", "spec", ")", ":", "path", "=", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", "return", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "xcode_settings", ".", "GetExecutablePath", "(", ")", ")" ]
[ 1422, 2 ]
[ 1425, 70 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.ComputeDeps
(self, spec)
Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps).
Compute the dependencies of a gyp spec.
def ComputeDeps(self, spec): """Compute the dependencies of a gyp spec. Returns a tuple (deps, link_deps), where each is a list of filenames that will need to be put in front of make for either building (deps) or linking (link_deps). """ deps = [] link_deps = [] if 'dependencies' in spec: deps.extend([target_outputs[dep] for dep in spec['dependencies'] if target_outputs[dep]]) for dep in spec['dependencies']: if dep in target_link_deps: link_deps.append(target_link_deps[dep]) deps.extend(link_deps) # TODO: It seems we need to transitively link in libraries (e.g. -lfoo)? # This hack makes it work: # link_deps.extend(spec.get('libraries', [])) return (gyp.common.uniquer(deps), gyp.common.uniquer(link_deps))
[ "def", "ComputeDeps", "(", "self", ",", "spec", ")", ":", "deps", "=", "[", "]", "link_deps", "=", "[", "]", "if", "'dependencies'", "in", "spec", ":", "deps", ".", "extend", "(", "[", "target_outputs", "[", "dep", "]", "for", "dep", "in", "spec", "[", "'dependencies'", "]", "if", "target_outputs", "[", "dep", "]", "]", ")", "for", "dep", "in", "spec", "[", "'dependencies'", "]", ":", "if", "dep", "in", "target_link_deps", ":", "link_deps", ".", "append", "(", "target_link_deps", "[", "dep", "]", ")", "deps", ".", "extend", "(", "link_deps", ")", "# TODO: It seems we need to transitively link in libraries (e.g. -lfoo)?", "# This hack makes it work:", "# link_deps.extend(spec.get('libraries', []))", "return", "(", "gyp", ".", "common", ".", "uniquer", "(", "deps", ")", ",", "gyp", ".", "common", ".", "uniquer", "(", "link_deps", ")", ")" ]
[ 1428, 2 ]
[ 1447, 68 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteTarget
(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all)
Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all'
Write Makefile code to produce the final target of the gyp spec.
def WriteTarget(self, spec, configs, deps, link_deps, bundle_deps, extra_outputs, part_of_all): """Write Makefile code to produce the final target of the gyp spec. spec, configs: input from gyp. deps, link_deps: dependency lists; see ComputeDeps() extra_outputs: any extra outputs that our target should depend on part_of_all: flag indicating this target is part of 'all' """ self.WriteLn('### Rules for final target.') if extra_outputs: self.WriteDependencyOnExtraOutputs(self.output_binary, extra_outputs) self.WriteMakeRule(extra_outputs, deps, comment=('Preserve order dependency of ' 'special output on deps.'), order_only = True) target_postbuilds = {} if self.type != 'none': for configname in sorted(configs.keys()): config = configs[configname] if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(configname, generator_default_variables['PRODUCT_DIR'], lambda p: Sourceify(self.Absolutify(p))) # TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on. gyp_to_build = gyp.common.InvertRelativePath(self.path) target_postbuild = self.xcode_settings.AddImplicitPostbuilds( configname, QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output))), QuoteSpaces(os.path.normpath(os.path.join(gyp_to_build, self.output_binary)))) if target_postbuild: target_postbuilds[configname] = target_postbuild else: ldflags = config.get('ldflags', []) # Compute an rpath for this output if needed. if any(dep.endswith('.so') or '.so.' in dep for dep in deps): # We want to get the literal string "$ORIGIN" into the link command, # so we need lots of escaping. ldflags.append(r'-Wl,-rpath=\$$ORIGIN/lib.%s/' % self.toolset) ldflags.append(r'-Wl,-rpath-link=\$(builddir)/lib.%s/' % self.toolset) library_dirs = config.get('library_dirs', []) ldflags += [('-L%s' % library_dir) for library_dir in library_dirs] self.WriteList(ldflags, 'LDFLAGS_%s' % configname) if self.flavor == 'mac': self.WriteList(self.xcode_settings.GetLibtoolflags(configname), 'LIBTOOLFLAGS_%s' % configname) libraries = spec.get('libraries') if libraries: # Remove duplicate entries libraries = gyp.common.uniquer(libraries) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries) self.WriteList(libraries, 'LIBS') self.WriteLn('%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) self.WriteLn('%s: LIBS := $(LIBS)' % QuoteSpaces(self.output_binary)) if self.flavor == 'mac': self.WriteLn('%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))' % QuoteSpaces(self.output_binary)) # Postbuild actions. Like actions, but implicitly depend on the target's # output. postbuilds = [] if self.flavor == 'mac': if target_postbuilds: postbuilds.append('$(TARGET_POSTBUILDS_$(BUILDTYPE))') postbuilds.extend( gyp.xcode_emulation.GetSpecPostbuildCommands(spec)) if postbuilds: # Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE), # so we must output its definition first, since we declare variables # using ":=". self.WriteSortedXcodeEnv(self.output, self.GetSortedXcodePostbuildEnv()) for configname in target_postbuilds: self.WriteLn('%s: TARGET_POSTBUILDS_%s := %s' % (QuoteSpaces(self.output), configname, gyp.common.EncodePOSIXShellList(target_postbuilds[configname]))) # Postbuilds expect to be run in the gyp file's directory, so insert an # implicit postbuild to cd to there. postbuilds.insert(0, gyp.common.EncodePOSIXShellList(['cd', self.path])) for i in xrange(len(postbuilds)): if not postbuilds[i].startswith('$'): postbuilds[i] = EscapeShellArgument(postbuilds[i]) self.WriteLn('%s: builddir := $(abs_builddir)' % QuoteSpaces(self.output)) self.WriteLn('%s: POSTBUILDS := %s' % ( QuoteSpaces(self.output), ' '.join(postbuilds))) # A bundle directory depends on its dependencies such as bundle resources # and bundle binary. When all dependencies have been built, the bundle # needs to be packaged. if self.is_mac_bundle: # If the framework doesn't contain a binary, then nothing depends # on the actions -- make the framework depend on them directly too. self.WriteDependencyOnExtraOutputs(self.output, extra_outputs) # Bundle dependencies. Note that the code below adds actions to this # target, so if you move these two lines, move the lines below as well. self.WriteList(map(QuoteSpaces, bundle_deps), 'BUNDLE_DEPS') self.WriteLn('%s: $(BUNDLE_DEPS)' % QuoteSpaces(self.output)) # After the framework is built, package it. Needs to happen before # postbuilds, since postbuilds depend on this. if self.type in ('shared_library', 'loadable_module'): self.WriteLn('\t@$(call do_cmd,mac_package_framework,,,%s)' % self.xcode_settings.GetFrameworkVersion()) # Bundle postbuilds can depend on the whole bundle, so run them after # the bundle is packaged, not already after the bundle binary is done. if postbuilds: self.WriteLn('\t@$(call do_postbuilds)') postbuilds = [] # Don't write postbuilds for target's output. # Needed by test/mac/gyptest-rebuild.py. self.WriteLn('\t@true # No-op, used by tests') # Since this target depends on binary and resources which are in # nested subfolders, the framework directory will be older than # its dependencies usually. To prevent this rule from executing # on every build (expensive, especially with postbuilds), expliclity # update the time on the framework directory. self.WriteLn('\t@touch -c %s' % QuoteSpaces(self.output)) if postbuilds: assert not self.is_mac_bundle, ('Postbuilds for bundles should be done ' 'on the bundle, not the binary (target \'%s\')' % self.target) assert 'product_dir' not in spec, ('Postbuilds do not work with ' 'custom product_dir') if self.type == 'executable': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'link_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'link', part_of_all, postbuilds=postbuilds) elif self.type == 'static_library': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in alink input filenames not supported (%s)" % link_dep) if (self.flavor not in ('mac', 'openbsd', 'netbsd', 'win') and not self.is_standalone_static_library): self.WriteDoCmd([self.output_binary], link_deps, 'alink_thin', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd([self.output_binary], link_deps, 'alink', part_of_all, postbuilds=postbuilds) elif self.type == 'shared_library': self.WriteLn('%s: LD_INPUTS := %s' % ( QuoteSpaces(self.output_binary), ' '.join(map(QuoteSpaces, link_deps)))) self.WriteDoCmd([self.output_binary], link_deps, 'solink', part_of_all, postbuilds=postbuilds) elif self.type == 'loadable_module': for link_dep in link_deps: assert ' ' not in link_dep, ( "Spaces in module input filenames not supported (%s)" % link_dep) if self.toolset == 'host' and self.flavor == 'android': self.WriteDoCmd([self.output_binary], link_deps, 'solink_module_host', part_of_all, postbuilds=postbuilds) else: self.WriteDoCmd( [self.output_binary], link_deps, 'solink_module', part_of_all, postbuilds=postbuilds) elif self.type == 'none': # Write a stamp line. self.WriteDoCmd([self.output_binary], deps, 'touch', part_of_all, postbuilds=postbuilds) else: print "WARNING: no output for", self.type, target # Add an alias for each target (if there are any outputs). # Installable target aliases are created below. if ((self.output and self.output != self.target) and (self.type not in self._INSTALLABLE_TARGETS)): self.WriteMakeRule([self.target], [self.output], comment='Add target alias', phony = True) if part_of_all: self.WriteMakeRule(['all'], [self.target], comment = 'Add target alias to "all" target.', phony = True) # Add special-case rules for our installable targets. # 1) They need to install to the build dir or "product" dir. # 2) They get shortcuts for building (e.g. "make chrome"). # 3) They are part of "make all". if (self.type in self._INSTALLABLE_TARGETS or self.is_standalone_static_library): if self.type == 'shared_library': file_desc = 'shared library' elif self.type == 'static_library': file_desc = 'static library' else: file_desc = 'executable' install_path = self._InstallableTargetInstallPath() installable_deps = [self.output] if (self.flavor == 'mac' and not 'product_dir' in spec and self.toolset == 'target'): # On mac, products are created in install_path immediately. assert install_path == self.output, '%s != %s' % ( install_path, self.output) # Point the target alias to the final binary output. self.WriteMakeRule([self.target], [install_path], comment='Add target alias', phony = True) if install_path != self.output: assert not self.is_mac_bundle # See comment a few lines above. self.WriteDoCmd([install_path], [self.output], 'copy', comment = 'Copy this to the %s output path.' % file_desc, part_of_all=part_of_all) installable_deps.append(install_path) if self.output != self.alias and self.alias != self.target: self.WriteMakeRule([self.alias], installable_deps, comment = 'Short alias for building this %s.' % file_desc, phony = True) if part_of_all: self.WriteMakeRule(['all'], [install_path], comment = 'Add %s to "all" target.' % file_desc, phony = True)
[ "def", "WriteTarget", "(", "self", ",", "spec", ",", "configs", ",", "deps", ",", "link_deps", ",", "bundle_deps", ",", "extra_outputs", ",", "part_of_all", ")", ":", "self", ".", "WriteLn", "(", "'### Rules for final target.'", ")", "if", "extra_outputs", ":", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output_binary", ",", "extra_outputs", ")", "self", ".", "WriteMakeRule", "(", "extra_outputs", ",", "deps", ",", "comment", "=", "(", "'Preserve order dependency of '", "'special output on deps.'", ")", ",", "order_only", "=", "True", ")", "target_postbuilds", "=", "{", "}", "if", "self", ".", "type", "!=", "'none'", ":", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "ldflags", "=", "self", ".", "xcode_settings", ".", "GetLdflags", "(", "configname", ",", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ",", "lambda", "p", ":", "Sourceify", "(", "self", ".", "Absolutify", "(", "p", ")", ")", ")", "# TARGET_POSTBUILDS_$(BUILDTYPE) is added to postbuilds later on.", "gyp_to_build", "=", "gyp", ".", "common", ".", "InvertRelativePath", "(", "self", ".", "path", ")", "target_postbuild", "=", "self", ".", "xcode_settings", ".", "AddImplicitPostbuilds", "(", "configname", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output", ")", ")", ")", ",", "QuoteSpaces", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "gyp_to_build", ",", "self", ".", "output_binary", ")", ")", ")", ")", "if", "target_postbuild", ":", "target_postbuilds", "[", "configname", "]", "=", "target_postbuild", "else", ":", "ldflags", "=", "config", ".", "get", "(", "'ldflags'", ",", "[", "]", ")", "# Compute an rpath for this output if needed.", "if", "any", "(", "dep", ".", "endswith", "(", "'.so'", ")", "or", "'.so.'", "in", "dep", "for", "dep", "in", "deps", ")", ":", "# We want to get the literal string \"$ORIGIN\" into the link command,", "# so we need lots of escaping.", "ldflags", ".", "append", "(", "r'-Wl,-rpath=\\$$ORIGIN/lib.%s/'", "%", "self", ".", "toolset", ")", "ldflags", ".", "append", "(", "r'-Wl,-rpath-link=\\$(builddir)/lib.%s/'", "%", "self", ".", "toolset", ")", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "ldflags", "+=", "[", "(", "'-L%s'", "%", "library_dir", ")", "for", "library_dir", "in", "library_dirs", "]", "self", ".", "WriteList", "(", "ldflags", ",", "'LDFLAGS_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteList", "(", "self", ".", "xcode_settings", ".", "GetLibtoolflags", "(", "configname", ")", ",", "'LIBTOOLFLAGS_%s'", "%", "configname", ")", "libraries", "=", "spec", ".", "get", "(", "'libraries'", ")", "if", "libraries", ":", "# Remove duplicate entries", "libraries", "=", "gyp", ".", "common", ".", "uniquer", "(", "libraries", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "libraries", "=", "self", ".", "xcode_settings", ".", "AdjustLibraries", "(", "libraries", ")", "self", ".", "WriteList", "(", "libraries", ",", "'LIBS'", ")", "self", ".", "WriteLn", "(", "'%s: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "self", ".", "WriteLn", "(", "'%s: LIBS := $(LIBS)'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "'%s: GYP_LIBTOOLFLAGS := $(LIBTOOLFLAGS_$(BUILDTYPE))'", "%", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ")", "# Postbuild actions. Like actions, but implicitly depend on the target's", "# output.", "postbuilds", "=", "[", "]", "if", "self", ".", "flavor", "==", "'mac'", ":", "if", "target_postbuilds", ":", "postbuilds", ".", "append", "(", "'$(TARGET_POSTBUILDS_$(BUILDTYPE))'", ")", "postbuilds", ".", "extend", "(", "gyp", ".", "xcode_emulation", ".", "GetSpecPostbuildCommands", "(", "spec", ")", ")", "if", "postbuilds", ":", "# Envvars may be referenced by TARGET_POSTBUILDS_$(BUILDTYPE),", "# so we must output its definition first, since we declare variables", "# using \":=\".", "self", ".", "WriteSortedXcodeEnv", "(", "self", ".", "output", ",", "self", ".", "GetSortedXcodePostbuildEnv", "(", ")", ")", "for", "configname", "in", "target_postbuilds", ":", "self", ".", "WriteLn", "(", "'%s: TARGET_POSTBUILDS_%s := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "configname", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "target_postbuilds", "[", "configname", "]", ")", ")", ")", "# Postbuilds expect to be run in the gyp file's directory, so insert an", "# implicit postbuild to cd to there.", "postbuilds", ".", "insert", "(", "0", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "[", "'cd'", ",", "self", ".", "path", "]", ")", ")", "for", "i", "in", "xrange", "(", "len", "(", "postbuilds", ")", ")", ":", "if", "not", "postbuilds", "[", "i", "]", ".", "startswith", "(", "'$'", ")", ":", "postbuilds", "[", "i", "]", "=", "EscapeShellArgument", "(", "postbuilds", "[", "i", "]", ")", "self", ".", "WriteLn", "(", "'%s: builddir := $(abs_builddir)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "self", ".", "WriteLn", "(", "'%s: POSTBUILDS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output", ")", ",", "' '", ".", "join", "(", "postbuilds", ")", ")", ")", "# A bundle directory depends on its dependencies such as bundle resources", "# and bundle binary. When all dependencies have been built, the bundle", "# needs to be packaged.", "if", "self", ".", "is_mac_bundle", ":", "# If the framework doesn't contain a binary, then nothing depends", "# on the actions -- make the framework depend on them directly too.", "self", ".", "WriteDependencyOnExtraOutputs", "(", "self", ".", "output", ",", "extra_outputs", ")", "# Bundle dependencies. Note that the code below adds actions to this", "# target, so if you move these two lines, move the lines below as well.", "self", ".", "WriteList", "(", "map", "(", "QuoteSpaces", ",", "bundle_deps", ")", ",", "'BUNDLE_DEPS'", ")", "self", ".", "WriteLn", "(", "'%s: $(BUNDLE_DEPS)'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "# After the framework is built, package it. Needs to happen before", "# postbuilds, since postbuilds depend on this.", "if", "self", ".", "type", "in", "(", "'shared_library'", ",", "'loadable_module'", ")", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_cmd,mac_package_framework,,,%s)'", "%", "self", ".", "xcode_settings", ".", "GetFrameworkVersion", "(", ")", ")", "# Bundle postbuilds can depend on the whole bundle, so run them after", "# the bundle is packaged, not already after the bundle binary is done.", "if", "postbuilds", ":", "self", ".", "WriteLn", "(", "'\\t@$(call do_postbuilds)'", ")", "postbuilds", "=", "[", "]", "# Don't write postbuilds for target's output.", "# Needed by test/mac/gyptest-rebuild.py.", "self", ".", "WriteLn", "(", "'\\t@true # No-op, used by tests'", ")", "# Since this target depends on binary and resources which are in", "# nested subfolders, the framework directory will be older than", "# its dependencies usually. To prevent this rule from executing", "# on every build (expensive, especially with postbuilds), expliclity", "# update the time on the framework directory.", "self", ".", "WriteLn", "(", "'\\t@touch -c %s'", "%", "QuoteSpaces", "(", "self", ".", "output", ")", ")", "if", "postbuilds", ":", "assert", "not", "self", ".", "is_mac_bundle", ",", "(", "'Postbuilds for bundles should be done '", "'on the bundle, not the binary (target \\'%s\\')'", "%", "self", ".", "target", ")", "assert", "'product_dir'", "not", "in", "spec", ",", "(", "'Postbuilds do not work with '", "'custom product_dir'", ")", "if", "self", ".", "type", "==", "'executable'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "map", "(", "QuoteSpaces", ",", "link_deps", ")", ")", ")", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'link'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'static_library'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in alink input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "(", "self", ".", "flavor", "not", "in", "(", "'mac'", ",", "'openbsd'", ",", "'netbsd'", ",", "'win'", ")", "and", "not", "self", ".", "is_standalone_static_library", ")", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink_thin'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'alink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'shared_library'", ":", "self", ".", "WriteLn", "(", "'%s: LD_INPUTS := %s'", "%", "(", "QuoteSpaces", "(", "self", ".", "output_binary", ")", ",", "' '", ".", "join", "(", "map", "(", "QuoteSpaces", ",", "link_deps", ")", ")", ")", ")", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'loadable_module'", ":", "for", "link_dep", "in", "link_deps", ":", "assert", "' '", "not", "in", "link_dep", ",", "(", "\"Spaces in module input filenames not supported (%s)\"", "%", "link_dep", ")", "if", "self", ".", "toolset", "==", "'host'", "and", "self", ".", "flavor", "==", "'android'", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module_host'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "link_deps", ",", "'solink_module'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "elif", "self", ".", "type", "==", "'none'", ":", "# Write a stamp line.", "self", ".", "WriteDoCmd", "(", "[", "self", ".", "output_binary", "]", ",", "deps", ",", "'touch'", ",", "part_of_all", ",", "postbuilds", "=", "postbuilds", ")", "else", ":", "print", "\"WARNING: no output for\"", ",", "self", ".", "type", ",", "target", "# Add an alias for each target (if there are any outputs).", "# Installable target aliases are created below.", "if", "(", "(", "self", ".", "output", "and", "self", ".", "output", "!=", "self", ".", "target", ")", "and", "(", "self", ".", "type", "not", "in", "self", ".", "_INSTALLABLE_TARGETS", ")", ")", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "self", ".", "output", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "self", ".", "target", "]", ",", "comment", "=", "'Add target alias to \"all\" target.'", ",", "phony", "=", "True", ")", "# Add special-case rules for our installable targets.", "# 1) They need to install to the build dir or \"product\" dir.", "# 2) They get shortcuts for building (e.g. \"make chrome\").", "# 3) They are part of \"make all\".", "if", "(", "self", ".", "type", "in", "self", ".", "_INSTALLABLE_TARGETS", "or", "self", ".", "is_standalone_static_library", ")", ":", "if", "self", ".", "type", "==", "'shared_library'", ":", "file_desc", "=", "'shared library'", "elif", "self", ".", "type", "==", "'static_library'", ":", "file_desc", "=", "'static library'", "else", ":", "file_desc", "=", "'executable'", "install_path", "=", "self", ".", "_InstallableTargetInstallPath", "(", ")", "installable_deps", "=", "[", "self", ".", "output", "]", "if", "(", "self", ".", "flavor", "==", "'mac'", "and", "not", "'product_dir'", "in", "spec", "and", "self", ".", "toolset", "==", "'target'", ")", ":", "# On mac, products are created in install_path immediately.", "assert", "install_path", "==", "self", ".", "output", ",", "'%s != %s'", "%", "(", "install_path", ",", "self", ".", "output", ")", "# Point the target alias to the final binary output.", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "target", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add target alias'", ",", "phony", "=", "True", ")", "if", "install_path", "!=", "self", ".", "output", ":", "assert", "not", "self", ".", "is_mac_bundle", "# See comment a few lines above.", "self", ".", "WriteDoCmd", "(", "[", "install_path", "]", ",", "[", "self", ".", "output", "]", ",", "'copy'", ",", "comment", "=", "'Copy this to the %s output path.'", "%", "file_desc", ",", "part_of_all", "=", "part_of_all", ")", "installable_deps", ".", "append", "(", "install_path", ")", "if", "self", ".", "output", "!=", "self", ".", "alias", "and", "self", ".", "alias", "!=", "self", ".", "target", ":", "self", ".", "WriteMakeRule", "(", "[", "self", ".", "alias", "]", ",", "installable_deps", ",", "comment", "=", "'Short alias for building this %s.'", "%", "file_desc", ",", "phony", "=", "True", ")", "if", "part_of_all", ":", "self", ".", "WriteMakeRule", "(", "[", "'all'", "]", ",", "[", "install_path", "]", ",", "comment", "=", "'Add %s to \"all\" target.'", "%", "file_desc", ",", "phony", "=", "True", ")" ]
[ 1456, 2 ]
[ 1689, 40 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteList
(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary)
Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style.
Write a variable definition that is a list of values.
def WriteList(self, value_list, variable=None, prefix='', quoter=QuoteIfNecessary): """Write a variable definition that is a list of values. E.g. WriteList(['a','b'], 'foo', prefix='blah') writes out foo = blaha blahb but in a pretty-printed style. """ values = '' if value_list: value_list = [quoter(prefix + l) for l in value_list] values = ' \\\n\t' + ' \\\n\t'.join(value_list) self.fp.write('%s :=%s\n\n' % (variable, values))
[ "def", "WriteList", "(", "self", ",", "value_list", ",", "variable", "=", "None", ",", "prefix", "=", "''", ",", "quoter", "=", "QuoteIfNecessary", ")", ":", "values", "=", "''", "if", "value_list", ":", "value_list", "=", "[", "quoter", "(", "prefix", "+", "l", ")", "for", "l", "in", "value_list", "]", "values", "=", "' \\\\\\n\\t'", "+", "' \\\\\\n\\t'", ".", "join", "(", "value_list", ")", "self", ".", "fp", ".", "write", "(", "'%s :=%s\\n\\n'", "%", "(", "variable", ",", "values", ")", ")" ]
[ 1692, 2 ]
[ 1704, 53 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteDoCmd
(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False)
Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag.
Write a Makefile rule that uses do_cmd.
def WriteDoCmd(self, outputs, inputs, command, part_of_all, comment=None, postbuilds=False): """Write a Makefile rule that uses do_cmd. This makes the outputs dependent on the command line that was run, as well as support the V= make command line flag. """ suffix = '' if postbuilds: assert ',' not in command suffix = ',,1' # Tell do_cmd to honor $POSTBUILDS self.WriteMakeRule(outputs, inputs, actions = ['$(call do_cmd,%s%s)' % (command, suffix)], comment = comment, command = command, force = True) # Add our outputs to the list of targets we read depfiles from. # all_deps is only used for deps file reading, and for deps files we replace # spaces with ? because escaping doesn't work with make's $(sort) and # other functions. outputs = [QuoteSpaces(o, SPACE_REPLACEMENT) for o in outputs] self.WriteLn('all_deps += %s' % ' '.join(outputs))
[ "def", "WriteDoCmd", "(", "self", ",", "outputs", ",", "inputs", ",", "command", ",", "part_of_all", ",", "comment", "=", "None", ",", "postbuilds", "=", "False", ")", ":", "suffix", "=", "''", "if", "postbuilds", ":", "assert", "','", "not", "in", "command", "suffix", "=", "',,1'", "# Tell do_cmd to honor $POSTBUILDS", "self", ".", "WriteMakeRule", "(", "outputs", ",", "inputs", ",", "actions", "=", "[", "'$(call do_cmd,%s%s)'", "%", "(", "command", ",", "suffix", ")", "]", ",", "comment", "=", "comment", ",", "command", "=", "command", ",", "force", "=", "True", ")", "# Add our outputs to the list of targets we read depfiles from.", "# all_deps is only used for deps file reading, and for deps files we replace", "# spaces with ? because escaping doesn't work with make's $(sort) and", "# other functions.", "outputs", "=", "[", "QuoteSpaces", "(", "o", ",", "SPACE_REPLACEMENT", ")", "for", "o", "in", "outputs", "]", "self", ".", "WriteLn", "(", "'all_deps += %s'", "%", "' '", ".", "join", "(", "outputs", ")", ")" ]
[ 1707, 2 ]
[ 1728, 54 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteMakeRule
(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None)
Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels
Write a Makefile rule, with some extra tricks.
def WriteMakeRule(self, outputs, inputs, actions=None, comment=None, order_only=False, force=False, phony=False, command=None): """Write a Makefile rule, with some extra tricks. outputs: a list of outputs for the rule (note: this is not directly supported by make; see comments below) inputs: a list of inputs for the rule actions: a list of shell commands to run for the rule comment: a comment to put in the Makefile above the rule (also useful for making this Python script's code self-documenting) order_only: if true, makes the dependency order-only force: if true, include FORCE_DO_CMD as an order-only dep phony: if true, the rule does not actually generate the named output, the output is just a name to run the rule command: (optional) command name to generate unambiguous labels """ outputs = map(QuoteSpaces, outputs) inputs = map(QuoteSpaces, inputs) if comment: self.WriteLn('# ' + comment) if phony: self.WriteLn('.PHONY: ' + ' '.join(outputs)) if actions: self.WriteLn("%s: TOOLSET := $(TOOLSET)" % outputs[0]) force_append = ' FORCE_DO_CMD' if force else '' if order_only: # Order only rule: Just write a simple rule. # TODO(evanm): just make order_only a list of deps instead of this hack. self.WriteLn('%s: | %s%s' % (' '.join(outputs), ' '.join(inputs), force_append)) elif len(outputs) == 1: # Regular rule, one output: Just write a simple rule. self.WriteLn('%s: %s%s' % (outputs[0], ' '.join(inputs), force_append)) else: # Regular rule, more than one output: Multiple outputs are tricky in # make. We will write three rules: # - All outputs depend on an intermediate file. # - Make .INTERMEDIATE depend on the intermediate. # - The intermediate file depends on the inputs and executes the # actual command. # - The intermediate recipe will 'touch' the intermediate file. # - The multi-output rule will have an do-nothing recipe. # Hash the target name to avoid generating overlong filenames. cmddigest = hashlib.sha1(command if command else self.target).hexdigest() intermediate = "%s.intermediate" % cmddigest self.WriteLn('%s: %s' % (' '.join(outputs), intermediate)) self.WriteLn('\t%s' % '@:'); self.WriteLn('%s: %s' % ('.INTERMEDIATE', intermediate)) self.WriteLn('%s: %s%s' % (intermediate, ' '.join(inputs), force_append)) actions.insert(0, '$(call do_cmd,touch)') if actions: for action in actions: self.WriteLn('\t%s' % action) self.WriteLn()
[ "def", "WriteMakeRule", "(", "self", ",", "outputs", ",", "inputs", ",", "actions", "=", "None", ",", "comment", "=", "None", ",", "order_only", "=", "False", ",", "force", "=", "False", ",", "phony", "=", "False", ",", "command", "=", "None", ")", ":", "outputs", "=", "map", "(", "QuoteSpaces", ",", "outputs", ")", "inputs", "=", "map", "(", "QuoteSpaces", ",", "inputs", ")", "if", "comment", ":", "self", ".", "WriteLn", "(", "'# '", "+", "comment", ")", "if", "phony", ":", "self", ".", "WriteLn", "(", "'.PHONY: '", "+", "' '", ".", "join", "(", "outputs", ")", ")", "if", "actions", ":", "self", ".", "WriteLn", "(", "\"%s: TOOLSET := $(TOOLSET)\"", "%", "outputs", "[", "0", "]", ")", "force_append", "=", "' FORCE_DO_CMD'", "if", "force", "else", "''", "if", "order_only", ":", "# Order only rule: Just write a simple rule.", "# TODO(evanm): just make order_only a list of deps instead of this hack.", "self", ".", "WriteLn", "(", "'%s: | %s%s'", "%", "(", "' '", ".", "join", "(", "outputs", ")", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "elif", "len", "(", "outputs", ")", "==", "1", ":", "# Regular rule, one output: Just write a simple rule.", "self", ".", "WriteLn", "(", "'%s: %s%s'", "%", "(", "outputs", "[", "0", "]", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "else", ":", "# Regular rule, more than one output: Multiple outputs are tricky in", "# make. We will write three rules:", "# - All outputs depend on an intermediate file.", "# - Make .INTERMEDIATE depend on the intermediate.", "# - The intermediate file depends on the inputs and executes the", "# actual command.", "# - The intermediate recipe will 'touch' the intermediate file.", "# - The multi-output rule will have an do-nothing recipe.", "# Hash the target name to avoid generating overlong filenames.", "cmddigest", "=", "hashlib", ".", "sha1", "(", "command", "if", "command", "else", "self", ".", "target", ")", ".", "hexdigest", "(", ")", "intermediate", "=", "\"%s.intermediate\"", "%", "cmddigest", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "' '", ".", "join", "(", "outputs", ")", ",", "intermediate", ")", ")", "self", ".", "WriteLn", "(", "'\\t%s'", "%", "'@:'", ")", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "'.INTERMEDIATE'", ",", "intermediate", ")", ")", "self", ".", "WriteLn", "(", "'%s: %s%s'", "%", "(", "intermediate", ",", "' '", ".", "join", "(", "inputs", ")", ",", "force_append", ")", ")", "actions", ".", "insert", "(", "0", ",", "'$(call do_cmd,touch)'", ")", "if", "actions", ":", "for", "action", "in", "actions", ":", "self", ".", "WriteLn", "(", "'\\t%s'", "%", "action", ")", "self", ".", "WriteLn", "(", ")" ]
[ 1731, 2 ]
[ 1789, 18 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.WriteAndroidNdkModuleRule
(self, module_name, all_sources, link_deps)
Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents.
Write a set of LOCAL_XXX definitions for Android NDK.
def WriteAndroidNdkModuleRule(self, module_name, all_sources, link_deps): """Write a set of LOCAL_XXX definitions for Android NDK. These variable definitions will be used by Android NDK but do nothing for non-Android applications. Arguments: module_name: Android NDK module name, which must be unique among all module names. all_sources: A list of source files (will be filtered by Compilable). link_deps: A list of link dependencies, which must be sorted in the order from dependencies to dependents. """ if self.type not in ('executable', 'shared_library', 'static_library'): return self.WriteLn('# Variable definitions for Android applications') self.WriteLn('include $(CLEAR_VARS)') self.WriteLn('LOCAL_MODULE := ' + module_name) self.WriteLn('LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) ' '$(DEFS_$(BUILDTYPE)) ' # LOCAL_CFLAGS is applied to both of C and C++. There is # no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C # sources. '$(CFLAGS_C_$(BUILDTYPE)) ' # $(INCS_$(BUILDTYPE)) includes the prefix '-I' while # LOCAL_C_INCLUDES does not expect it. So put it in # LOCAL_CFLAGS. '$(INCS_$(BUILDTYPE))') # LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred. self.WriteLn('LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))') self.WriteLn('LOCAL_C_INCLUDES :=') self.WriteLn('LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)') # Detect the C++ extension. cpp_ext = {'.cc': 0, '.cpp': 0, '.cxx': 0} default_cpp_ext = '.cpp' for filename in all_sources: ext = os.path.splitext(filename)[1] if ext in cpp_ext: cpp_ext[ext] += 1 if cpp_ext[ext] > cpp_ext[default_cpp_ext]: default_cpp_ext = ext self.WriteLn('LOCAL_CPP_EXTENSION := ' + default_cpp_ext) self.WriteList(map(self.Absolutify, filter(Compilable, all_sources)), 'LOCAL_SRC_FILES') # Filter out those which do not match prefix and suffix and produce # the resulting list without prefix and suffix. def DepsToModules(deps, prefix, suffix): modules = [] for filepath in deps: filename = os.path.basename(filepath) if filename.startswith(prefix) and filename.endswith(suffix): modules.append(filename[len(prefix):-len(suffix)]) return modules # Retrieve the default value of 'SHARED_LIB_SUFFIX' params = {'flavor': 'linux'} default_variables = {} CalculateVariables(default_variables, params) self.WriteList( DepsToModules(link_deps, generator_default_variables['SHARED_LIB_PREFIX'], default_variables['SHARED_LIB_SUFFIX']), 'LOCAL_SHARED_LIBRARIES') self.WriteList( DepsToModules(link_deps, generator_default_variables['STATIC_LIB_PREFIX'], generator_default_variables['STATIC_LIB_SUFFIX']), 'LOCAL_STATIC_LIBRARIES') if self.type == 'executable': self.WriteLn('include $(BUILD_EXECUTABLE)') elif self.type == 'shared_library': self.WriteLn('include $(BUILD_SHARED_LIBRARY)') elif self.type == 'static_library': self.WriteLn('include $(BUILD_STATIC_LIBRARY)') self.WriteLn()
[ "def", "WriteAndroidNdkModuleRule", "(", "self", ",", "module_name", ",", "all_sources", ",", "link_deps", ")", ":", "if", "self", ".", "type", "not", "in", "(", "'executable'", ",", "'shared_library'", ",", "'static_library'", ")", ":", "return", "self", ".", "WriteLn", "(", "'# Variable definitions for Android applications'", ")", "self", ".", "WriteLn", "(", "'include $(CLEAR_VARS)'", ")", "self", ".", "WriteLn", "(", "'LOCAL_MODULE := '", "+", "module_name", ")", "self", ".", "WriteLn", "(", "'LOCAL_CFLAGS := $(CFLAGS_$(BUILDTYPE)) '", "'$(DEFS_$(BUILDTYPE)) '", "# LOCAL_CFLAGS is applied to both of C and C++. There is", "# no way to specify $(CFLAGS_C_$(BUILDTYPE)) only for C", "# sources.", "'$(CFLAGS_C_$(BUILDTYPE)) '", "# $(INCS_$(BUILDTYPE)) includes the prefix '-I' while", "# LOCAL_C_INCLUDES does not expect it. So put it in", "# LOCAL_CFLAGS.", "'$(INCS_$(BUILDTYPE))'", ")", "# LOCAL_CXXFLAGS is obsolete and LOCAL_CPPFLAGS is preferred.", "self", ".", "WriteLn", "(", "'LOCAL_CPPFLAGS := $(CFLAGS_CC_$(BUILDTYPE))'", ")", "self", ".", "WriteLn", "(", "'LOCAL_C_INCLUDES :='", ")", "self", ".", "WriteLn", "(", "'LOCAL_LDLIBS := $(LDFLAGS_$(BUILDTYPE)) $(LIBS)'", ")", "# Detect the C++ extension.", "cpp_ext", "=", "{", "'.cc'", ":", "0", ",", "'.cpp'", ":", "0", ",", "'.cxx'", ":", "0", "}", "default_cpp_ext", "=", "'.cpp'", "for", "filename", "in", "all_sources", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "if", "ext", "in", "cpp_ext", ":", "cpp_ext", "[", "ext", "]", "+=", "1", "if", "cpp_ext", "[", "ext", "]", ">", "cpp_ext", "[", "default_cpp_ext", "]", ":", "default_cpp_ext", "=", "ext", "self", ".", "WriteLn", "(", "'LOCAL_CPP_EXTENSION := '", "+", "default_cpp_ext", ")", "self", ".", "WriteList", "(", "map", "(", "self", ".", "Absolutify", ",", "filter", "(", "Compilable", ",", "all_sources", ")", ")", ",", "'LOCAL_SRC_FILES'", ")", "# Filter out those which do not match prefix and suffix and produce", "# the resulting list without prefix and suffix.", "def", "DepsToModules", "(", "deps", ",", "prefix", ",", "suffix", ")", ":", "modules", "=", "[", "]", "for", "filepath", "in", "deps", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "filepath", ")", "if", "filename", ".", "startswith", "(", "prefix", ")", "and", "filename", ".", "endswith", "(", "suffix", ")", ":", "modules", ".", "append", "(", "filename", "[", "len", "(", "prefix", ")", ":", "-", "len", "(", "suffix", ")", "]", ")", "return", "modules", "# Retrieve the default value of 'SHARED_LIB_SUFFIX'", "params", "=", "{", "'flavor'", ":", "'linux'", "}", "default_variables", "=", "{", "}", "CalculateVariables", "(", "default_variables", ",", "params", ")", "self", ".", "WriteList", "(", "DepsToModules", "(", "link_deps", ",", "generator_default_variables", "[", "'SHARED_LIB_PREFIX'", "]", ",", "default_variables", "[", "'SHARED_LIB_SUFFIX'", "]", ")", ",", "'LOCAL_SHARED_LIBRARIES'", ")", "self", ".", "WriteList", "(", "DepsToModules", "(", "link_deps", ",", "generator_default_variables", "[", "'STATIC_LIB_PREFIX'", "]", ",", "generator_default_variables", "[", "'STATIC_LIB_SUFFIX'", "]", ")", ",", "'LOCAL_STATIC_LIBRARIES'", ")", "if", "self", ".", "type", "==", "'executable'", ":", "self", ".", "WriteLn", "(", "'include $(BUILD_EXECUTABLE)'", ")", "elif", "self", ".", "type", "==", "'shared_library'", ":", "self", ".", "WriteLn", "(", "'include $(BUILD_SHARED_LIBRARY)'", ")", "elif", "self", ".", "type", "==", "'static_library'", ":", "self", ".", "WriteLn", "(", "'include $(BUILD_STATIC_LIBRARY)'", ")", "self", ".", "WriteLn", "(", ")" ]
[ 1792, 2 ]
[ 1872, 18 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.Objectify
(self, path)
Convert a path to its output directory form.
Convert a path to its output directory form.
def Objectify(self, path): """Convert a path to its output directory form.""" if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/' % self.toolset) if not '$(obj)' in path: path = '$(obj).%s/$(TARGET)/%s' % (self.toolset, path) return path
[ "def", "Objectify", "(", "self", ",", "path", ")", ":", "if", "'$('", "in", "path", ":", "path", "=", "path", ".", "replace", "(", "'$(obj)/'", ",", "'$(obj).%s/$(TARGET)/'", "%", "self", ".", "toolset", ")", "if", "not", "'$(obj)'", "in", "path", ":", "path", "=", "'$(obj).%s/$(TARGET)/%s'", "%", "(", "self", ".", "toolset", ",", "path", ")", "return", "path" ]
[ 1908, 2 ]
[ 1914, 15 ]
python
en
['en', 'en', 'en']
True
MakefileWriter.Pchify
(self, path, lang)
Convert a prefix header path to its output directory form.
Convert a prefix header path to its output directory form.
def Pchify(self, path, lang): """Convert a prefix header path to its output directory form.""" path = self.Absolutify(path) if '$(' in path: path = path.replace('$(obj)/', '$(obj).%s/$(TARGET)/pch-%s' % (self.toolset, lang)) return path return '$(obj).%s/$(TARGET)/pch-%s/%s' % (self.toolset, lang, path)
[ "def", "Pchify", "(", "self", ",", "path", ",", "lang", ")", ":", "path", "=", "self", ".", "Absolutify", "(", "path", ")", "if", "'$('", "in", "path", ":", "path", "=", "path", ".", "replace", "(", "'$(obj)/'", ",", "'$(obj).%s/$(TARGET)/pch-%s'", "%", "(", "self", ".", "toolset", ",", "lang", ")", ")", "return", "path", "return", "'$(obj).%s/$(TARGET)/pch-%s/%s'", "%", "(", "self", ".", "toolset", ",", "lang", ",", "path", ")" ]
[ 1917, 2 ]
[ 1924, 71 ]
python
en
['en', 'lb', 'en']
True
MakefileWriter.Absolutify
(self, path)
Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.
Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.
def Absolutify(self, path): """Convert a subdirectory-relative path into a base-relative path. Skips over paths that contain variables.""" if '$(' in path: # Don't call normpath in this case, as it might collapse the # path too aggressively if it features '..'. However it's still # important to strip trailing slashes. return path.rstrip('/') return os.path.normpath(os.path.join(self.path, path))
[ "def", "Absolutify", "(", "self", ",", "path", ")", ":", "if", "'$('", "in", "path", ":", "# Don't call normpath in this case, as it might collapse the", "# path too aggressively if it features '..'. However it's still", "# important to strip trailing slashes.", "return", "path", ".", "rstrip", "(", "'/'", ")", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "path", ")", ")" ]
[ 1927, 2 ]
[ 1935, 58 ]
python
en
['it', 'en', 'en']
True
MakefileWriter._InstallableTargetInstallPath
(self)
Returns the location of the final output for an installable target.
Returns the location of the final output for an installable target.
def _InstallableTargetInstallPath(self): """Returns the location of the final output for an installable target.""" # Xcode puts shared_library results into PRODUCT_DIR, and some gyp files # rely on this. Emulate this behavior for mac. # XXX(TooTallNate): disabling this code since we don't want this behavior... #if (self.type == 'shared_library' and # (self.flavor != 'mac' or self.toolset != 'target')): # # Install all shared libs into a common directory (per toolset) for # # convenient access with LD_LIBRARY_PATH. # return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias) return '$(builddir)/' + self.alias
[ "def", "_InstallableTargetInstallPath", "(", "self", ")", ":", "# Xcode puts shared_library results into PRODUCT_DIR, and some gyp files", "# rely on this. Emulate this behavior for mac.", "# XXX(TooTallNate): disabling this code since we don't want this behavior...", "#if (self.type == 'shared_library' and", "# (self.flavor != 'mac' or self.toolset != 'target')):", "# # Install all shared libs into a common directory (per toolset) for", "# # convenient access with LD_LIBRARY_PATH.", "# return '$(builddir)/lib.%s/%s' % (self.toolset, self.alias)", "return", "'$(builddir)/'", "+", "self", ".", "alias" ]
[ 1948, 2 ]
[ 1959, 38 ]
python
en
['en', 'en', 'en']
True
ExpectColumnStdevToBeBetween.validate_configuration
(self, configuration: Optional[ExpectationConfiguration])
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: True if the configuration has been validated successfully. Otherwise, raises an exception
Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation.
def validate_configuration(self, configuration: Optional[ExpectationConfiguration]): """ Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: True if the configuration has been validated successfully. Otherwise, raises an exception """ super().validate_configuration(configuration) self.validate_metric_value_between_configuration(configuration=configuration)
[ "def", "validate_configuration", "(", "self", ",", "configuration", ":", "Optional", "[", "ExpectationConfiguration", "]", ")", ":", "super", "(", ")", ".", "validate_configuration", "(", "configuration", ")", "self", ".", "validate_metric_value_between_configuration", "(", "configuration", "=", "configuration", ")" ]
[ 102, 4 ]
[ 114, 85 ]
python
en
['en', 'error', 'th']
False
preprocess
( project_directory, output_directory, all_files, show_progress=True)
Call preprocessor on selected files.
Call preprocessor on selected files.
def preprocess( project_directory, output_directory, all_files, show_progress=True): """ Call preprocessor on selected files. """ for filepath in all_files: preprocessor(project_directory, output_directory, filepath) if show_progress: print( filepath, "->", get_hip_file_path(filepath)) print("Successfully preprocessed all matching files.")
[ "def", "preprocess", "(", "project_directory", ",", "output_directory", ",", "all_files", ",", "show_progress", "=", "True", ")", ":", "for", "filepath", "in", "all_files", ":", "preprocessor", "(", "project_directory", ",", "output_directory", ",", "filepath", ")", "if", "show_progress", ":", "print", "(", "filepath", ",", "\"->\"", ",", "get_hip_file_path", "(", "filepath", ")", ")", "print", "(", "\"Successfully preprocessed all matching files.\"", ")" ]
[ 83, 0 ]
[ 99, 58 ]
python
en
['en', 'error', 'th']
False
add_dim3
(kernel_string, cuda_kernel)
adds dim3() to the second and third arguments in the kernel launch
adds dim3() to the second and third arguments in the kernel launch
def add_dim3(kernel_string, cuda_kernel): '''adds dim3() to the second and third arguments in the kernel launch''' count = 0 closure = 0 kernel_string = kernel_string.replace("<<<", "").replace(">>>", "") arg_locs = [{} for _ in range(2)] arg_locs[count]['start'] = 0 for ind, c in enumerate(kernel_string): if count > 1: break if c == "(": closure += 1 elif c == ")": closure -= 1 elif (c == "," or ind == len(kernel_string) - 1) and closure == 0: arg_locs[count]['end'] = ind + (c != ",") count += 1 if count < 2: arg_locs[count]['start'] = ind + 1 first_arg_raw = kernel_string[arg_locs[0]['start']:arg_locs[0]['end'] + 1] second_arg_raw = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']] first_arg_clean = kernel_string[arg_locs[0]['start']:arg_locs[0]['end']].replace("\n", "").strip(" ") second_arg_clean = kernel_string[arg_locs[1]['start']:arg_locs[1]['end']].replace("\n", "").strip(" ") first_arg_dim3 = "dim3({})".format(first_arg_clean) second_arg_dim3 = "dim3({})".format(second_arg_clean) first_arg_raw_dim3 = first_arg_raw.replace(first_arg_clean, first_arg_dim3) second_arg_raw_dim3 = second_arg_raw.replace(second_arg_clean, second_arg_dim3) cuda_kernel = cuda_kernel.replace(first_arg_raw + second_arg_raw, first_arg_raw_dim3 + second_arg_raw_dim3) return cuda_kernel
[ "def", "add_dim3", "(", "kernel_string", ",", "cuda_kernel", ")", ":", "count", "=", "0", "closure", "=", "0", "kernel_string", "=", "kernel_string", ".", "replace", "(", "\"<<<\"", ",", "\"\"", ")", ".", "replace", "(", "\">>>\"", ",", "\"\"", ")", "arg_locs", "=", "[", "{", "}", "for", "_", "in", "range", "(", "2", ")", "]", "arg_locs", "[", "count", "]", "[", "'start'", "]", "=", "0", "for", "ind", ",", "c", "in", "enumerate", "(", "kernel_string", ")", ":", "if", "count", ">", "1", ":", "break", "if", "c", "==", "\"(\"", ":", "closure", "+=", "1", "elif", "c", "==", "\")\"", ":", "closure", "-=", "1", "elif", "(", "c", "==", "\",\"", "or", "ind", "==", "len", "(", "kernel_string", ")", "-", "1", ")", "and", "closure", "==", "0", ":", "arg_locs", "[", "count", "]", "[", "'end'", "]", "=", "ind", "+", "(", "c", "!=", "\",\"", ")", "count", "+=", "1", "if", "count", "<", "2", ":", "arg_locs", "[", "count", "]", "[", "'start'", "]", "=", "ind", "+", "1", "first_arg_raw", "=", "kernel_string", "[", "arg_locs", "[", "0", "]", "[", "'start'", "]", ":", "arg_locs", "[", "0", "]", "[", "'end'", "]", "+", "1", "]", "second_arg_raw", "=", "kernel_string", "[", "arg_locs", "[", "1", "]", "[", "'start'", "]", ":", "arg_locs", "[", "1", "]", "[", "'end'", "]", "]", "first_arg_clean", "=", "kernel_string", "[", "arg_locs", "[", "0", "]", "[", "'start'", "]", ":", "arg_locs", "[", "0", "]", "[", "'end'", "]", "]", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ".", "strip", "(", "\" \"", ")", "second_arg_clean", "=", "kernel_string", "[", "arg_locs", "[", "1", "]", "[", "'start'", "]", ":", "arg_locs", "[", "1", "]", "[", "'end'", "]", "]", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ".", "strip", "(", "\" \"", ")", "first_arg_dim3", "=", "\"dim3({})\"", ".", "format", "(", "first_arg_clean", ")", "second_arg_dim3", "=", "\"dim3({})\"", ".", "format", "(", "second_arg_clean", ")", "first_arg_raw_dim3", "=", "first_arg_raw", ".", "replace", "(", "first_arg_clean", ",", "first_arg_dim3", ")", "second_arg_raw_dim3", "=", "second_arg_raw", ".", "replace", "(", "second_arg_clean", ",", "second_arg_dim3", ")", "cuda_kernel", "=", "cuda_kernel", ".", "replace", "(", "first_arg_raw", "+", "second_arg_raw", ",", "first_arg_raw_dim3", "+", "second_arg_raw_dim3", ")", "return", "cuda_kernel" ]
[ 102, 0 ]
[ 134, 22 ]
python
en
['en', 'en', 'en']
True
processKernelLaunches
(string)
Replace the CUDA style Kernel launches with the HIP style kernel launches.
Replace the CUDA style Kernel launches with the HIP style kernel launches.
def processKernelLaunches(string): """ Replace the CUDA style Kernel launches with the HIP style kernel launches.""" # Concat the namespace with the kernel names. (Find cleaner way of doing this later). string = RE_KERNEL_LAUNCH.sub(lambda inp: "{0}{1}::".format(inp.group(1), inp.group(2)), string) def grab_method_and_template(in_kernel): # The positions for relevant kernel components. pos = { "kernel_launch": {"start": in_kernel["start"], "end": in_kernel["end"]}, "kernel_name": {"start": -1, "end": -1}, "template": {"start": -1, "end": -1} } # Count for balancing template count = {"<>": 0} # Status for whether we are parsing a certain item. START = 0 AT_TEMPLATE = 1 AFTER_TEMPLATE = 2 AT_KERNEL_NAME = 3 status = START # Parse the string character by character for i in range(pos["kernel_launch"]["start"] - 1, -1, -1): char = string[i] # Handle Templating Arguments if status == START or status == AT_TEMPLATE: if char == ">": if status == START: status = AT_TEMPLATE pos["template"]["end"] = i count["<>"] += 1 if char == "<": count["<>"] -= 1 if count["<>"] == 0 and (status == AT_TEMPLATE): pos["template"]["start"] = i status = AFTER_TEMPLATE # Handle Kernel Name if status != AT_TEMPLATE: if string[i].isalnum() or string[i] in {'(', ')', '_', ':', '#'}: if status != AT_KERNEL_NAME: status = AT_KERNEL_NAME pos["kernel_name"]["end"] = i # Case: Kernel name starts the string. if i == 0: pos["kernel_name"]["start"] = 0 # Finished return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] else: # Potential ending point if we're already traversing a kernel's name. if status == AT_KERNEL_NAME: pos["kernel_name"]["start"] = i # Finished return [(pos["kernel_name"]), (pos["template"]), (pos["kernel_launch"])] def find_kernel_bounds(string): """Finds the starting and ending points for all kernel launches in the string.""" kernel_end = 0 kernel_positions = [] # Continue until we cannot find any more kernels anymore. while string.find("<<<", kernel_end) != -1: # Get kernel starting position (starting from the previous ending point) kernel_start = string.find("<<<", kernel_end) # Get kernel ending position (adjust end point past the >>>) kernel_end = string.find(">>>", kernel_start) + 3 if kernel_end <= 0: raise InputError("no kernel end found") # Add to list of traversed kernels kernel_positions.append({"start": kernel_start, "end": kernel_end, "group": string[kernel_start: kernel_end]}) return kernel_positions # Grab positional ranges of all kernel launchces get_kernel_positions = [k for k in find_kernel_bounds(string)] output_string = string # Replace each CUDA kernel with a HIP kernel. for kernel in get_kernel_positions: # Get kernel components params = grab_method_and_template(kernel) # Find parenthesis after kernel launch parenthesis = string.find("(", kernel["end"]) # Extract cuda kernel cuda_kernel = string[params[0]["start"]:parenthesis + 1] kernel_string = string[kernel['start']:kernel['end']] cuda_kernel_dim3 = add_dim3(kernel_string, cuda_kernel) # Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size) num_klp = len(extract_arguments(0, kernel["group"].replace("<<<", "(").replace(">>>", ")"))) hip_kernel = "hipLaunchKernelGGL(" + cuda_kernel_dim3[0:-1].replace( ">>>", ", 0" * (4 - num_klp) + ">>>").replace("<<<", ", ").replace(">>>", ", ") # Replace cuda kernel with hip kernel output_string = output_string.replace(cuda_kernel, hip_kernel) return output_string
[ "def", "processKernelLaunches", "(", "string", ")", ":", "# Concat the namespace with the kernel names. (Find cleaner way of doing this later).", "string", "=", "RE_KERNEL_LAUNCH", ".", "sub", "(", "lambda", "inp", ":", "\"{0}{1}::\"", ".", "format", "(", "inp", ".", "group", "(", "1", ")", ",", "inp", ".", "group", "(", "2", ")", ")", ",", "string", ")", "def", "grab_method_and_template", "(", "in_kernel", ")", ":", "# The positions for relevant kernel components.", "pos", "=", "{", "\"kernel_launch\"", ":", "{", "\"start\"", ":", "in_kernel", "[", "\"start\"", "]", ",", "\"end\"", ":", "in_kernel", "[", "\"end\"", "]", "}", ",", "\"kernel_name\"", ":", "{", "\"start\"", ":", "-", "1", ",", "\"end\"", ":", "-", "1", "}", ",", "\"template\"", ":", "{", "\"start\"", ":", "-", "1", ",", "\"end\"", ":", "-", "1", "}", "}", "# Count for balancing template", "count", "=", "{", "\"<>\"", ":", "0", "}", "# Status for whether we are parsing a certain item.", "START", "=", "0", "AT_TEMPLATE", "=", "1", "AFTER_TEMPLATE", "=", "2", "AT_KERNEL_NAME", "=", "3", "status", "=", "START", "# Parse the string character by character", "for", "i", "in", "range", "(", "pos", "[", "\"kernel_launch\"", "]", "[", "\"start\"", "]", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "char", "=", "string", "[", "i", "]", "# Handle Templating Arguments", "if", "status", "==", "START", "or", "status", "==", "AT_TEMPLATE", ":", "if", "char", "==", "\">\"", ":", "if", "status", "==", "START", ":", "status", "=", "AT_TEMPLATE", "pos", "[", "\"template\"", "]", "[", "\"end\"", "]", "=", "i", "count", "[", "\"<>\"", "]", "+=", "1", "if", "char", "==", "\"<\"", ":", "count", "[", "\"<>\"", "]", "-=", "1", "if", "count", "[", "\"<>\"", "]", "==", "0", "and", "(", "status", "==", "AT_TEMPLATE", ")", ":", "pos", "[", "\"template\"", "]", "[", "\"start\"", "]", "=", "i", "status", "=", "AFTER_TEMPLATE", "# Handle Kernel Name", "if", "status", "!=", "AT_TEMPLATE", ":", "if", "string", "[", "i", "]", ".", "isalnum", "(", ")", "or", "string", "[", "i", "]", "in", "{", "'('", ",", "')'", ",", "'_'", ",", "':'", ",", "'#'", "}", ":", "if", "status", "!=", "AT_KERNEL_NAME", ":", "status", "=", "AT_KERNEL_NAME", "pos", "[", "\"kernel_name\"", "]", "[", "\"end\"", "]", "=", "i", "# Case: Kernel name starts the string.", "if", "i", "==", "0", ":", "pos", "[", "\"kernel_name\"", "]", "[", "\"start\"", "]", "=", "0", "# Finished", "return", "[", "(", "pos", "[", "\"kernel_name\"", "]", ")", ",", "(", "pos", "[", "\"template\"", "]", ")", ",", "(", "pos", "[", "\"kernel_launch\"", "]", ")", "]", "else", ":", "# Potential ending point if we're already traversing a kernel's name.", "if", "status", "==", "AT_KERNEL_NAME", ":", "pos", "[", "\"kernel_name\"", "]", "[", "\"start\"", "]", "=", "i", "# Finished", "return", "[", "(", "pos", "[", "\"kernel_name\"", "]", ")", ",", "(", "pos", "[", "\"template\"", "]", ")", ",", "(", "pos", "[", "\"kernel_launch\"", "]", ")", "]", "def", "find_kernel_bounds", "(", "string", ")", ":", "\"\"\"Finds the starting and ending points for all kernel launches in the string.\"\"\"", "kernel_end", "=", "0", "kernel_positions", "=", "[", "]", "# Continue until we cannot find any more kernels anymore.", "while", "string", ".", "find", "(", "\"<<<\"", ",", "kernel_end", ")", "!=", "-", "1", ":", "# Get kernel starting position (starting from the previous ending point)", "kernel_start", "=", "string", ".", "find", "(", "\"<<<\"", ",", "kernel_end", ")", "# Get kernel ending position (adjust end point past the >>>)", "kernel_end", "=", "string", ".", "find", "(", "\">>>\"", ",", "kernel_start", ")", "+", "3", "if", "kernel_end", "<=", "0", ":", "raise", "InputError", "(", "\"no kernel end found\"", ")", "# Add to list of traversed kernels", "kernel_positions", ".", "append", "(", "{", "\"start\"", ":", "kernel_start", ",", "\"end\"", ":", "kernel_end", ",", "\"group\"", ":", "string", "[", "kernel_start", ":", "kernel_end", "]", "}", ")", "return", "kernel_positions", "# Grab positional ranges of all kernel launchces", "get_kernel_positions", "=", "[", "k", "for", "k", "in", "find_kernel_bounds", "(", "string", ")", "]", "output_string", "=", "string", "# Replace each CUDA kernel with a HIP kernel.", "for", "kernel", "in", "get_kernel_positions", ":", "# Get kernel components", "params", "=", "grab_method_and_template", "(", "kernel", ")", "# Find parenthesis after kernel launch", "parenthesis", "=", "string", ".", "find", "(", "\"(\"", ",", "kernel", "[", "\"end\"", "]", ")", "# Extract cuda kernel", "cuda_kernel", "=", "string", "[", "params", "[", "0", "]", "[", "\"start\"", "]", ":", "parenthesis", "+", "1", "]", "kernel_string", "=", "string", "[", "kernel", "[", "'start'", "]", ":", "kernel", "[", "'end'", "]", "]", "cuda_kernel_dim3", "=", "add_dim3", "(", "kernel_string", ",", "cuda_kernel", ")", "# Keep number of kernel launch params consistent (grid dims, group dims, stream, dynamic shared size)", "num_klp", "=", "len", "(", "extract_arguments", "(", "0", ",", "kernel", "[", "\"group\"", "]", ".", "replace", "(", "\"<<<\"", ",", "\"(\"", ")", ".", "replace", "(", "\">>>\"", ",", "\")\"", ")", ")", ")", "hip_kernel", "=", "\"hipLaunchKernelGGL(\"", "+", "cuda_kernel_dim3", "[", "0", ":", "-", "1", "]", ".", "replace", "(", "\">>>\"", ",", "\", 0\"", "*", "(", "4", "-", "num_klp", ")", "+", "\">>>\"", ")", ".", "replace", "(", "\"<<<\"", ",", "\", \"", ")", ".", "replace", "(", "\">>>\"", ",", "\", \"", ")", "# Replace cuda kernel with hip kernel", "output_string", "=", "output_string", ".", "replace", "(", "cuda_kernel", ",", "hip_kernel", ")", "return", "output_string" ]
[ 140, 0 ]
[ 250, 24 ]
python
en
['en', 'en', 'en']
True
get_hip_file_path
(filepath)
Returns the new name of the hipified file
Returns the new name of the hipified file
def get_hip_file_path(filepath): """ Returns the new name of the hipified file """ dirpath, filename = os.path.split(filepath) root, ext = os.path.splitext(filename) # Concretely, we do the following: # # - If there is a directory component named "cuda", replace # it with "hip", AND # # - If the file name contains "CUDA", replace it with "HIP", AND # Furthermore, ALWAYS replace '.cu' with '.hip', because those files # contain CUDA kernels that needs to be hipified and processed with # hcc compiler # # This isn't set in stone; we might adjust this to support other # naming conventions. if ext == '.cu': ext = '.hip' orig_dirpath = dirpath dirpath = dirpath.replace('cuda', 'hip') root = root.replace('cuda', 'hip') root = root.replace('CUDA', 'HIP') return os.path.join(dirpath, root + ext)
[ "def", "get_hip_file_path", "(", "filepath", ")", ":", "dirpath", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "filepath", ")", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "# Concretely, we do the following:", "#", "# - If there is a directory component named \"cuda\", replace", "# it with \"hip\", AND", "#", "# - If the file name contains \"CUDA\", replace it with \"HIP\", AND", "# Furthermore, ALWAYS replace '.cu' with '.hip', because those files", "# contain CUDA kernels that needs to be hipified and processed with", "# hcc compiler", "#", "# This isn't set in stone; we might adjust this to support other", "# naming conventions.", "if", "ext", "==", "'.cu'", ":", "ext", "=", "'.hip'", "orig_dirpath", "=", "dirpath", "dirpath", "=", "dirpath", ".", "replace", "(", "'cuda'", ",", "'hip'", ")", "root", "=", "root", ".", "replace", "(", "'cuda'", ",", "'hip'", ")", "root", "=", "root", ".", "replace", "(", "'CUDA'", ",", "'HIP'", ")", "return", "os", ".", "path", ".", "join", "(", "dirpath", ",", "root", "+", "ext", ")" ]
[ 253, 0 ]
[ 281, 44 ]
python
en
['en', 'error', 'th']
False
preprocessor
(project_directory, output_directory, filepath)
Executes the CUDA -> HIP conversion on the specified file.
Executes the CUDA -> HIP conversion on the specified file.
def preprocessor(project_directory, output_directory, filepath): """ Executes the CUDA -> HIP conversion on the specified file. """ fin_path = os.path.join(project_directory, filepath) with open(fin_path, 'r') as fin: output_source = fin.read() fout_path = os.path.join(output_directory, get_hip_file_path(filepath)) assert(os.path.join(output_directory, fout_path) != os.path.join(project_directory, fin_path)) if not os.path.exists(os.path.dirname(fout_path)): os.makedirs(os.path.dirname(fout_path)) with open(fout_path, 'w') as fout: output_source = re_replace(output_source) # Perform Kernel Launch Replacements output_source = processKernelLaunches(output_source) fout.write(output_source)
[ "def", "preprocessor", "(", "project_directory", ",", "output_directory", ",", "filepath", ")", ":", "fin_path", "=", "os", ".", "path", ".", "join", "(", "project_directory", ",", "filepath", ")", "with", "open", "(", "fin_path", ",", "'r'", ")", "as", "fin", ":", "output_source", "=", "fin", ".", "read", "(", ")", "fout_path", "=", "os", ".", "path", ".", "join", "(", "output_directory", ",", "get_hip_file_path", "(", "filepath", ")", ")", "assert", "(", "os", ".", "path", ".", "join", "(", "output_directory", ",", "fout_path", ")", "!=", "os", ".", "path", ".", "join", "(", "project_directory", ",", "fin_path", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "fout_path", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "fout_path", ")", ")", "with", "open", "(", "fout_path", ",", "'w'", ")", "as", "fout", ":", "output_source", "=", "re_replace", "(", "output_source", ")", "# Perform Kernel Launch Replacements", "output_source", "=", "processKernelLaunches", "(", "output_source", ")", "fout", ".", "write", "(", "output_source", ")" ]
[ 362, 0 ]
[ 379, 33 ]
python
en
['en', 'en', 'en']
True
extract_arguments
(start, string)
Return the list of arguments in the upcoming function parameter closure. Example: string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' arguments (output): '[{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, {'start': 17, 'end': 19}, {'start': 20, 'end': 53}]'
Return the list of arguments in the upcoming function parameter closure. Example: string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' arguments (output): '[{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, {'start': 17, 'end': 19}, {'start': 20, 'end': 53}]'
def extract_arguments(start, string): """ Return the list of arguments in the upcoming function parameter closure. Example: string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))' arguments (output): '[{'start': 1, 'end': 7}, {'start': 8, 'end': 16}, {'start': 17, 'end': 19}, {'start': 20, 'end': 53}]' """ arguments = [] closures = { "<": 0, "(": 0 } current_position = start argument_start_pos = current_position + 1 # Search for final parenthesis while current_position < len(string): if string[current_position] == "(": closures["("] += 1 elif string[current_position] == ")": closures["("] -= 1 elif string[current_position] == "<": closures["<"] += 1 elif string[current_position] == ">" and string[current_position - 1] != "-" and closures["<"] > 0: closures["<"] -= 1 # Finished all arguments if closures["("] == 0 and closures["<"] == 0: # Add final argument arguments.append({"start": argument_start_pos, "end": current_position}) break # Finished current argument if closures["("] == 1 and closures["<"] == 0 and string[current_position] == ",": arguments.append({"start": argument_start_pos, "end": current_position}) argument_start_pos = current_position + 1 current_position += 1 return arguments
[ "def", "extract_arguments", "(", "start", ",", "string", ")", ":", "arguments", "=", "[", "]", "closures", "=", "{", "\"<\"", ":", "0", ",", "\"(\"", ":", "0", "}", "current_position", "=", "start", "argument_start_pos", "=", "current_position", "+", "1", "# Search for final parenthesis", "while", "current_position", "<", "len", "(", "string", ")", ":", "if", "string", "[", "current_position", "]", "==", "\"(\"", ":", "closures", "[", "\"(\"", "]", "+=", "1", "elif", "string", "[", "current_position", "]", "==", "\")\"", ":", "closures", "[", "\"(\"", "]", "-=", "1", "elif", "string", "[", "current_position", "]", "==", "\"<\"", ":", "closures", "[", "\"<\"", "]", "+=", "1", "elif", "string", "[", "current_position", "]", "==", "\">\"", "and", "string", "[", "current_position", "-", "1", "]", "!=", "\"-\"", "and", "closures", "[", "\"<\"", "]", ">", "0", ":", "closures", "[", "\"<\"", "]", "-=", "1", "# Finished all arguments", "if", "closures", "[", "\"(\"", "]", "==", "0", "and", "closures", "[", "\"<\"", "]", "==", "0", ":", "# Add final argument", "arguments", ".", "append", "(", "{", "\"start\"", ":", "argument_start_pos", ",", "\"end\"", ":", "current_position", "}", ")", "break", "# Finished current argument", "if", "closures", "[", "\"(\"", "]", "==", "1", "and", "closures", "[", "\"<\"", "]", "==", "0", "and", "string", "[", "current_position", "]", "==", "\",\"", ":", "arguments", ".", "append", "(", "{", "\"start\"", ":", "argument_start_pos", ",", "\"end\"", ":", "current_position", "}", ")", "argument_start_pos", "=", "current_position", "+", "1", "current_position", "+=", "1", "return", "arguments" ]
[ 382, 0 ]
[ 425, 20 ]
python
en
['en', 'en', 'en']
True
Parent.expectation
(cls, func)
Manages configuration and running of expectation objects.
Manages configuration and running of expectation objects.
def expectation(cls, func): """Manages configuration and running of expectation objects.""" @wraps(func) def wrapper(*args, **kwargs): # wrapper logic func(*args, **kwargs) return wrapper
[ "def", "expectation", "(", "cls", ",", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# wrapper logic", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
[ 105, 4 ]
[ 113, 22 ]
python
en
['en', 'en', 'en']
True
Parent.override_me
(self)
Parent method docstring Returns: Unattainable abiding satisfaction.
Parent method docstring Returns: Unattainable abiding satisfaction.
def override_me(self): """Parent method docstring Returns: Unattainable abiding satisfaction. """ raise NotImplementedError
[ "def", "override_me", "(", "self", ")", ":", "raise", "NotImplementedError" ]
[ 115, 4 ]
[ 120, 33 ]
python
en
['en', 'da', 'en']
True
Child.override_me
(self)
Child method docstring Returns: Real, instantiable, abiding satisfaction.
Child method docstring Returns: Real, instantiable, abiding satisfaction.
def override_me(self): """Child method docstring Returns: Real, instantiable, abiding satisfaction. """
[ "def", "override_me", "(", "self", ")", ":" ]
[ 130, 4 ]
[ 134, 11 ]
python
en
['en', 'da', 'en']
True
SimpleColumnSuffixDomainBuilder.__init__
( self, data_context: DataContext, batch_request: Optional[Union[BatchRequest, dict]] = None, column_name_suffixes: Optional[List[str]] = None, )
Args: data_context: DataContext batch_request: specified in DomainBuilder configuration to get Batch objects for domain computation.
Args: data_context: DataContext batch_request: specified in DomainBuilder configuration to get Batch objects for domain computation.
def __init__( self, data_context: DataContext, batch_request: Optional[Union[BatchRequest, dict]] = None, column_name_suffixes: Optional[List[str]] = None, ): """ Args: data_context: DataContext batch_request: specified in DomainBuilder configuration to get Batch objects for domain computation. """ super().__init__( data_context=data_context, batch_request=batch_request, ) if column_name_suffixes is None: column_name_suffixes = [] self._column_name_suffixes = column_name_suffixes
[ "def", "__init__", "(", "self", ",", "data_context", ":", "DataContext", ",", "batch_request", ":", "Optional", "[", "Union", "[", "BatchRequest", ",", "dict", "]", "]", "=", "None", ",", "column_name_suffixes", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", "data_context", "=", "data_context", ",", "batch_request", "=", "batch_request", ",", ")", "if", "column_name_suffixes", "is", "None", ":", "column_name_suffixes", "=", "[", "]", "self", ".", "_column_name_suffixes", "=", "column_name_suffixes" ]
[ 15, 4 ]
[ 34, 57 ]
python
en
['en', 'error', 'th']
False
SimpleColumnSuffixDomainBuilder._get_domains
( self, variables: Optional[ParameterContainer] = None, )
Find the column suffix for each column and return all domains matching the specified suffix.
Find the column suffix for each column and return all domains matching the specified suffix.
def _get_domains( self, variables: Optional[ParameterContainer] = None, ) -> List[Domain]: """ Find the column suffix for each column and return all domains matching the specified suffix. """ column_name_suffixes: Union[ str, Iterable, List[str] ] = self._column_name_suffixes if isinstance(column_name_suffixes, str): column_name_suffixes = [column_name_suffixes] else: if not isinstance(column_name_suffixes, (Iterable, List)): raise ValueError( "Unrecognized column_name_suffixes directive -- must be a list or a string." ) batch_id: str = self.get_batch_id(variables=variables) table_column_names: List[str] = self.get_validator( variables=variables ).get_metric( metric=MetricConfiguration( metric_name="table.columns", metric_domain_kwargs={ "batch_id": batch_id, }, metric_value_kwargs=None, metric_dependencies=None, ) ) candidate_column_names: List[str] = list( filter( lambda candidate_column_name: candidate_column_name.endswith( tuple(column_name_suffixes) ), table_column_names, ) ) column_name: str domains: List[Domain] = [ Domain( domain_type=MetricDomainTypes.COLUMN, domain_kwargs={ "column": column_name, }, ) for column_name in candidate_column_names ] return domains
[ "def", "_get_domains", "(", "self", ",", "variables", ":", "Optional", "[", "ParameterContainer", "]", "=", "None", ",", ")", "->", "List", "[", "Domain", "]", ":", "column_name_suffixes", ":", "Union", "[", "str", ",", "Iterable", ",", "List", "[", "str", "]", "]", "=", "self", ".", "_column_name_suffixes", "if", "isinstance", "(", "column_name_suffixes", ",", "str", ")", ":", "column_name_suffixes", "=", "[", "column_name_suffixes", "]", "else", ":", "if", "not", "isinstance", "(", "column_name_suffixes", ",", "(", "Iterable", ",", "List", ")", ")", ":", "raise", "ValueError", "(", "\"Unrecognized column_name_suffixes directive -- must be a list or a string.\"", ")", "batch_id", ":", "str", "=", "self", ".", "get_batch_id", "(", "variables", "=", "variables", ")", "table_column_names", ":", "List", "[", "str", "]", "=", "self", ".", "get_validator", "(", "variables", "=", "variables", ")", ".", "get_metric", "(", "metric", "=", "MetricConfiguration", "(", "metric_name", "=", "\"table.columns\"", ",", "metric_domain_kwargs", "=", "{", "\"batch_id\"", ":", "batch_id", ",", "}", ",", "metric_value_kwargs", "=", "None", ",", "metric_dependencies", "=", "None", ",", ")", ")", "candidate_column_names", ":", "List", "[", "str", "]", "=", "list", "(", "filter", "(", "lambda", "candidate_column_name", ":", "candidate_column_name", ".", "endswith", "(", "tuple", "(", "column_name_suffixes", ")", ")", ",", "table_column_names", ",", ")", ")", "column_name", ":", "str", "domains", ":", "List", "[", "Domain", "]", "=", "[", "Domain", "(", "domain_type", "=", "MetricDomainTypes", ".", "COLUMN", ",", "domain_kwargs", "=", "{", "\"column\"", ":", "column_name", ",", "}", ",", ")", "for", "column_name", "in", "candidate_column_names", "]", "return", "domains" ]
[ 36, 4 ]
[ 88, 22 ]
python
en
['en', 'error', 'th']
False
CheckpointNewNotebookRenderer._find_datasource_with_asset
(self)
Find a Datasource with a configured Asset. Useful to pre-populate a working sample Checkpoint for notebook users.
Find a Datasource with a configured Asset.
def _find_datasource_with_asset(self) -> Dict[str, str]: """ Find a Datasource with a configured Asset. Useful to pre-populate a working sample Checkpoint for notebook users. """ datasource_candidate = None for datasource_name, datasource in self.context.datasources.items(): for ( data_connector_name, data_connector, ) in datasource.data_connectors.items(): if len(data_connector.get_available_data_asset_names()) > 0: datasource_candidate = { "datasource_name": datasource_name, "data_connector_name": data_connector_name, "asset_name": list( data_connector.get_available_data_asset_names() )[0], } break return datasource_candidate
[ "def", "_find_datasource_with_asset", "(", "self", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "datasource_candidate", "=", "None", "for", "datasource_name", ",", "datasource", "in", "self", ".", "context", ".", "datasources", ".", "items", "(", ")", ":", "for", "(", "data_connector_name", ",", "data_connector", ",", ")", "in", "datasource", ".", "data_connectors", ".", "items", "(", ")", ":", "if", "len", "(", "data_connector", ".", "get_available_data_asset_names", "(", ")", ")", ">", "0", ":", "datasource_candidate", "=", "{", "\"datasource_name\"", ":", "datasource_name", ",", "\"data_connector_name\"", ":", "data_connector_name", ",", "\"asset_name\"", ":", "list", "(", "data_connector", ".", "get_available_data_asset_names", "(", ")", ")", "[", "0", "]", ",", "}", "break", "return", "datasource_candidate" ]
[ 14, 4 ]
[ 35, 35 ]
python
en
['en', 'error', 'th']
False
PublicTagsApiTests.test_login_required
(self)
Test that the login is required from retrieving tags
Test that the login is required from retrieving tags
def test_login_required(self): """Test that the login is required from retrieving tags""" res = self.client.get(TAGS_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
[ "def", "test_login_required", "(", "self", ")", ":", "res", "=", "self", ".", "client", ".", "get", "(", "TAGS_URL", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_401_UNAUTHORIZED", ")" ]
[ 21, 4 ]
[ 25, 71 ]
python
en
['en', 'en', 'en']
True
PrivateTagsApiTests.test_retrieve_tags
(self)
Test retrieving tags
Test retrieving tags
def test_retrieve_tags(self): """Test retrieving tags""" Tag.objects.create(user=self.user, name='Vegan') Tag.objects.create(user=self.user, name='Dessert') res = self.client.get(TAGS_URL) tags = Tag.objects.all().order_by('-name') serializer = TagSerializer(tags, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data)
[ "def", "test_retrieve_tags", "(", "self", ")", ":", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Vegan'", ")", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Dessert'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "TAGS_URL", ")", "tags", "=", "Tag", ".", "objects", ".", "all", "(", ")", ".", "order_by", "(", "'-name'", ")", "serializer", "=", "TagSerializer", "(", "tags", ",", "many", "=", "True", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_200_OK", ")", "self", ".", "assertEqual", "(", "res", ".", "data", ",", "serializer", ".", "data", ")" ]
[ 39, 4 ]
[ 49, 51 ]
python
en
['en', 'hmn', 'en']
True
PrivateTagsApiTests.test_tags_limited_to_user
(self)
Test that tags returned are for the authenticated user
Test that tags returned are for the authenticated user
def test_tags_limited_to_user(self): """Test that tags returned are for the authenticated user""" user2 = get_user_model().objects.create_user( '[email protected]', 'testpass' ) Tag.objects.create(user=user2, name='Fruity') tag = Tag.objects.create(user=self.user, name='Confort Food') res = self.client.get(TAGS_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(res.data), 1) self.assertEqual(res.data[0]['name'], tag.name)
[ "def", "test_tags_limited_to_user", "(", "self", ")", ":", "user2", "=", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "'[email protected]'", ",", "'testpass'", ")", "Tag", ".", "objects", ".", "create", "(", "user", "=", "user2", ",", "name", "=", "'Fruity'", ")", "tag", "=", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Confort Food'", ")", "res", "=", "self", ".", "client", ".", "get", "(", "TAGS_URL", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_200_OK", ")", "self", ".", "assertEqual", "(", "len", "(", "res", ".", "data", ")", ",", "1", ")", "self", ".", "assertEqual", "(", "res", ".", "data", "[", "0", "]", "[", "'name'", "]", ",", "tag", ".", "name", ")" ]
[ 51, 4 ]
[ 64, 55 ]
python
en
['en', 'en', 'en']
True
PrivateTagsApiTests.test_create_tags_successful
(self)
Test creating a new tag
Test creating a new tag
def test_create_tags_successful(self): """Test creating a new tag""" payload = {'name': 'Test tag'} self.client.post(TAGS_URL, payload) exists = Tag.objects.filter( user=self.user, name=payload['name'] ).exists() self.assertTrue(exists)
[ "def", "test_create_tags_successful", "(", "self", ")", ":", "payload", "=", "{", "'name'", ":", "'Test tag'", "}", "self", ".", "client", ".", "post", "(", "TAGS_URL", ",", "payload", ")", "exists", "=", "Tag", ".", "objects", ".", "filter", "(", "user", "=", "self", ".", "user", ",", "name", "=", "payload", "[", "'name'", "]", ")", ".", "exists", "(", ")", "self", ".", "assertTrue", "(", "exists", ")" ]
[ 66, 4 ]
[ 76, 31 ]
python
en
['en', 'en', 'en']
True
PrivateTagsApiTests.test_create_tags_invalid
(self)
Test creating a new tag with invalid payload
Test creating a new tag with invalid payload
def test_create_tags_invalid(self): """Test creating a new tag with invalid payload""" payload = {'name': ''} res = self.client.post(TAGS_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
[ "def", "test_create_tags_invalid", "(", "self", ")", ":", "payload", "=", "{", "'name'", ":", "''", "}", "res", "=", "self", ".", "client", ".", "post", "(", "TAGS_URL", ",", "payload", ")", "self", ".", "assertEqual", "(", "res", ".", "status_code", ",", "status", ".", "HTTP_400_BAD_REQUEST", ")" ]
[ 78, 4 ]
[ 83, 70 ]
python
en
['en', 'en', 'en']
True
PrivateTagsApiTests.test_retrieve_tags_assigned_to_recipes
(self)
Test filtering tags by those assigned to recipes
Test filtering tags by those assigned to recipes
def test_retrieve_tags_assigned_to_recipes(self): """Test filtering tags by those assigned to recipes""" tag1 = Tag.objects.create(user=self.user, name='Confort Food') tag2 = Tag.objects.create(user=self.user, name='Lunch') recipe = Recipe.objects.create( title='Coriander eggs on toast', time_minutes=10, price=5.00, user=self.user ) recipe.tags.add(tag1) res = self.client.get(TAGS_URL, {'assigned_only': 1}) serializer1 = TagSerializer(tag1) serializer2 = TagSerializer(tag2) self.assertIn(serializer1.data, res.data) self.assertNotIn(serializer2.data, res.data)
[ "def", "test_retrieve_tags_assigned_to_recipes", "(", "self", ")", ":", "tag1", "=", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Confort Food'", ")", "tag2", "=", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Lunch'", ")", "recipe", "=", "Recipe", ".", "objects", ".", "create", "(", "title", "=", "'Coriander eggs on toast'", ",", "time_minutes", "=", "10", ",", "price", "=", "5.00", ",", "user", "=", "self", ".", "user", ")", "recipe", ".", "tags", ".", "add", "(", "tag1", ")", "res", "=", "self", ".", "client", ".", "get", "(", "TAGS_URL", ",", "{", "'assigned_only'", ":", "1", "}", ")", "serializer1", "=", "TagSerializer", "(", "tag1", ")", "serializer2", "=", "TagSerializer", "(", "tag2", ")", "self", ".", "assertIn", "(", "serializer1", ".", "data", ",", "res", ".", "data", ")", "self", ".", "assertNotIn", "(", "serializer2", ".", "data", ",", "res", ".", "data", ")" ]
[ 85, 4 ]
[ 102, 52 ]
python
en
['en', 'en', 'en']
True
PrivateTagsApiTests.test_retrieve_tags_assigned_unique
(self)
Test filtering tags by those assigned unique items
Test filtering tags by those assigned unique items
def test_retrieve_tags_assigned_unique(self): """Test filtering tags by those assigned unique items""" tag = Tag.objects.create(user=self.user, name='Confort Food') Tag.objects.create(user=self.user, name='Lunch') recipe1 = Recipe.objects.create( title='Coriander eggs on toast', time_minutes=10, price=5.00, user=self.user ) recipe2 = Recipe.objects.create( title='Porridge', time_minutes=4, price=3.00, user=self.user ) recipe1.tags.add(tag) recipe2.tags.add(tag) res = self.client.get(TAGS_URL, {'assigned_only': 1}) self.assertEqual(len(res.data), 1)
[ "def", "test_retrieve_tags_assigned_unique", "(", "self", ")", ":", "tag", "=", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Confort Food'", ")", "Tag", ".", "objects", ".", "create", "(", "user", "=", "self", ".", "user", ",", "name", "=", "'Lunch'", ")", "recipe1", "=", "Recipe", ".", "objects", ".", "create", "(", "title", "=", "'Coriander eggs on toast'", ",", "time_minutes", "=", "10", ",", "price", "=", "5.00", ",", "user", "=", "self", ".", "user", ")", "recipe2", "=", "Recipe", ".", "objects", ".", "create", "(", "title", "=", "'Porridge'", ",", "time_minutes", "=", "4", ",", "price", "=", "3.00", ",", "user", "=", "self", ".", "user", ")", "recipe1", ".", "tags", ".", "add", "(", "tag", ")", "recipe2", ".", "tags", ".", "add", "(", "tag", ")", "res", "=", "self", ".", "client", ".", "get", "(", "TAGS_URL", ",", "{", "'assigned_only'", ":", "1", "}", ")", "self", ".", "assertEqual", "(", "len", "(", "res", ".", "data", ")", ",", "1", ")" ]
[ 104, 4 ]
[ 125, 42 ]
python
en
['en', 'en', 'en']
True
test_docs_clean_and_build_raises_helpful_errors
( mock_emit, mock_webbrowser, invocation, expected_error, expected_usage_event_begin, expected_usage_event_end, caplog, monkeypatch, context_with_site_built, )
Test helpful error messages for docs build and docs clean - invalid site names are specified via --site-name For docs clean: - invalid combinations of the --all and --site-name flags are used
Test helpful error messages for docs build and docs clean - invalid site names are specified via --site-name
def test_docs_clean_and_build_raises_helpful_errors( mock_emit, mock_webbrowser, invocation, expected_error, expected_usage_event_begin, expected_usage_event_end, caplog, monkeypatch, context_with_site_built, ): """ Test helpful error messages for docs build and docs clean - invalid site names are specified via --site-name For docs clean: - invalid combinations of the --all and --site-name flags are used """ context = context_with_site_built runner = CliRunner(mix_stderr=True) monkeypatch.chdir(os.path.dirname(context.root_directory)) result = runner.invoke( cli, invocation, catch_exceptions=False, ) stdout = result.stdout assert result.exit_code == 1 assert expected_error in stdout assert "Cleaned data docs" not in stdout assert mock_emit.call_count == 3 assert mock_emit.call_args_list == [ mock.call( {"event_payload": {}, "event": "data_context.__init__", "success": True} ), mock.call( { "event": expected_usage_event_begin, "event_payload": {"api_version": "v3"}, "success": True, } ), mock.call( { "event": expected_usage_event_end, "event_payload": {"api_version": "v3"}, "success": False, } ), ] assert_no_logging_messages_or_tracebacks( my_caplog=caplog, click_result=result, )
[ "def", "test_docs_clean_and_build_raises_helpful_errors", "(", "mock_emit", ",", "mock_webbrowser", ",", "invocation", ",", "expected_error", ",", "expected_usage_event_begin", ",", "expected_usage_event_end", ",", "caplog", ",", "monkeypatch", ",", "context_with_site_built", ",", ")", ":", "context", "=", "context_with_site_built", "runner", "=", "CliRunner", "(", "mix_stderr", "=", "True", ")", "monkeypatch", ".", "chdir", "(", "os", ".", "path", ".", "dirname", "(", "context", ".", "root_directory", ")", ")", "result", "=", "runner", ".", "invoke", "(", "cli", ",", "invocation", ",", "catch_exceptions", "=", "False", ",", ")", "stdout", "=", "result", ".", "stdout", "assert", "result", ".", "exit_code", "==", "1", "assert", "expected_error", "in", "stdout", "assert", "\"Cleaned data docs\"", "not", "in", "stdout", "assert", "mock_emit", ".", "call_count", "==", "3", "assert", "mock_emit", ".", "call_args_list", "==", "[", "mock", ".", "call", "(", "{", "\"event_payload\"", ":", "{", "}", ",", "\"event\"", ":", "\"data_context.__init__\"", ",", "\"success\"", ":", "True", "}", ")", ",", "mock", ".", "call", "(", "{", "\"event\"", ":", "expected_usage_event_begin", ",", "\"event_payload\"", ":", "{", "\"api_version\"", ":", "\"v3\"", "}", ",", "\"success\"", ":", "True", ",", "}", ")", ",", "mock", ".", "call", "(", "{", "\"event\"", ":", "expected_usage_event_end", ",", "\"event_payload\"", ":", "{", "\"api_version\"", ":", "\"v3\"", "}", ",", "\"success\"", ":", "False", ",", "}", ")", ",", "]", "assert_no_logging_messages_or_tracebacks", "(", "my_caplog", "=", "caplog", ",", "click_result", "=", "result", ",", ")" ]
[ 549, 0 ]
[ 603, 5 ]
python
en
['en', 'error', 'th']
False
DatabaseManager.__init__
(self, database_env='test', conf_creds=None)
Create a connection to the MySQL DB.
Create a connection to the MySQL DB.
def __init__(self, database_env='test', conf_creds=None): """ Create a connection to the MySQL DB. """ import pymysql db_server = settings.DB_HOST db_port = settings.DB_PORT db_user = settings.DB_USERNAME db_pass = settings.DB_PASSWORD db_schema = settings.DB_SCHEMA if hasattr(sb_config, "settings_file") and sb_config.settings_file: override = settings_parser.set_settings(sb_config.settings_file) if "DB_HOST" in override.keys(): db_server = override['DB_HOST'] if "DB_PORT" in override.keys(): db_port = override['DB_PORT'] if "DB_USERNAME" in override.keys(): db_user = override['DB_USERNAME'] if "DB_PASSWORD" in override.keys(): db_pass = override['DB_PASSWORD'] if "DB_SCHEMA" in override.keys(): db_schema = override['DB_SCHEMA'] retry_count = 3 backoff = 1.2 # Time to wait (in seconds) between retries. count = 0 while count < retry_count: try: self.conn = pymysql.connect(host=db_server, port=db_port, user=db_user, passwd=db_pass, db=db_schema) self.conn.autocommit(True) self.cursor = self.conn.cursor() return except Exception: time.sleep(backoff) count = count + 1 if retry_count == 3: raise Exception("Unable to connect to Database after 3 retries.")
[ "def", "__init__", "(", "self", ",", "database_env", "=", "'test'", ",", "conf_creds", "=", "None", ")", ":", "import", "pymysql", "db_server", "=", "settings", ".", "DB_HOST", "db_port", "=", "settings", ".", "DB_PORT", "db_user", "=", "settings", ".", "DB_USERNAME", "db_pass", "=", "settings", ".", "DB_PASSWORD", "db_schema", "=", "settings", ".", "DB_SCHEMA", "if", "hasattr", "(", "sb_config", ",", "\"settings_file\"", ")", "and", "sb_config", ".", "settings_file", ":", "override", "=", "settings_parser", ".", "set_settings", "(", "sb_config", ".", "settings_file", ")", "if", "\"DB_HOST\"", "in", "override", ".", "keys", "(", ")", ":", "db_server", "=", "override", "[", "'DB_HOST'", "]", "if", "\"DB_PORT\"", "in", "override", ".", "keys", "(", ")", ":", "db_port", "=", "override", "[", "'DB_PORT'", "]", "if", "\"DB_USERNAME\"", "in", "override", ".", "keys", "(", ")", ":", "db_user", "=", "override", "[", "'DB_USERNAME'", "]", "if", "\"DB_PASSWORD\"", "in", "override", ".", "keys", "(", ")", ":", "db_pass", "=", "override", "[", "'DB_PASSWORD'", "]", "if", "\"DB_SCHEMA\"", "in", "override", ".", "keys", "(", ")", ":", "db_schema", "=", "override", "[", "'DB_SCHEMA'", "]", "retry_count", "=", "3", "backoff", "=", "1.2", "# Time to wait (in seconds) between retries.", "count", "=", "0", "while", "count", "<", "retry_count", ":", "try", ":", "self", ".", "conn", "=", "pymysql", ".", "connect", "(", "host", "=", "db_server", ",", "port", "=", "db_port", ",", "user", "=", "db_user", ",", "passwd", "=", "db_pass", ",", "db", "=", "db_schema", ")", "self", ".", "conn", ".", "autocommit", "(", "True", ")", "self", ".", "cursor", "=", "self", ".", "conn", ".", "cursor", "(", ")", "return", "except", "Exception", ":", "time", ".", "sleep", "(", "backoff", ")", "count", "=", "count", "+", "1", "if", "retry_count", "==", "3", ":", "raise", "Exception", "(", "\"Unable to connect to Database after 3 retries.\"", ")" ]
[ 15, 4 ]
[ 54, 77 ]
python
en
['en', 'error', 'th']
False
DatabaseManager.query_fetch_all
(self, query, values)
Executes a db query, gets all the values, and closes the connection.
Executes a db query, gets all the values, and closes the connection.
def query_fetch_all(self, query, values): """ Executes a db query, gets all the values, and closes the connection. """ self.cursor.execute(query, values) retval = self.cursor.fetchall() self.__close_db() return retval
[ "def", "query_fetch_all", "(", "self", ",", "query", ",", "values", ")", ":", "self", ".", "cursor", ".", "execute", "(", "query", ",", "values", ")", "retval", "=", "self", ".", "cursor", ".", "fetchall", "(", ")", "self", ".", "__close_db", "(", ")", "return", "retval" ]
[ 56, 4 ]
[ 63, 21 ]
python
en
['en', 'error', 'th']
False
DatabaseManager.query_fetch_one
(self, query, values)
Executes a db query, gets the first value, and closes the connection.
Executes a db query, gets the first value, and closes the connection.
def query_fetch_one(self, query, values): """ Executes a db query, gets the first value, and closes the connection. """ self.cursor.execute(query, values) retval = self.cursor.fetchone() self.__close_db() return retval
[ "def", "query_fetch_one", "(", "self", ",", "query", ",", "values", ")", ":", "self", ".", "cursor", ".", "execute", "(", "query", ",", "values", ")", "retval", "=", "self", ".", "cursor", ".", "fetchone", "(", ")", "self", ".", "__close_db", "(", ")", "return", "retval" ]
[ 65, 4 ]
[ 72, 21 ]
python
en
['en', 'error', 'th']
False
DatabaseManager.execute_query
(self, query, values)
Executes a query to the test_db and closes the connection afterwards.
Executes a query to the test_db and closes the connection afterwards.
def execute_query(self, query, values): """ Executes a query to the test_db and closes the connection afterwards. """ retval = self.cursor.execute(query, values) self.__close_db() return retval
[ "def", "execute_query", "(", "self", ",", "query", ",", "values", ")", ":", "retval", "=", "self", ".", "cursor", ".", "execute", "(", "query", ",", "values", ")", "self", ".", "__close_db", "(", ")", "return", "retval" ]
[ 74, 4 ]
[ 80, 21 ]
python
en
['en', 'error', 'th']
False
find_best_lexer
(text, min_confidence=0.85)
Like the built in pygments guess_lexer, except has a minimum confidence level. If that is not met, it falls back to plain text to avoid bad highlighting. :returns: Lexer instance
Like the built in pygments guess_lexer, except has a minimum confidence level. If that is not met, it falls back to plain text to avoid bad highlighting.
def find_best_lexer(text, min_confidence=0.85): """ Like the built in pygments guess_lexer, except has a minimum confidence level. If that is not met, it falls back to plain text to avoid bad highlighting. :returns: Lexer instance """ current_best_confidence = 0.0 current_best_lexer = None for lexer in _iter_lexerclasses(): confidence = lexer.analyse_text(text) if confidence == 1.0: return lexer() elif confidence > current_best_confidence: current_best_confidence = confidence current_best_lexer = lexer if current_best_confidence >= min_confidence: return current_best_lexer() else: return TextLexer()
[ "def", "find_best_lexer", "(", "text", ",", "min_confidence", "=", "0.85", ")", ":", "current_best_confidence", "=", "0.0", "current_best_lexer", "=", "None", "for", "lexer", "in", "_iter_lexerclasses", "(", ")", ":", "confidence", "=", "lexer", ".", "analyse_text", "(", "text", ")", "if", "confidence", "==", "1.0", ":", "return", "lexer", "(", ")", "elif", "confidence", ">", "current_best_confidence", ":", "current_best_confidence", "=", "confidence", "current_best_lexer", "=", "lexer", "if", "current_best_confidence", ">=", "min_confidence", ":", "return", "current_best_lexer", "(", ")", "else", ":", "return", "TextLexer", "(", ")" ]
[ 71, 0 ]
[ 92, 26 ]
python
en
['en', 'error', 'th']
False
WheelDistribution.get_pkg_resources_distribution
(self)
Loads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement.
Loads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement.
def get_pkg_resources_distribution(self) -> Distribution: """Loads the metadata from the wheel file into memory and returns a Distribution that uses it, not relying on the wheel file or requirement. """ # Set as part of preparation during download. assert self.req.local_file_path # Wheels are never unnamed. assert self.req.name with ZipFile(self.req.local_file_path, allowZip64=True) as z: return pkg_resources_distribution_for_wheel( z, self.req.name, self.req.local_file_path )
[ "def", "get_pkg_resources_distribution", "(", "self", ")", "->", "Distribution", ":", "# Set as part of preparation during download.", "assert", "self", ".", "req", ".", "local_file_path", "# Wheels are never unnamed.", "assert", "self", ".", "req", ".", "name", "with", "ZipFile", "(", "self", ".", "req", ".", "local_file_path", ",", "allowZip64", "=", "True", ")", "as", "z", ":", "return", "pkg_resources_distribution_for_wheel", "(", "z", ",", "self", ".", "req", ".", "name", ",", "self", ".", "req", ".", "local_file_path", ")" ]
[ 15, 4 ]
[ 28, 13 ]
python
en
['en', 'en', 'en']
True
_length_hint
(obj)
Returns the length hint of an object.
Returns the length hint of an object.
def _length_hint(obj): """Returns the length hint of an object.""" try: return len(obj) except (AttributeError, TypeError): try: get_hint = type(obj).__length_hint__ except AttributeError: return None try: hint = get_hint(obj) except TypeError: return None if hint is NotImplemented or \ not isinstance(hint, int_types) or \ hint < 0: return None return hint
[ "def", "_length_hint", "(", "obj", ")", ":", "try", ":", "return", "len", "(", "obj", ")", "except", "(", "AttributeError", ",", "TypeError", ")", ":", "try", ":", "get_hint", "=", "type", "(", "obj", ")", ".", "__length_hint__", "except", "AttributeError", ":", "return", "None", "try", ":", "hint", "=", "get_hint", "(", "obj", ")", "except", "TypeError", ":", "return", "None", "if", "hint", "is", "NotImplemented", "or", "not", "isinstance", "(", "hint", ",", "int_types", ")", "or", "hint", "<", "0", ":", "return", "None", "return", "hint" ]
[ 33, 0 ]
[ 50, 19 ]
python
en
['en', 'en', 'en']
True
pager
(generator, color=None)
Decide what method to use for paging through text.
Decide what method to use for paging through text.
def pager(generator, color=None): """Decide what method to use for paging through text.""" stdout = _default_text_stdout() if not isatty(sys.stdin) or not isatty(stdout): return _nullpager(stdout, generator, color) pager_cmd = (os.environ.get('PAGER', None) or '').strip() if pager_cmd: if WIN: return _tempfilepager(generator, pager_cmd, color) return _pipepager(generator, pager_cmd, color) if os.environ.get('TERM') in ('dumb', 'emacs'): return _nullpager(stdout, generator, color) if WIN or sys.platform.startswith('os2'): return _tempfilepager(generator, 'more <', color) if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0: return _pipepager(generator, 'less', color) import tempfile fd, filename = tempfile.mkstemp() os.close(fd) try: if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0: return _pipepager(generator, 'more', color) return _nullpager(stdout, generator, color) finally: os.unlink(filename)
[ "def", "pager", "(", "generator", ",", "color", "=", "None", ")", ":", "stdout", "=", "_default_text_stdout", "(", ")", "if", "not", "isatty", "(", "sys", ".", "stdin", ")", "or", "not", "isatty", "(", "stdout", ")", ":", "return", "_nullpager", "(", "stdout", ",", "generator", ",", "color", ")", "pager_cmd", "=", "(", "os", ".", "environ", ".", "get", "(", "'PAGER'", ",", "None", ")", "or", "''", ")", ".", "strip", "(", ")", "if", "pager_cmd", ":", "if", "WIN", ":", "return", "_tempfilepager", "(", "generator", ",", "pager_cmd", ",", "color", ")", "return", "_pipepager", "(", "generator", ",", "pager_cmd", ",", "color", ")", "if", "os", ".", "environ", ".", "get", "(", "'TERM'", ")", "in", "(", "'dumb'", ",", "'emacs'", ")", ":", "return", "_nullpager", "(", "stdout", ",", "generator", ",", "color", ")", "if", "WIN", "or", "sys", ".", "platform", ".", "startswith", "(", "'os2'", ")", ":", "return", "_tempfilepager", "(", "generator", ",", "'more <'", ",", "color", ")", "if", "hasattr", "(", "os", ",", "'system'", ")", "and", "os", ".", "system", "(", "'(less) 2>/dev/null'", ")", "==", "0", ":", "return", "_pipepager", "(", "generator", ",", "'less'", ",", "color", ")", "import", "tempfile", "fd", ",", "filename", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "fd", ")", "try", ":", "if", "hasattr", "(", "os", ",", "'system'", ")", "and", "os", ".", "system", "(", "'more \"%s\"'", "%", "filename", ")", "==", "0", ":", "return", "_pipepager", "(", "generator", ",", "'more'", ",", "color", ")", "return", "_nullpager", "(", "stdout", ",", "generator", ",", "color", ")", "finally", ":", "os", ".", "unlink", "(", "filename", ")" ]
[ 292, 0 ]
[ 317, 27 ]
python
en
['en', 'en', 'en']
True
_pipepager
(generator, cmd, color)
Page through text by feeding it to another program. Invoking a pager through this might support colors.
Page through text by feeding it to another program. Invoking a pager through this might support colors.
def _pipepager(generator, cmd, color): """Page through text by feeding it to another program. Invoking a pager through this might support colors. """ import subprocess env = dict(os.environ) # If we're piping to less we might support colors under the # condition that cmd_detail = cmd.rsplit('/', 1)[-1].split() if color is None and cmd_detail[0] == 'less': less_flags = os.environ.get('LESS', '') + ' '.join(cmd_detail[1:]) if not less_flags: env['LESS'] = '-R' color = True elif 'r' in less_flags or 'R' in less_flags: color = True c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env) encoding = get_best_encoding(c.stdin) try: for text in generator: if not color: text = strip_ansi(text) c.stdin.write(text.encode(encoding, 'replace')) except (IOError, KeyboardInterrupt): pass else: c.stdin.close() # Less doesn't respect ^C, but catches it for its own UI purposes (aborting # search or other commands inside less). # # That means when the user hits ^C, the parent process (click) terminates, # but less is still alive, paging the output and messing up the terminal. # # If the user wants to make the pager exit on ^C, they should set # `LESS='-K'`. It's not our decision to make. while True: try: c.wait() except KeyboardInterrupt: pass else: break
[ "def", "_pipepager", "(", "generator", ",", "cmd", ",", "color", ")", ":", "import", "subprocess", "env", "=", "dict", "(", "os", ".", "environ", ")", "# If we're piping to less we might support colors under the", "# condition that", "cmd_detail", "=", "cmd", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]", ".", "split", "(", ")", "if", "color", "is", "None", "and", "cmd_detail", "[", "0", "]", "==", "'less'", ":", "less_flags", "=", "os", ".", "environ", ".", "get", "(", "'LESS'", ",", "''", ")", "+", "' '", ".", "join", "(", "cmd_detail", "[", "1", ":", "]", ")", "if", "not", "less_flags", ":", "env", "[", "'LESS'", "]", "=", "'-R'", "color", "=", "True", "elif", "'r'", "in", "less_flags", "or", "'R'", "in", "less_flags", ":", "color", "=", "True", "c", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "env", "=", "env", ")", "encoding", "=", "get_best_encoding", "(", "c", ".", "stdin", ")", "try", ":", "for", "text", "in", "generator", ":", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "c", ".", "stdin", ".", "write", "(", "text", ".", "encode", "(", "encoding", ",", "'replace'", ")", ")", "except", "(", "IOError", ",", "KeyboardInterrupt", ")", ":", "pass", "else", ":", "c", ".", "stdin", ".", "close", "(", ")", "# Less doesn't respect ^C, but catches it for its own UI purposes (aborting", "# search or other commands inside less).", "#", "# That means when the user hits ^C, the parent process (click) terminates,", "# but less is still alive, paging the output and messing up the terminal.", "#", "# If the user wants to make the pager exit on ^C, they should set", "# `LESS='-K'`. It's not our decision to make.", "while", "True", ":", "try", ":", "c", ".", "wait", "(", ")", "except", "KeyboardInterrupt", ":", "pass", "else", ":", "break" ]
[ 320, 0 ]
[ 366, 17 ]
python
en
['en', 'en', 'en']
True
_tempfilepager
(generator, cmd, color)
Page through text by invoking a program on a temporary file.
Page through text by invoking a program on a temporary file.
def _tempfilepager(generator, cmd, color): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(text) encoding = get_best_encoding(sys.stdout) with open_stream(filename, 'wb')[0] as f: f.write(text.encode(encoding)) try: os.system(cmd + ' "' + filename + '"') finally: os.unlink(filename)
[ "def", "_tempfilepager", "(", "generator", ",", "cmd", ",", "color", ")", ":", "import", "tempfile", "filename", "=", "tempfile", ".", "mktemp", "(", ")", "# TODO: This never terminates if the passed generator never terminates.", "text", "=", "\"\"", ".", "join", "(", "generator", ")", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "encoding", "=", "get_best_encoding", "(", "sys", ".", "stdout", ")", "with", "open_stream", "(", "filename", ",", "'wb'", ")", "[", "0", "]", "as", "f", ":", "f", ".", "write", "(", "text", ".", "encode", "(", "encoding", ")", ")", "try", ":", "os", ".", "system", "(", "cmd", "+", "' \"'", "+", "filename", "+", "'\"'", ")", "finally", ":", "os", ".", "unlink", "(", "filename", ")" ]
[ 369, 0 ]
[ 383, 27 ]
python
en
['en', 'en', 'en']
True
_nullpager
(stream, generator, color)
Simply print unformatted text. This is the ultimate fallback.
Simply print unformatted text. This is the ultimate fallback.
def _nullpager(stream, generator, color): """Simply print unformatted text. This is the ultimate fallback.""" for text in generator: if not color: text = strip_ansi(text) stream.write(text)
[ "def", "_nullpager", "(", "stream", ",", "generator", ",", "color", ")", ":", "for", "text", "in", "generator", ":", "if", "not", "color", ":", "text", "=", "strip_ansi", "(", "text", ")", "stream", ".", "write", "(", "text", ")" ]
[ 386, 0 ]
[ 391, 26 ]
python
en
['en', 'en', 'en']
True
ProgressBar.generator
(self)
Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns.
Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns.
def generator(self): """ Returns a generator which yields the items added to the bar during construction, and updates the progress bar *after* the yielded block returns. """ if not self.entered: raise RuntimeError('You need to use progress bars in a with block.') if self.is_hidden: for rv in self.iter: yield rv else: for rv in self.iter: self.current_item = rv yield rv self.update(1) self.finish() self.render_progress()
[ "def", "generator", "(", "self", ")", ":", "if", "not", "self", ".", "entered", ":", "raise", "RuntimeError", "(", "'You need to use progress bars in a with block.'", ")", "if", "self", ".", "is_hidden", ":", "for", "rv", "in", "self", ".", "iter", ":", "yield", "rv", "else", ":", "for", "rv", "in", "self", ".", "iter", ":", "self", ".", "current_item", "=", "rv", "yield", "rv", "self", ".", "update", "(", "1", ")", "self", ".", "finish", "(", ")", "self", ".", "render_progress", "(", ")" ]
[ 271, 4 ]
[ 289, 34 ]
python
en
['en', 'error', 'th']
False
Cache.get
(self, url)
Gets the content from the memcache with a given key. Args: url: string, the key for the cache. Returns: object, the value in the cache for the given key, or None if the key is not in the cache.
Gets the content from the memcache with a given key.
def get(self, url): """Gets the content from the memcache with a given key. Args: url: string, the key for the cache. Returns: object, the value in the cache for the given key, or None if the key is not in the cache. """ raise NotImplementedError()
[ "def", "get", "(", "self", ",", "url", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 24, 2 ]
[ 34, 31 ]
python
en
['en', 'en', 'en']
True
Cache.set
(self, url, content)
Sets the given key and content in the cache. Args: url: string, the key for the cache. content: string, the discovery document.
Sets the given key and content in the cache.
def set(self, url, content): """Sets the given key and content in the cache. Args: url: string, the key for the cache. content: string, the discovery document. """ raise NotImplementedError()
[ "def", "set", "(", "self", ",", "url", ",", "content", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 37, 2 ]
[ 44, 31 ]
python
en
['en', 'en', 'en']
True
Point.__init__
(self, x=None, y=None, z=None, srid=None)
The Point object may be initialized with either a tuple, or individual parameters. For example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters
The Point object may be initialized with either a tuple, or individual parameters.
def __init__(self, x=None, y=None, z=None, srid=None): """ The Point object may be initialized with either a tuple, or individual parameters. For example: >>> p = Point((5, 23)) # 2D point, passed in as a tuple >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters """ if x is None: coords = [] elif isinstance(x, (tuple, list)): # Here a tuple or list was passed in under the `x` parameter. coords = x elif isinstance(x, (float, int)) and isinstance(y, (float, int)): # Here X, Y, and (optionally) Z were passed in individually, as parameters. if isinstance(z, (float, int)): coords = [x, y, z] else: coords = [x, y] else: raise TypeError('Invalid parameters given for Point initialization.') point = self._create_point(len(coords), coords) # Initializing using the address returned from the GEOS # createPoint factory. super().__init__(point, srid=srid)
[ "def", "__init__", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "z", "=", "None", ",", "srid", "=", "None", ")", ":", "if", "x", "is", "None", ":", "coords", "=", "[", "]", "elif", "isinstance", "(", "x", ",", "(", "tuple", ",", "list", ")", ")", ":", "# Here a tuple or list was passed in under the `x` parameter.", "coords", "=", "x", "elif", "isinstance", "(", "x", ",", "(", "float", ",", "int", ")", ")", "and", "isinstance", "(", "y", ",", "(", "float", ",", "int", ")", ")", ":", "# Here X, Y, and (optionally) Z were passed in individually, as parameters.", "if", "isinstance", "(", "z", ",", "(", "float", ",", "int", ")", ")", ":", "coords", "=", "[", "x", ",", "y", ",", "z", "]", "else", ":", "coords", "=", "[", "x", ",", "y", "]", "else", ":", "raise", "TypeError", "(", "'Invalid parameters given for Point initialization.'", ")", "point", "=", "self", ".", "_create_point", "(", "len", "(", "coords", ")", ",", "coords", ")", "# Initializing using the address returned from the GEOS", "# createPoint factory.", "super", "(", ")", ".", "__init__", "(", "point", ",", "srid", "=", "srid", ")" ]
[ 13, 4 ]
[ 40, 42 ]
python
en
['en', 'error', 'th']
False
Point._create_point
(cls, ndim, coords)
Create a coordinate sequence, set X, Y, [Z], and create point
Create a coordinate sequence, set X, Y, [Z], and create point
def _create_point(cls, ndim, coords): """ Create a coordinate sequence, set X, Y, [Z], and create point """ if not ndim: return capi.create_point(None) if ndim < 2 or ndim > 3: raise TypeError('Invalid point dimension: %s' % ndim) cs = capi.create_cs(c_uint(1), c_uint(ndim)) i = iter(coords) capi.cs_setx(cs, 0, next(i)) capi.cs_sety(cs, 0, next(i)) if ndim == 3: capi.cs_setz(cs, 0, next(i)) return capi.create_point(cs)
[ "def", "_create_point", "(", "cls", ",", "ndim", ",", "coords", ")", ":", "if", "not", "ndim", ":", "return", "capi", ".", "create_point", "(", "None", ")", "if", "ndim", "<", "2", "or", "ndim", ">", "3", ":", "raise", "TypeError", "(", "'Invalid point dimension: %s'", "%", "ndim", ")", "cs", "=", "capi", ".", "create_cs", "(", "c_uint", "(", "1", ")", ",", "c_uint", "(", "ndim", ")", ")", "i", "=", "iter", "(", "coords", ")", "capi", ".", "cs_setx", "(", "cs", ",", "0", ",", "next", "(", "i", ")", ")", "capi", ".", "cs_sety", "(", "cs", ",", "0", ",", "next", "(", "i", ")", ")", "if", "ndim", "==", "3", ":", "capi", ".", "cs_setz", "(", "cs", ",", "0", ",", "next", "(", "i", ")", ")", "return", "capi", ".", "create_point", "(", "cs", ")" ]
[ 56, 4 ]
[ 73, 36 ]
python
en
['en', 'error', 'th']
False
Point.__iter__
(self)
Iterate over coordinates of this Point.
Iterate over coordinates of this Point.
def __iter__(self): "Iterate over coordinates of this Point." for i in range(len(self)): yield self[i]
[ "def", "__iter__", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", ":", "yield", "self", "[", "i", "]" ]
[ 91, 4 ]
[ 94, 25 ]
python
en
['en', 'en', 'en']
True
Point.__len__
(self)
Return the number of dimensions for this Point (either 0, 2 or 3).
Return the number of dimensions for this Point (either 0, 2 or 3).
def __len__(self): "Return the number of dimensions for this Point (either 0, 2 or 3)." if self.empty: return 0 if self.hasz: return 3 else: return 2
[ "def", "__len__", "(", "self", ")", ":", "if", "self", ".", "empty", ":", "return", "0", "if", "self", ".", "hasz", ":", "return", "3", "else", ":", "return", "2" ]
[ 96, 4 ]
[ 103, 20 ]
python
en
['en', 'en', 'en']
True
Point.x
(self)
Return the X component of the Point.
Return the X component of the Point.
def x(self): "Return the X component of the Point." return self._cs.getOrdinate(0, 0)
[ "def", "x", "(", "self", ")", ":", "return", "self", ".", "_cs", ".", "getOrdinate", "(", "0", ",", "0", ")" ]
[ 116, 4 ]
[ 118, 41 ]
python
en
['en', 'en', 'en']
True
Point.x
(self, value)
Set the X component of the Point.
Set the X component of the Point.
def x(self, value): "Set the X component of the Point." self._cs.setOrdinate(0, 0, value)
[ "def", "x", "(", "self", ",", "value", ")", ":", "self", ".", "_cs", ".", "setOrdinate", "(", "0", ",", "0", ",", "value", ")" ]
[ 121, 4 ]
[ 123, 41 ]
python
en
['en', 'en', 'en']
True
Point.y
(self)
Return the Y component of the Point.
Return the Y component of the Point.
def y(self): "Return the Y component of the Point." return self._cs.getOrdinate(1, 0)
[ "def", "y", "(", "self", ")", ":", "return", "self", ".", "_cs", ".", "getOrdinate", "(", "1", ",", "0", ")" ]
[ 126, 4 ]
[ 128, 41 ]
python
en
['en', 'en', 'en']
True
Point.y
(self, value)
Set the Y component of the Point.
Set the Y component of the Point.
def y(self, value): "Set the Y component of the Point." self._cs.setOrdinate(1, 0, value)
[ "def", "y", "(", "self", ",", "value", ")", ":", "self", ".", "_cs", ".", "setOrdinate", "(", "1", ",", "0", ",", "value", ")" ]
[ 131, 4 ]
[ 133, 41 ]
python
en
['en', 'en', 'en']
True
Point.z
(self)
Return the Z component of the Point.
Return the Z component of the Point.
def z(self): "Return the Z component of the Point." return self._cs.getOrdinate(2, 0) if self.hasz else None
[ "def", "z", "(", "self", ")", ":", "return", "self", ".", "_cs", ".", "getOrdinate", "(", "2", ",", "0", ")", "if", "self", ".", "hasz", "else", "None" ]
[ 136, 4 ]
[ 138, 64 ]
python
en
['en', 'en', 'en']
True
Point.z
(self, value)
Set the Z component of the Point.
Set the Z component of the Point.
def z(self, value): "Set the Z component of the Point." if not self.hasz: raise GEOSException('Cannot set Z on 2D Point.') self._cs.setOrdinate(2, 0, value)
[ "def", "z", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "hasz", ":", "raise", "GEOSException", "(", "'Cannot set Z on 2D Point.'", ")", "self", ".", "_cs", ".", "setOrdinate", "(", "2", ",", "0", ",", "value", ")" ]
[ 141, 4 ]
[ 145, 41 ]
python
en
['en', 'en', 'en']
True
Point.tuple
(self)
Return a tuple of the point.
Return a tuple of the point.
def tuple(self): "Return a tuple of the point." return self._cs.tuple
[ "def", "tuple", "(", "self", ")", ":", "return", "self", ".", "_cs", ".", "tuple" ]
[ 149, 4 ]
[ 151, 29 ]
python
en
['en', 'en', 'en']
True
Point.tuple
(self, tup)
Set the coordinates of the point with the given tuple.
Set the coordinates of the point with the given tuple.
def tuple(self, tup): "Set the coordinates of the point with the given tuple." self._cs[0] = tup
[ "def", "tuple", "(", "self", ",", "tup", ")", ":", "self", ".", "_cs", "[", "0", "]", "=", "tup" ]
[ 154, 4 ]
[ 156, 25 ]
python
en
['en', 'en', 'en']
True
Layer.__init__
(self, layer_ptr, ds)
Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active.
Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active.
def __init__(self, layer_ptr, ds): """ Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise GDALException('Cannot create Layer, invalid pointer given') self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability(b'RandomRead')
[ "def", "__init__", "(", "self", ",", "layer_ptr", ",", "ds", ")", ":", "if", "not", "layer_ptr", ":", "raise", "GDALException", "(", "'Cannot create Layer, invalid pointer given'", ")", "self", ".", "ptr", "=", "layer_ptr", "self", ".", "_ds", "=", "ds", "self", ".", "_ldefn", "=", "capi", ".", "get_layer_defn", "(", "self", ".", "_ptr", ")", "# Does the Layer support random reading?", "self", ".", "_random_read", "=", "self", ".", "test_capability", "(", "b'RandomRead'", ")" ]
[ 23, 4 ]
[ 36, 63 ]
python
en
['en', 'error', 'th']
False
Layer.__getitem__
(self, index)
Get the Feature at the specified index.
Get the Feature at the specified index.
def __getitem__(self, index): "Get the Feature at the specified index." if isinstance(index, int): # An integer index was given -- we cannot do a check based on the # number of features because the beginning and ending feature IDs # are not guaranteed to be 0 and len(layer)-1, respectively. if index < 0: raise IndexError('Negative indices are not allowed on OGR Layers.') return self._make_feature(index) elif isinstance(index, slice): # A slice was given start, stop, stride = index.indices(self.num_feat) return [self._make_feature(fid) for fid in range(start, stop, stride)] else: raise TypeError('Integers and slices may only be used when indexing OGR Layers.')
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "int", ")", ":", "# An integer index was given -- we cannot do a check based on the", "# number of features because the beginning and ending feature IDs", "# are not guaranteed to be 0 and len(layer)-1, respectively.", "if", "index", "<", "0", ":", "raise", "IndexError", "(", "'Negative indices are not allowed on OGR Layers.'", ")", "return", "self", ".", "_make_feature", "(", "index", ")", "elif", "isinstance", "(", "index", ",", "slice", ")", ":", "# A slice was given", "start", ",", "stop", ",", "stride", "=", "index", ".", "indices", "(", "self", ".", "num_feat", ")", "return", "[", "self", ".", "_make_feature", "(", "fid", ")", "for", "fid", "in", "range", "(", "start", ",", "stop", ",", "stride", ")", "]", "else", ":", "raise", "TypeError", "(", "'Integers and slices may only be used when indexing OGR Layers.'", ")" ]
[ 38, 4 ]
[ 52, 93 ]
python
en
['en', 'en', 'en']
True
Layer.__iter__
(self)
Iterate over each Feature in the Layer.
Iterate over each Feature in the Layer.
def __iter__(self): "Iterate over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) for i in range(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self)
[ "def", "__iter__", "(", "self", ")", ":", "# ResetReading() must be called before iteration is to begin.", "capi", ".", "reset_reading", "(", "self", ".", "_ptr", ")", "for", "i", "in", "range", "(", "self", ".", "num_feat", ")", ":", "yield", "Feature", "(", "capi", ".", "get_next_feature", "(", "self", ".", "_ptr", ")", ",", "self", ")" ]
[ 54, 4 ]
[ 59, 65 ]
python
en
['en', 'en', 'en']
True
Layer.__len__
(self)
The length is the number of features.
The length is the number of features.
def __len__(self): "The length is the number of features." return self.num_feat
[ "def", "__len__", "(", "self", ")", ":", "return", "self", ".", "num_feat" ]
[ 61, 4 ]
[ 63, 28 ]
python
en
['en', 'en', 'en']
True
Layer.__str__
(self)
The string name of the layer.
The string name of the layer.
def __str__(self): "The string name of the layer." return self.name
[ "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "name" ]
[ 65, 4 ]
[ 67, 24 ]
python
en
['en', 'en', 'en']
True