repl.it
@anonymous/

HummingPalegreenDarwinsfox

Python

No description

fork
loading
Files
  • main.py
main.py
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
from pathlib import Path
from typing import NamedTuple

FSTAB = Path('/etc/fstab')
OFFSET = 4 # number of spaces desired between columns

class FstabLine(NamedTuple):
    device_spec: str
    mount_point: str
    fs_type: str
    options: str
    dump: int
    pass_: int


def format_line(len_dict: dict, line: FstabLine) -> str:
    return (
        f"{line.device_spec:{len_dict['device_spec']}}"
        f"{line.mount_point:{len_dict['mount_point']}}"
        f"{line.fs_type:{len_dict['fs_type']}}"
        f"{line.options:{len_dict['options']}}{line.dump{len_dict['dump']}}"
        f"{line.pass_}\n"
    )

def get_longest(lines: list) -> dict:
    d = {}
    for field in FstabLine._fields:
        if field == 'pass_':
            continue

        d[field] = max(
            [len(getattr(l, field)) for l in lines if isinstance(l, FstabLine)]
        ) + OFFSET

    return d

def parse(content: list) -> list:
    parsed_content = []
    for line in content:
        if line.startswith('#'):
            parsed_content.append(f'# {line.lstrip("#").strip()}\n')
        elif line.startswith('\n'):
            parsed_content.append(line)
        else:
            parsed_content.append(FstabLine(*line.split(maxsplit=6)))

    return parsed_content

def main() -> None:
    with FSTAB.open() as f:
        lines = f.readlines()

    lines = parse(lines)

    len_dict = get_longest(lines)

    with FSTAB.open('w+') as f:
        for line in lines:
            if isinstance(line, FstabLine):
                f.write(format_line(len_dict, line))
            else:
                f.write(line)

if __name__ == '__main__':
    main()