File: file_format.py

package info (click to toggle)
basis-universal 2.0.2-3
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 216,436 kB
  • sloc: cpp: 163,224; ansic: 51,368; python: 2,824; javascript: 2,637; lisp: 1,026; sh: 161; makefile: 17
file content (52 lines) | stat: -rwxr-xr-x 1,296 bytes parent folder | download
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

if len(sys.argv) < 2:
    print("Invalid usage of file_format.py, it should be called with a path to one or multiple files.")
    sys.exit(1)

BOM = b"\xef\xbb\xbf"

changed = []
invalid = []

for file in sys.argv[1:]:
    try:
        with open(file, "rt", encoding="utf-8") as f:
            original = f.read()
    except UnicodeDecodeError:
        invalid.append(file)
        continue

    if original == "":
        continue

    EOL = "\r\n" if file.endswith((".csproj", ".sln", ".bat")) else "\n"
    WANTS_BOM = file.endswith((".csproj", ".sln"))

    revamp = EOL.join([line.rstrip("\n\r\t ") for line in original.splitlines(True)]).rstrip(EOL) + EOL

    new_raw = revamp.encode(encoding="utf-8")
    if not WANTS_BOM and new_raw.startswith(BOM):
        new_raw = new_raw[len(BOM) :]
    elif WANTS_BOM and not new_raw.startswith(BOM):
        new_raw = BOM + new_raw

    with open(file, "rb") as f:
        old_raw = f.read()

    if old_raw != new_raw:
        changed.append(file)
        with open(file, "wb") as f:
            f.write(new_raw)

if changed:
    for file in changed:
        print(f"FIXED: {file}")

if invalid:
    for file in invalid:
        print(f"REQUIRES MANUAL CHANGES: {file}")
    sys.exit(1)