Source

knife / knife / base.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# -*- coding: utf-8 -*-
'''Base knife mixins.'''

from threading import local
from functools import partial
from operator import truth
from collections import deque

from stuf.utils import memoize
from stuf.patterns import searcher
from stuf.six import identity, tounicode, tobytes

SLOTS = (
    '_in _work _hold _out _original _baseline _each _kw _history _worker _args'
    '_wrapper _pipe'
).split()


class KnifeMixin(local):

    '''Base knife mixin.'''

    _REPR = '{0}.{1} ([IN: ({2}) => WORK: ({3}) => HOLD: ({4}) => OUT: ({5})])'

    def __init__(self, ins, outs, **kw):
        super(KnifeMixin, self).__init__()
        # incoming things
        self._in = ins
        # outgoing things
        self._out = outs
        # pipe out default
        self._pipe = None
        # default output default
        self._each = False
        # original and baseline snapshots
        self._original = self._baseline = None
        # maximum number of history snapshots to keep (default: 5)
        self._history = deque(maxlen=kw.pop('snapshots', 5))
        # worker default
        self._worker = None
        # position arguments default
        self._args = ()
        # keyword arguments default
        self._kw = {}
        # default wrapper default
        self._wrapper = list

    @property
    def _identity(self):
        # use  generic identity function for worker if no worker assigned
        return self._worker if self._worker is not None else identity

    @property
    def _test(self, truth_=truth):
        # use truth operator function for worker if no worker assigned
        return self._worker if self._worker is not None else truth_

    @staticmethod
    @memoize
    def _pattern(pat, type, flags, s=searcher):
        # compile glob pattern into regex
        return s((type, pat), flags)

    def apply(self, worker, *args, **kw):
        '''
        Assign :func:`callable` used to work on incoming things plus any
        :term:`positional argument`\s and :term:`keyword argument`\s
        it will use.

        .. note::

          Global :term:`positional argument`\s and :term:`keyword argument`\s
          assigned with :meth:`params` are reset whenever :func:`apply` is
          called.

        :argument worker: a :func:`callable`

        :rtype: :mod:`knife` :term:`object`
        '''
        # assign worker
        self._worker = worker
        # positional params
        self._args = args
        # keyword arguemnts
        self._kw = kw
        return self

    def worker(self, worker):
        '''
        Assign :func:`callable` used to work on incoming things.

        .. note::

          Global :term:`positional argument`\s and :term:`keyword argument`\s
          assigned with :meth:`params` are reset whenever a new `worker` is
          assigned.

        :argument worker: a :func:`callable`

        :rtype: :mod:`knife` :term:`object`
        '''
        # reset stored position params
        self._args = ()
        # reset stored keyword params
        self._kw = {}
        # assign worker
        self._worker = worker
        return self

    def params(self, *args, **kw):
        '''
        Assign :term:`positional argument`\s and :term:`keyword argument`\s
        to be used globally.

        :rtype: :mod:`knife` :term:`object`
        '''
        # positional params
        self._args = args
        # keyword arguemnts
        self._kw = kw
        return self

    def partial(self, worker, *args, **kw):
        self._worker = partial(worker, *args, **kw)
        return self

    def pattern(self, pattern, type='parse', flags=0):
        '''
        Compile search `pattern` for use as :meth:`worker`.

        .. note::

          Global :term:`positional argument`\s and :term:`keyword argument`\s
          assigned with :meth:`params` are reset whenever a new `pattern` is
          compiled.

        :argument str pattern: search pattern

        :keyword str type: engine to compile `pattern` with. Valid options
          are `'parse' <http://pypi.python.org/pypi/parse/>`_, `'re'
          <http://docs.python.org/library/re.html>`_, or `'glob' <http://docs.
          python.org/library/fnmatch.html>`_
        :keyword int flags: regular expression `flags <http://docs.python.org/
          library/re.html#re.DEBUG>`_

        :rtype: :mod:`knife` :term:`object`

        >>> # using parse expression
        >>> test = __('first test', 'second test', 'third test')
        >>> test.pattern('first {}').filter().get()
        'first test'
        >>> # using glob pattern
        >>> test.original().pattern('second*', type='glob').filter().get()
        'second test'
        >>> # using regular expression
        >>> test.original().pattern('third .', type='regex').filter().get()
        'third test'
        '''
        # reset stored position params
        self._args = ()
        # reset stored keyword params
        self._kw = {}
        self._worker = self._pattern(pattern, type, flags)
        return self

    def prepend(self, *things):
        '''
        Insert `things` **before** other incoming things.

        :argument things: incoming things

        :rtype: :mod:`knife` :term:`object`

        >>> __(3, 4, 5).prepend(1, 2, 3, 4, 5, 6).peek()
        [1, 2, 3, 4, 5, 6, 3, 4, 5]
        '''
        return self._prependit(things)

    def append(self, *things):
        '''
        Insert `things` **after** other incoming things.

        :argument things: incoming things

        :rtype: :mod:`knife` :term:`object`

        >>> from knife import __
        >>> __(3, 4, 5).append(1, 2, 3, 4, 5, 6).peek()
        [3, 4, 5, 1, 2, 3, 4, 5, 6]
        '''
        return self._appendit(things)

    def pipe(self, knife):
        '''
        Pipe incoming things from some other :mod:`knife` :term:`object`
        through this :mod:`knife` :term:`object`.

        :argument knife: another :mod:`knife` :term:`object`

        :rtype: :mod:`knife` :term:`object`
        '''
        with self._chain:
            return self._pipeit(knife)

    def back(self):
        '''
        Switch back to :mod:`knife` :term:`object` that piped its incoming
        things through this :mod:`knife` :term:`object`.

        :rtype: :mod:`knife` :term:`object`
        '''
        with self._chain:
            return self._unpipeit()

    def __len__(self):
        '''Number of incoming things.'''
        return self._len()

    def __repr__(self):
        '''String representation.'''
        return self._repr()

    def __iter__(self):
        '''Iterate over outgoing things.'''
        return self._iterate()

    def get(self):
        '''
        Return outgoing things wrapped with :meth:`wrap`.

        .. note::

          With only one outgoing thing, only that one outgoing thing is
          returned. With multiple outgoing things, they are returned wrapped
          with the wrapper assigned with :meth:`wrap` (default wrapper is
          :func:`list`).
        '''
        return self._get()

    def peek(self):
        '''
        Preview current incoming things wrapped with :meth:`wrap`.

        .. note::

          With only one outgoing thing, only that one thing is returned. With
          multiple outgoing things, everything is returned wrapped with the
          wrapper assigned with :meth:`wrap` (default wrapper is :func:`list`).
        '''
        return self._peek()

    def wrap(self, wrapper):
        '''
        Assign :term:`object`, :term:`type`, or :keyword:`class` used to wrap
        outgoing things.

        .. note::

          A :mod:`knife` :term:`object` resets back to its default wrapper
          (:func:`list`) after :meth:`get` or :meth:`peek` is called.

        :argument wrapper: an :term:`object`, :func:`type`, or :keyword:`class`

        :rtype: :mod:`knife` :term:`object`

        >>> __(1, 2, 3, 4, 5, 6).wrap(tuple).peek()
        (1, 2, 3, 4, 5, 6)
        '''
        self._wrapper = wrapper
        return self

    def oneach(self):
        '''
        Toggle whether each outgoing thing should be individually wrapped with
        the wrapper assigned with :meth:`wrap` (default wrapper is :func:`list`
        ) or whether all outgoing things should be wrapped all at once.

        .. note::

          :mod:`knife` :term:`object` default behavior is to wrap all outgoing
          things all at once. :mod:`knife` :term:`object`\s reset back to this
          behavior **after** :meth:`get` or :meth:`peek` is called.

        :rtype: :mod:`knife` :term:`object`
        '''
        self._each = not self._each
        return self

    def ascii(self, errors='strict'):
        '''
        :meth:`~str.encode` outgoing things as `bytes <http://docs.python
        .org/py3k/library/functions.html#bytes>`_ with the ``'latin-1'`` codec.

        :keyword str errors: `error handling <http://docs.python.org/library/
          codecs.html#codec-base-classes>`_ for encoding

        :rtype: :mod:`knife` :term:`object`

        >>> from stuf.six import u, b
        >>> test = __([1], True, r't', b('i'), u('g'), None, (1,))
        >>> test.ascii().oneach().peek()
        ['[1]', 'True', 't', 'i', 'g', 'None', '(1,)']
        '''
        self._wrapper = lambda x: tobytes(x, 'latin_1', errors)
        return self

    def bytes(self, encoding='utf_8', errors='strict'):
        '''
        :meth:`~str.encode` outgoing things as `bytes <http://docs.python
        .org/py3k/library/functions.html#bytes>`_.

        :keyword str encoding: character `encoding <http://docs.python.org/
          library/codecs.html#standard-encodings>`_

        :keyword str errors: `error handling <http://docs.python.org/library/
          codecs.html#codec-base-classes>`_ for encoding

        :rtype: :mod:`knife` :term:`object`

        >>> test = __([1], True, r't', b('i'), u('g'), None, (1,))
        >>> test.bytes().oneach().peek()
        ['[1]', 'True', 't', 'i', 'g', 'None', '(1,)']
        '''
        self._wrapper = lambda x: tobytes(x, encoding, errors)
        return self

    def unicode(self, encoding='utf_8', errors='strict'):
        '''
        :func:`unicode` (:func:`str` under Python 3) :meth:`~str.decode`
        outgoing things.

        :keyword str encoding: Unicode `encoding <http://docs.python.org/
          library/codecs.html#standard-encodings>`_

        :keyword str errors: `error handling <http://docs.python.org/library/
          codecs.html#codec-base-classes>`_ for decoding

        :rtype: :mod:`knife` :term:`object`

        >>> test = __([1], True, r't', b('i'), u('g'), None, (1,))
        >>> test.unicode().oneach().peek()
        [u'[1]', u'True', u't', u'i', u'g', u'None', u'(1,)']
        '''
        self._wrapper = lambda x: tounicode(x, encoding, errors)
        return self

    def undo(self, snapshot=0):
        '''
        Revert incoming things to a previous snapshot.

        .. note::

          A snapshot of current incoming things is taken when a :mod:`knife`
          :term:`method` is called but before the main body of the method
          executes.

        :keyword int snapshot: number of steps ago ``1``, ``2``, ``3``, etc.

        :rtype: :mod:`knife` :term:`object`

        >>> undone = __(1, 2, 3).prepend(1, 2, 3, 4, 5, 6)
        >>> undone.peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3]
        >>> # undo back one step
        >>> undone.append(1).undo().peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3]
        >>> # undo back one step
        >>> undone.append(1).append(2).undo().peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3, 1]
        >>> # undo back 2 steps
        >>> undone.append(1).append(2).undo(2).peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3, 1]
        '''
        return self._undo(snapshot)

    def snapshot(self):
        '''
        Take a baseline snapshot of current incoming things.

        :rtype: :mod:`knife` :term:`object`
        '''
        return self._snapshot()

    def baseline(self):
        '''
        Restore incoming things back to the baseline :meth:`snapshot`.

        :rtype: :mod:`knife` :term:`object`

        >>> from knife import __
        >>> undone = __(1, 2, 3).prepend(1, 2, 3, 4, 5, 6)
        >>> undone.peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3]
        >>> undone.snapshot().append(1).append(2).peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2]
        >>> undone.baseline().peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3]
        '''
        return self._rollback()

    def original(self):
        '''
        Restore incoming things back to the original snapshot.

        .. note::

          THe original snapshot of incoming things is taken following the first
          :mod:`knife` :term:`method` call but before the second :mod:`knife`
          :term:`method` call (if there is a second :term:`method` call)

        :rtype: :mod:`knife` :term:`object`

        >>> undone = __(1, 2, 3).prepend(1, 2, 3, 4, 5, 6)
        >>> undone.peek()
        [1, 2, 3, 4, 5, 6, 1, 2, 3]
        >>> undone.original().peek()
        [1, 2, 3]
        '''
        return self._revert()

    def clear(self):
        '''
        Clear everything.

        :rtype: :mod:`knife` :term:`object`
        '''
        return self._clear()