1#!/usr/bin/env python3
2
3
4# Copyright 2018 The Meson development team
5
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9
10#     http://www.apache.org/licenses/LICENSE-2.0
11
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18'''Renames test case directories using Git from this:
19
201 something
213 other
223 foo
233 bar
24
25to this:
26
271 something
282 other
293 foo
304 bar
31
32This directory must be run from source root as it touches run_unittests.py.
33'''
34
35import typing as T
36import os
37import sys
38import subprocess
39
40from glob import glob
41
42def get_entries() -> T.List[T.Tuple[int, str]]:
43    entries = []
44    for e in glob('*'):
45        if not os.path.isdir(e):
46            raise SystemExit('Current directory must not contain any files.')
47        (number, rest) = e.split(' ', 1)
48        try:
49            numstr = int(number)
50        except ValueError:
51            raise SystemExit(f'Dir name {e} does not start with a number.')
52        entries.append((numstr, rest))
53    entries.sort()
54    return entries
55
56def replace_source(sourcefile: str, replacements: T.List[T.Tuple[str, str]]) -> None:
57    with open(sourcefile, encoding='utf-8') as f:
58        contents = f.read()
59    for old_name, new_name in replacements:
60        contents = contents.replace(old_name, new_name)
61    with open(sourcefile, 'w', encoding='utf-8') as f:
62        f.write(contents)
63
64def condense(dirname: str) -> None:
65    curdir = os.getcwd()
66    os.chdir(dirname)
67    entries = get_entries()
68    replacements = []
69    for _i, e in enumerate(entries):
70        i = _i + 1
71        if e[0] != i:
72            old_name = str(e[0]) + ' ' + e[1]
73            new_name = str(i) + ' ' + e[1]
74            #print('git mv "%s" "%s"' % (old_name, new_name))
75            subprocess.check_call(['git', 'mv', old_name, new_name])
76            replacements.append((old_name, new_name))
77            # update any appearances of old_name in expected stdout in test.json
78            json = os.path.join(new_name, 'test.json')
79            if os.path.isfile(json):
80                replace_source(json, [(old_name, new_name)])
81    os.chdir(curdir)
82    replace_source('run_unittests.py', replacements)
83    replace_source('run_project_tests.py', replacements)
84
85if __name__ == '__main__':
86    if len(sys.argv) != 1:
87        raise SystemExit('This script takes no arguments.')
88    for d in glob('test cases/*'):
89        condense(d)
90