aboutsummaryrefslogtreecommitdiff
path: root/Python Pipeline.wiki
blob: e91f93f790a264225534467d14e8a1105bdd5a68 (plain)
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
{{{python
#!/usr/bin/env python3

import base64
import hashlib
import os.path
import sys
from typing import Callable, Any
from dataclasses import dataclass


@dataclass
class Pipeline:
    """
    A data pipeline.

    "Syntax" to allow functions and methods to be chained, similar to
    clojures arrow operator (``->``).

    Each operation applies some kind of procedure, and forwards the
    pipeline with the result (by returning a new Pipeline object with
    the contained object being replaced:

    ``.do`` applies a function, passing the pipelined object as the
    first value. If another position is wanted, use a lambda.

    ``.on`` Applies a method on the object. The method name needs to
    be passed as a string due to how python works.
    """

    object: Any

    def on(self, proc: str, *args) -> 'Pipeline':
        """Apply function to pipeline."""
        return Pipeline(getattr(self.object, proc)(*args))

    def do(self, proc: Callable, *args) -> 'Pipeline':
        """Run method in pipeline."""
        return Pipeline(proc(self.object, *args))


with open(os.path.expanduser('~/.ssh/id_rsa'), 'rb') as f:
    data = f.read()

Pipeline(data) \
    .on('split', b'\n') \
    .do(lambda x: x[1:-2]) \
    .do(lambda d: b''.join(d)) \
    .do(base64.b64decode) \
    .do(hashlib.sha256) \
    .on('digest') \
    .do(base64.b64encode) \
    .do(sys.stdout.buffer.write)

print()
}}}