コード例 #1
0
ファイル: _transaction.py プロジェクト: chenqianethz/pyRevit
class Action():
    """
    Simplifies transactions by applying ``Transaction.Start()`` and
    ``Transaction.Commit()`` before and after the context.
    Automatically rolls back if exception is raised.

    >>> with Action('Move Wall'):
    >>>     wall.DoSomething()

    >>> with Action('Move Wall') as action:
    >>>     wall.DoSomething()
    >>>     assert action.status == ActionStatus.Started  # True
    >>> assert action.status == ActionStatus.Committed    # True

    """
    def __init__(self,
                 name=None,
                 clear_after_rollback=False,
                 show_error_dialog=False):
        self._rvt_transaction = Transaction(
            self.doc, name if name else DEFAULT_TRANSACTION_NAME)
        self._fail_hndlr_ops = self._rvt_transaction.GetFailureHandlingOptions(
        )
        self._fail_hndlr_ops.SetClearAfterRollback(clear_after_rollback)
        self._fail_hndlr_ops.SetForcedModalHandling(show_error_dialog)
        self._rvt_transaction.SetFailureHandlingOptions(self._fail_hndlr_ops)

    def __enter__(self):
        self._rvt_transaction.Start()
        return self

    def __exit__(self, exception, exception_value, traceback):
        if exception:
            self._rvt_transaction.RollBack()
            logger.error(
                'Error in Action Context. Rolling back changes. | {}:{}'.
                format(exception, exception_value))
        else:
            try:
                self._rvt_transaction.Commit()
            except Exception as errmsg:
                self._rvt_transaction.RollBack()
                logger.error(
                    'Error in Action Commit. Rolling back changes. | {}'.
                    format(errmsg))

    @property
    def name(self):
        return self._rvt_transaction.GetName()

    @name.setter
    def name(self, new_name):
        return self._rvt_transaction.SetName(new_name)

    @property
    def status(self):
        return ActionStatus.from_rvt_trans_stat(
            self._rvt_transaction.GetStatus())

    @staticmethod
    def carryout(name):
        """ Action Decorator

        Decorate any function with ``@Action.carryout('Action Name')``
        and the funciton will run within an Action context.

        Args:
            name (str): Name of the Action

        >>> @Action.carryout('Do Something')
        >>> def set_some_parameter(wall, value):
        >>>     wall.parameters['Comments'].value = value
        >>>
        >>> set_some_parameter(wall, value)
        """
        from functools import wraps

        def wrap(f):
            @wraps(f)
            def wrapped_f(*args, **kwargs):
                with Action(name):
                    return_value = f(*args, **kwargs)
                return return_value

            return wrapped_f

        return wrap

    def has_started(self):
        return self._rvt_transaction.HasStarted()

    def has_ended(self):
        return self._rvt_transaction.HasEnded()
active_lvl = active_view.GenLevel


class RoomWarningSwallower(IFailuresPreprocessor):
    def PreprocessFailures(self, failuresAccessor):
        fail_list = List[FailureMessageAccessor]()
        fail_acc_list = failuresAccessor.GetFailureMessages().GetEnumerator()
        for failure in fail_acc_list:
            failure_id = failure.GetFailureDefinitionId()
            failure_severity = failure.GetSeverity()
            failure_type = BuiltInFailures.RoomFailures.RoomNotEnclosed
            if failure_id == failure_type:
                print("{0} with id: {1} of type: RoomNotEnclosed removed!".
                      format(failure_severity, failure_id.Guid))
                failuresAccessor.DeleteWarning(failure)
        return FailureProcessingResult.Continue


# "Start" the transaction
tx = Transaction(doc, "place unenclosed room")
tx.Start()

options = tx.GetFailureHandlingOptions()
options.SetFailuresPreprocessor(RoomWarningSwallower())
tx.SetFailureHandlingOptions(options)

room = doc.Create.NewRoom(active_lvl, UV(0, 0))

# "End" the transaction
tx.Commit()