Debian Codegraph @

check-style.py

raw symbols SCIP
1 #!/bin/env python3
2
3 # Based on https://gitlab.gnome.org/GNOME/mutter/-/blob/main/check-style.py
4
5 import argparse
6 import os
7 import re
8 import shutil
9 import subprocess
10 import sys
11 import tempfile
12
13 # Path relative to this script
14 uncrustify_cfg = 'tools/gtk.cfg'
15
16
17 def check_progs():
18 git = shutil.which('git')
19 patch = shutil.which('patch')
20 uncrustify = shutil.which('uncrustify')
21
22 return git is not None and uncrustify is not None and patch is not None
23
24
25 def find_files(sha, all):
26 if all:
27 files = []
28 for dirpath, dirnames, filenames in os.walk('src'):
29 for filename in filenames:
30 files.append(os.path.join(dirpath, filename))
31 else:
32 proc = subprocess.Popen(
33 ["git", "diff", "--name-only", sha, "HEAD"],
34 stdout=subprocess.PIPE,
35 stderr=subprocess.STDOUT)
36 files = proc.stdout.read().strip().decode('utf-8')
37 files = files.split('\n')
38
39 files_filtered = []
40 for file in files:
41 if file.endswith('.cpp') or file.endswith('.c') or file.endswith('.h'):
42 files_filtered.append(file)
43
44 return files_filtered
45
46
47 def reformat_files(files, rewrite):
48 changed = None
49
50 for file in files:
51 # uncrustify chunk
52 proc = subprocess.Popen(
53 ["uncrustify", "-c", uncrustify_cfg, "-f", file],
54 stdout=subprocess.PIPE)
55 reformatted_raw = proc.stdout.readlines()
56 proc.wait()
57 if proc.returncode != 0:
58 continue
59
60 reformatted_tmp = tempfile.NamedTemporaryFile()
61 for line in reformatted_raw:
62 reformatted_tmp.write(line)
63 reformatted_tmp.seek(0)
64
65 if dry_run is True:
66 # Show changes
67 proc = subprocess.Popen(
68 ["diff", "-up", "--color=always", file, reformatted_tmp.name],
69 stdout=subprocess.PIPE,
70 stderr=subprocess.STDOUT)
71 diff = proc.stdout.read().decode('utf-8')
72 if diff != '':
73 output = re.sub('\t', '↦\t', diff)
74 print(output)
75 changed = True
76 else:
77 # Apply changes
78 diff = subprocess.Popen(
79 ["diff", "-up", file, reformatted_tmp.name],
80 stdout=subprocess.PIPE,
81 stderr=subprocess.STDOUT)
82 patch = subprocess.Popen(["patch", file], stdin=diff.stdout)
83 diff.stdout.close()
84 patch.communicate()
85
86 reformatted_tmp.close()
87
88 return changed
89
90
91 parser = argparse.ArgumentParser(description='Check code style.')
92 parser.add_argument('--all', type=bool,
93 action=argparse.BooleanOptionalAction,
94 help='Format all source files')
95 parser.add_argument('--sha', metavar='SHA', type=str,
96 help='SHA for the commit to compare HEAD with')
97 parser.add_argument('--dry-run', '-d', type=bool,
98 action=argparse.BooleanOptionalAction,
99 help='Only print changes to stdout, do not change code')
100 parser.add_argument('--rewrite', '-r', type=bool,
101 action=argparse.BooleanOptionalAction,
102 help='Whether to amend the result to the last commit (e.g. \'git rebase --exec "%(prog)s -r"\')')
103
104 # Change CWD to script location, necessary for always locating the configuration file
105 os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
106
107 args = parser.parse_args()
108 all = args.all
109 sha = args.sha or 'HEAD^'
110 rewrite = args.rewrite
111 dry_run = args.dry_run
112
113 if all and args.sha is not None:
114 print("Flags --all and --sha are mutualy exclusive")
115 sys.exit(1)
116
117 if check_progs() is False:
118 print("Make sure git, patch and uncrustify are installed")
119 sys.exit(1)
120
121 files = find_files(sha, all)
122 changed = reformat_files(files, rewrite)
123
124 if dry_run is not True and rewrite is True:
125 proc = subprocess.Popen(
126 ["git", "commit", "--all", "--amend", "-C", "HEAD"],
127 stdout=subprocess.DEVNULL)
128 sys.exit(0)
129 elif dry_run is True and changed is True:
130 print("\nIssue the following command in your local tree to apply the suggested changes:\n\n $ git rebase origin/main --exec \"./check-style.py -r\" \n")
131 sys.exit(2)
132
133 sys.exit(0)