1#!/usr/local/bin/python3.8
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2014 - 2021 Detlev Offenbach <detlev@die-offenbachs.de>
5#
6
7"""
8Script for eric to clean up the source tree.
9"""
10
11import os
12import sys
13import fnmatch
14import shutil
15
16
17def cleanupSource(dirName):
18    """
19    Cleanup the sources directory to get rid of leftover files
20    and directories.
21
22    @param dirName name of the directory to prune (string)
23    """
24    # step 1: delete all Ui_*.py files without a corresponding
25    #         *.ui file
26    dirListing = os.listdir(dirName)
27    for formName, sourceName in [
28        (f.replace('Ui_', "").replace(".py", ".ui"), f)
29            for f in dirListing if fnmatch.fnmatch(f, "Ui_*.py")]:
30        if not os.path.exists(os.path.join(dirName, formName)):
31            os.remove(os.path.join(dirName, sourceName))
32            if os.path.exists(os.path.join(dirName, sourceName + "c")):
33                os.remove(os.path.join(dirName, sourceName + "c"))
34
35    # step 2: delete the __pycache__ directory and all remaining *.pyc files
36    if os.path.exists(os.path.join(dirName, "__pycache__")):
37        shutil.rmtree(os.path.join(dirName, "__pycache__"))
38    for name in [f for f in os.listdir(dirName)
39                 if fnmatch.fnmatch(f, "*.pyc")]:
40        os.remove(os.path.join(dirName, name))
41
42    # step 3: descent into subdirectories and delete them if empty
43    for name in os.listdir(dirName):
44        name = os.path.join(dirName, name)
45        if os.path.isdir(name):
46            cleanupSource(name)
47            if len(os.listdir(name)) == 0:
48                os.rmdir(name)
49
50
51def main(argv):
52    """
53    The main function of the script.
54
55    @param argv the list of command line arguments.
56    """
57    print("Cleaning up source ...")
58    sourceDir = os.path.dirname(os.path.dirname(__file__)) or "."
59    cleanupSource(sourceDir)
60
61
62if __name__ == "__main__":
63    try:
64        main(sys.argv)
65    except SystemExit:
66        raise
67    except Exception:
68        print(
69            "\nAn internal error occured.  Please report all the output of the"
70            " program, \nincluding the following traceback, to"
71            " eric-bugs@eric-ide.python-projects.org.\n")
72        raise
73
74#
75# eflag: noqa = M801
76