Esempio n. 1
0
 def folderGopBack(self):
     if self.main == True:
         winshell.delete_file(self.selected.obj.original_filename())
         self.goBack()
     if self.main == False:
         self.FolderUi(MainWindow, self.lst[0], self.lst[1], True,
                       self.lst[3], self.lst[4])
Esempio n. 2
0
def delete_old_output(ctx):
    '''Delete old Pelican output.'''
    global step_no
    step_no += 1
    minchin.text.clock_on_right(str(step_no).rjust(2) + ". Deleting old Pelican output.")

    to_delete = []
    html_files = 0
    os.chdir(str(GITHUB_FOLDER))
    all_files = os.listdir(str(GITHUB_FOLDER))

    for filename in all_files:
        if filename == ('.git'):
            pass  # don't drop the GIT repo
        elif filename == ('images'):
            pass  # don't drop the image folder
        elif filename.endswith('.html'):
            html_files += 1
        else:
            to_delete.append(filename)

    counter = 0

    # delete HTML files
    run('del /S /Q {}\*.html'.format(GITHUB_FOLDER), shell=INVOKE_SHELL, hide=True)
    bar = minchin.text.progressbar(maximum=len(to_delete) + html_files)
    counter = html_files
    bar.update(counter)

    # delete everything else
    for my_file in to_delete:
        winshell.delete_file(my_file, no_confirm=True, allow_undo=False, silent=True)
        counter += 1
        bar.update(counter)
    print("\n{}{} files deleted.".format(INDENT*2, str(len(to_delete) + html_files)))
Esempio n. 3
0
def OpenFolder(obj, dict):
    winshell.undelete(obj.obj.original_filename())
    listOfDirs = os.listdir(obj.sahiPath)
    winshell.delete_file(obj.obj.original_filename())
    fmt = "{0:3} | {1:8} | {2:10}"
    print(fmt.format("Sr:", "Type:", "Name:"))
    Sr = 0
    for i in listOfDirs:
        Sr += 1
        if "." in i:
            type = "file"
        else:
            type = "Folder"
        print(fmt.format(Sr, type, i))
    print(" Enter serial no to open any file/folder \n Press B to go back ")
    n = input("Enter: ")
    if str(n) == "B" or str(n) == "b":
        Beginning(dict)
    else:
        try:
            n = eval(n)
            name = listOfDirs[n - 1]
            path = obj.sahiPath + "\\\\" + listOfDirs[n - 1]
            if "." in name:
                ClearScreen()
                OpenFileFromFolder(obj, path, dict)
            else:
                ClearScreen()
                OpenFolderFromFolder(obj, path, dict)
        except:
            ClearScreen()
            print(" Enter a valid serial no ")
            OpenFolder(obj, dict)
Esempio n. 4
0
def borrar_acceso():
	startup = winshell.startup()
	accesoD = os.path.join(startup, "IP por Email - vCC.lnk")
	aux = os.path.isfile(accesoD)
	# Si el acceso directo existe lo borra
	if aux == True:
		winshell.delete_file(accesoD, allow_undo=False,
			no_confirm=True ,silent=True)
Esempio n. 5
0
def generate_prjct_docs(export_path=None, relative_path=True):
    """
    Provide prjct documentation.

    Generates prjct's included documentation sources, and exports it to the
    `export_path`.
    """
    if config.confirm():
        cfg = config.load()
        if export_path is None:
            export_path = cfg['sphinx']['doc_sources']

        here = Path(__file__)
        readme_loc = here.parent / '..' / 'readme.rst'
        changes_loc = readme_loc.with_name('changes.rst')

        # everything but documentation front page
        docs_files = [changes_loc]

        if relative_path:
            export_loc = Path.cwd() / export_path / '.no-file'
        else:
            # we have an absolute path
            export_loc = Path(export_path)

        # make the folder if it doesn't exist
        export_loc.parent.mkdir(exist_ok=True)

        # copy over readme as front page of documentation
        # TODO: readme to have toctree containing the rest of the documentation
        dest_loc = export_loc.with_name('index.rst')
        try:
            winshell.delete_file(str(dest_loc), no_confirm=True)
        except winshell.x_winshell:
            pass
        winshell.copy_file(str(readme_loc),
                           str(dest_loc),
                           rename_on_collision=False)

        # copy over everything else
        for my_file in docs_files:
            # with Python 3.5.2 use `readme_loc.path`
            dest_loc = export_loc.with_name(my_file.name)
            try:
                winshell.delete_file(str(dest_loc), no_confirm=True)
            except winshell.x_winshell:
                pass
            winshell.copy_file(str(my_file),
                               str(dest_loc),
                               rename_on_collision=False)
    else:
        print('No existing configuration file found. Default configuration \
              written to {}.'.format(config.file_path()))
        print('Please reveiw configuration and re-run.')
Esempio n. 6
0
def generate_prjct_docs(export_path=None, relative_path=True):
    """
    Provide prjct documentation.

    Generates prjct's included documentation sources, and exports it to the
    `export_path`.
    """
    if config.confirm():
        cfg = config.load()
        if export_path is None:
            export_path = cfg['sphinx']['doc_sources']

        here = Path(__file__)
        readme_loc = here.parent / '..' / 'readme.rst'
        changes_loc = readme_loc.with_name('changes.rst')

        # everything but documentation front page
        docs_files = [changes_loc]

        if relative_path:
            export_loc = Path.cwd() / export_path / '.no-file'
        else:
            # we have an absolute path
            export_loc = Path(export_path)

        # make the folder if it doesn't exist
        export_loc.parent.mkdir(exist_ok=True)

        # copy over readme as front page of documentation
        # TODO: readme to have toctree containing the rest of the documentation
        dest_loc = export_loc.with_name('index.rst')
        try:
            winshell.delete_file(str(dest_loc), no_confirm=True)
        except winshell.x_winshell:
            pass
        winshell.copy_file(str(readme_loc), str(dest_loc), rename_on_collision=False)

        # copy over everything else
        for my_file in docs_files:
            # with Python 3.5.2 use `readme_loc.path`
            dest_loc = export_loc.with_name(my_file.name)
            try:
                winshell.delete_file(str(dest_loc), no_confirm=True)
            except winshell.x_winshell:
                pass
            winshell.copy_file(str(my_file), str(dest_loc), rename_on_collision=False)
    else:
        print('No existing configuration file found. Default configuration \
              written to {}.'.format(config.file_path()))
        print('Please reveiw configuration and re-run.')
Esempio n. 7
0
    def setUp(self):
        self.root = os.path.join(tempfile.gettempdir(), "winshell")
        if not os.path.exists(self.root):
            os.mkdir(self.root)

        self.temppath = tempfile.mkdtemp(dir=self.root)
        handle, self.tempfile = tempfile.mkstemp(dir=self.temppath)
        os.close(handle)

        self.deleted_files = set()
        f = open(self.tempfile, "wb")
        try:
            timestamp = b("*")
            f.write(timestamp)
        finally:
            f.close()
        winshell.delete_file(self.tempfile, silent=True, no_confirm=True)
Esempio n. 8
0
def unpack_assets(ctx, source=SB_ASSETS, destination="unpacked"):
    """Unpack the game assets."""
    text.title("Asset Unpacker")

    source = Path(source)
    destination = Path(destination)

    # check source file
    if source.exists():
        print("Games Assets: {}FOUND{}!".format(GREEN, RESET_ALL))
    else:
        print("Game Assets: {}MISSING{}".format(RED, RESET_ALL))
        print("Exiting...")
        sys.exit(1)

    # check destination folder
    if destination.exists():
        # test if folder is empty
        if list(destination.rglob("*")):
            print("Destination Folder: {}Exists, Not Empty{}".format(
                YELLOW, RESET_ALL))
            print("    {}".format(destination.resolve()))
            ans = text.query_yes_no("    Empty Folder?")
            if ans == text.Answers.YES:
                winshell.delete_file(destination.rglob("*"), silent=True)
        else:
            print("Destination Folder: {}Exists, Empty{}!".format(
                GREEN, RESET_ALL))
    else:
        print("Destination Folder: {}MISSING{}".format(YELLOW, RESET_ALL))
        ans = text.query_yes_no("    Create?")
        if ans == text.Answers.YES:
            destination.mkdir(parents=True)
        else:
            print("Exiting...")
            sys.exit(1)

    # the actual unpacking!
    cmd = '"{}" "{}" "{}"'.format(
        SB_ASSET_UNPACKER,
        source,
        destination,
    )
    print("Unpacking...")
    run(cmd)
    print("{}Done!{}".format(GREEN, RESET_ALL))
Esempio n. 9
0
def OpenFile(obj, dict):
    try:
        winshell.undelete(obj.obj.original_filename())
        file = open(obj.sahiPath, 'r')
        R = file.read()
        file.close()
        winshell.delete_file(obj.obj.original_filename())
        print(R)
        print("Press any key to go back")
        key = input("Enter: ")
        if key != '':
            ClearScreen()
            OperationOnItem(obj, dict)
    except:
        ClearScreen()
        print("This file can not be opened ")
        OperationOnItem(obj, dict)
Esempio n. 10
0
def replace_index(ctx):
    '''Copy over index.md, 404.md.'''
    global step_no
    step_no += 1
    minchin.text.clock_on_right(str(step_no).rjust(2) + ". Copy over index.md, 404.md.")

    os.chdir(str(CONTENT_FOLDER))
    for my_file in ("index.md", "index.html", "404.md"):
        try:
            winshell.delete_file(my_file, no_confirm=True, allow_undo=False, silent=True)
        except:
            pass

    for my_file in ("index.md",
                    # "404.md"
                   ):
        winshell.copy_file("../../_unchanging_pages/{}".format(my_file), my_file, no_confirm=True)
Esempio n. 11
0
    def get(self, request, target_folder):
        '''
        select * from fileinfo where 
        '''
        print("Get DeleteRAID1Duplicates:" + target_folder)

        (searchmatches,
         dup_files_in_target) = getMatchedFileInfos(target_folder)

        for fileobj in dup_files_in_target:
            filepath = os.path.abspath(fileobj.folder + '/' + fileobj.fname)
            winshell.delete_file(filepath)

        print("********  {cnt} Files are deleted!!!!!! =============".format(
            cnt=len(dup_files_in_target)))

        fileinfoserializer = FileInfoSerializer(searchmatches, many=True)
        return Response(fileinfoserializer.data)
Esempio n. 12
0
def Beginning(dictionary):
    ClearScreen()
    if dictionary is None:
        listOfItems = list(winshell.recycle_bin())

        dictOfObjects = {}
        fmt = "{0:3} | {1:8} | {2:10}"
        print(fmt.format("Sr:", "Type:", "Name:"))
        for i, v in enumerate(listOfItems):
            serialNo = i + 1
            path = v.original_filename()
            listOfPath = path.split("\\")
            newPath = "\\\\".join(listOfPath)
            winshell.undelete(path)
            name = listOfPath[-1]
            if os.path.isdir(newPath) == True:
                type = "Folder"
                size = get_dir_size(newPath)
                listOfFolderItems = os.listdir(newPath)
                noOfFolder = 0
                noOfFile = 0
                for i in listOfFolderItems:
                    checkpath = newPath + '\\\\' + i
                    if os.path.isdir(checkpath) == True:
                        noOfFolder += 1
                    elif os.path.isfile(checkpath) == True:
                        noOfFile += 1
                dictOfObjects[serialNo] = DeletedObject(
                    v, type, name, newPath, "{0:.1f}".format(size / 1024),
                    [noOfFile, noOfFolder])
            elif os.path.isfile(newPath) == True:
                type = "file"
                size = os.path.getsize(newPath)
                dictOfObjects[serialNo] = DeletedObject(
                    v, type, name, newPath, "{0:.1f}".format(size / 1024), [])
            winshell.delete_file(path)
            print(fmt.format(serialNo, type, name))
        SelectedItem(dictOfObjects)
    else:
        fmt = "{0:3} | {1:8} | {2:10}"
        print(fmt.format("Sr:", "Type:", "Name:"))
        for k, v in dictionary.items():
            print(fmt.format(k, v.typeOfObj, v.name))
        SelectedItem(dictionary)
Esempio n. 13
0
def OpenFileFromFolder(obj, filepath, dict):
    try:
        winshell.undelete(obj.obj.original_filename())
        file = open(filepath, "r")
        R = file.read()
        file.close()
        winshell.delete_file(obj.obj.original_filename())
        print(R)
        print(" Press any key to go back ")
        key = input(" Enter: ")
        if key:
            ClearScreen()
            OpenFolderFromFolder(obj, "\\\\".join(filepath.split("\\\\")[:-1]),
                                 dict)
    except:
        ClearScreen()
        print(" This file can not be opened ")
        OpenFolderFromFolder(obj, "\\\\".join(filepath.split("\\\\")[:-1]),
                             dict)
Esempio n. 14
0
        def setUp(self):
            self.root = os.path.join(tempfile.gettempdir(), "winshell")
            if not os.path.exists(self.root):
                os.mkdir(self.root)

            self.temppath = tempfile.mkdtemp(dir=self.root)
            handle, self.tempfile = tempfile.mkstemp(dir=self.temppath)
            os.close(handle)

            self.deleted_files = set()
            for i in range(3):
                f = open(self.tempfile, "wb")
                try:
                    timestamp = b("*") * (i + 1)
                    f.write(timestamp)
                finally:
                    f.close()
                self.deleted_files.add((timestamp, os.path.getsize(self.tempfile)))
                winshell.delete_file(self.tempfile, silent=True, no_confirm=True)

                time.sleep(1.1)
Esempio n. 15
0
def copy_gigatree_assets(ctx):
    '''Copy Gigatree .js, .css, and images files.'''
    global step_no
    step_no += 1
    minchin.text.clock_on_right(str(step_no).rjust(2) + ". Copy Gigatree asset files.")
    # files are copied from the base GIGATREES_ASSETS to the `content / js`
    # (where Pelican will find them)

    dest_folder = (CONTENT_FOLDER / '..').resolve() / 'assets'

    for my_file in GIGATREES_ASSETS.iterdir():
        dest_path = str(dest_folder / my_file.name)
        source_path = str(my_file)
        #print(dest_path)
        #print(source_path)
        #print(my_file, my_file)
        try:
            winshell.delete_file(dest_path, no_confirm=True, allow_undo=False, silent=True)
        except:
            pass
        winshell.copy_file(source_path, dest_path, no_confirm=True)
Esempio n. 16
0
 def ticked_runStartup():
     if run_startup.get() == True:
         # based on https://winshell.readthedocs.io/en/latest/shortcuts.html
         startup_lnk = os.path.join(winshell.startup(), "AutoTheme-19.lnk")
         with winshell.shortcut(startup_lnk) as link:
             link.path = sys.executable
             link.description = "AutoTheme-19, a windows desktop time-based theme switcher"
             link.icon = sys.executable, 0
             link.working_directory = os.path.dirname(
                 os.path.abspath(__file__))
         print("setting a shortcut in the startup folder to run at startup")
     elif run_startup.get() == False:
         try:
             winshell.delete_file(os.path.join(winshell.startup(),
                                               "AutoTheme-19.lnk"),
                                  allow_undo=False,
                                  no_confirm=True,
                                  silent=True)
             print(
                 "deleting the shortcut in the startup folder so I don't run at startup"
             )
         except winshell.x_winshell:
             print("shortcut not found, shrugs")
Esempio n. 17
0
def unpack_steam_mods(
    ctx,
    source=SB_STEAM_MODS_DIR,
    destination="unpacked-mods",
    override_existing=False,
    skip_existing=False,
    verbose=False,
):
    """Unpack all steam mods."""
    text.title("Steam Mod Unpacker")

    count_skipped = 0
    count_unpacked = 0
    count_errorred = 0
    error_list = []

    source = Path(source)
    destination = Path(destination)

    # check source file
    if source.exists():
        print("Steam Mods: {}FOUND{}!".format(GREEN, RESET_ALL))
    else:
        print("Steam Mods: {}MISSING{}".format(RED, RESET_ALL))
        print("Exiting...")
        sys.exit(1)

    # check destination folder
    if destination.exists():
        # test if folder is empty
        if list(destination.rglob("*")):
            print("Destination Folder: {}Exists, Not Empty{}".format(
                YELLOW, RESET_ALL))
            print("    {}".format(destination.resolve()))
            ans = text.query_yes_no("    Empty Folder?", default="no")
            if ans == text.Answers.YES:
                winshell.delete_file(destination.rglob("*"), silent=True)
        else:
            print("Destination Folder: {}Exists, Empty{}!".format(
                GREEN, RESET_ALL))
    else:
        print("Destination Folder: {}MISSING{}".format(YELLOW, RESET_ALL))
        ans = text.query_yes_no("    Create?")
        if ans == text.Answers.YES:
            destination.mkdir(parents=True)
        else:
            print("Exiting...")
            sys.exit(1)

    print("Unpacking...")
    for fn in source.iterdir():
        if fn.is_dir():
            mod_id = fn.name
            mod_destination = destination / mod_id
            skip_this = False
            override_this = False
            if mod_destination.exists():
                if not override_existing and not skip_existing:
                    ans = text.query_yes_no_all_none(
                        ("Destination folder for "
                         "mod {} exists. Override?".format(mod_id)),
                        default="none",
                    )
                    if ans == text.Answers.YES:
                        override_this = True
                    elif ans == text.Answers.NO:
                        skip_this = True
                    elif ans == text.Answers.ALL:
                        override_existing = True
                        override_this = True
                    elif ans == text.Answers.NONE:
                        skip_existing = True
                        skip_this = True

                if override_this or override_existing:
                    winshell.rmdir(mod_destination)
                else:
                    skip_this = True

            # the actual unpacking!
            if skip_this:
                if verbose:
                    print("    {}Skipping{} {}...".format(
                        YELLOW, RESET_ALL, mod_id))
                count_skipped += 1
            else:
                if (fn / "contents.pak").exists():
                    cmd = '"{}" "{}" "{}"'.format(
                        SB_ASSET_UNPACKER,
                        fn / "contents.pak",
                        mod_destination,
                    )
                    try:
                        run(cmd)
                    except Exception as e:
                        # print(e)
                        count_errorred += 1
                        error_list.append(mod_id)
                    else:
                        count_unpacked += 1
                else:
                    print("    {}Skipping{}, missing file: {}".format(
                        YELLOW, RESET_ALL, (fn / "contents.pak")))
                    count_skipped += 1

    print()
    print(("{}Done!{} {} mods unpacked, {} skipped, and {} errorred.".format(
        GREEN, RESET_ALL, count_unpacked, count_skipped, count_errorred)))
    if error_list:
        print("{}Errors{}: {}".format(YELLOW, RESET_ALL,
                                      ", ".join(error_list)))
Esempio n. 18
0
def copy_mods_to_server(
    ctx,
    source=SB_STEAM_MODS_DIR,
    destination=None,
    override_existing=False,
    skip_existing=False,
    update_existing=False,
    verbose=False,
    mods=None,
):
    """Copy and 'flat file' steam mods to server mod directory."""
    text.title("Copy and 'flat file' steam mods to server mod directory.")

    count_copied = 0
    count_updated = 0
    count_skipped = 0
    count_missing = 0
    count_errorred = 0
    missing_list = []
    error_list = []

    source = Path(source)
    # check source file
    if source.exists():
        print("Steam Mods: {}FOUND{}!".format(GREEN, RESET_ALL))
    else:
        print("Steam Mods: {}MISSING{}".format(RED, RESET_ALL))
        print("Exiting...")
        sys.exit(1)

    if destination:
        destination = Path(destination)
    else:
        print("Destination: {}UNDEFINED{}".format(RED, RESET_ALL))
        print("Exiting...")
        sys.exit(1)

    # check destination folder
    if destination.exists():
        # test if folder is empty
        if list(destination.rglob("*")):
            print("Destination Folder: {}Exists, Not Empty{}".format(
                YELLOW, RESET_ALL))
            print("    {}".format(destination.resolve()))
            ans = text.query_yes_no("    Empty Folder?", default="no")
            if ans == text.Answers.YES:
                winshell.delete_file(destination.rglob("*"), silent=True)
        else:
            print("Destination Folder: {}Exists, Empty{}!".format(
                GREEN, RESET_ALL))
    else:
        print("Destination Folder: {}MISSING{}".format(YELLOW, RESET_ALL))
        ans = text.query_yes_no("    Create?")
        if ans == text.Answers.YES:
            destination.mkdir(parents=True)
        else:
            print("Exiting...")
            sys.exit(1)

    if not mods:
        if (destination / "mods.txt").exists():
            with (destination / "mods.txt").open() as f:
                # drop everything after '#'
                mods = [line.split("#", 1)[0].strip() for line in f]
                # remove empty lines
                mods = [line for line in mods if line]
            print("Using 'mods.txt' in destination folder.")
        else:
            print(
                "{}Provide a list of the steam IDs of the mods you want to copy{}"
                .format(RED, RESET_ALL))
            print("Exiting...")
            sys.exit(1)

    print("Coping...")
    for fn in source.iterdir():
        if fn.is_dir() and (fn.name in mods or mods[0].lower() == "all"):
            mod_source = fn / "contents.pak"
            if not mod_source.exists():
                print(
                    f"{YELLOW}Mod {mod_id} in non-typical format. Skipping.{RESET_ALL}"
                )
                count_skipped += 1
                continue

            mod_id = fn.name
            mod_destination = destination / f"{mod_id}.pak"
            skip_this = False
            override_this = False

            if mod_destination.exists():
                if update_existing:
                    # last modified time
                    source_mtime = mod_source.stat().st_mtime
                    destination_mtime = mod_destination.stat().st_mtime

                    if source_mtime > destination_mtime:
                        override_this = True
                        count_updated += 1

                if not override_existing and not skip_existing:
                    ans = text.query_yes_no_all_none(
                        ("Destination file for "
                         "mod {} exists. Overwrite?".format(mod_id)),
                        default="none",
                    )
                    if ans == text.Answers.YES:
                        override_this = True
                    elif ans == text.Answers.NO:
                        skip_this = True
                    elif ans == text.Answers.ALL:
                        override_existing = True
                        override_this = True
                    elif ans == text.Answers.NONE:
                        skip_existing = True
                        skip_this = True

                if override_this or override_existing:
                    winshell.delete_file(str(mod_destination))
                else:
                    skip_this = True

            # the actual unpacking!
            if skip_this:
                if verbose:
                    print("    {}Skipping{} {}...".format(
                        YELLOW, RESET_ALL, mod_id))
                count_skipped += 1
            else:
                winshell.copy_file(str(mod_source), str(mod_destination))
                count_copied += 1

    print("Check for completion...")
    for mod_id in mods:
        mod_destination = destination / f"{mod_id}.pak"
        if not mod_destination.exists():
            missing_list.append(mod_id)
            count_missing += 1

    print()
    print((
        "{}Done!{} {} mods copied, {} updated, {} skipped, {} missing, and {} errorred."
        .format(
            GREEN,
            RESET_ALL,
            count_copied,
            count_updated,
            count_skipped,
            count_missing,
            count_errorred,
        )))
    if missing_list:
        print("{}Missing from source{}: {}".format(YELLOW, RESET_ALL,
                                                   ", ".join(missing_list)))
    if error_list:
        print("{}Errors{}: {}".format(YELLOW, RESET_ALL,
                                      ", ".join(error_list)))
Esempio n. 19
0
 def delShortcutFromStartUp(self):
     self._waitAction.emit(waitGif)
     defile = os.path.join(winshell.startup(), 'connor.lnk')
     winshell.delete_file(defile)
Esempio n. 20
0
import sys, os, glob, re, winshell


def keepit(fn, words=['fr_', 'de_', 'en_', 'us_', 'pt_', 'pl_', 'uk_']):
    result = False
    for k in words:
        if k.lower() in os.path.basename(fn).lower():
            result = True
            break
    return result


for fn in glob.glob(r'lib\site-packages\babel\locale-data\*'):
    if not keepit(fn):
        os.unlink(fn)

for fn in glob.glob(r'lib\site-packages\pytz\zoneinfo\*'):
    if not keepit(fn, [
            'europe', 'etc', 'us', 'gb', 'portugal', 'france', 'cet', 'est',
            'gmt', 'met', 'poland', 'utc', 'zone', 'universal', 'factory'
    ]):
        if os.path.isdir(os.path.abspath(fn)):
            print('delete %s' % fn)
            winshell.delete_file(os.path.abspath(fn), no_confirm=True)
        else:
            os.unlink(fn)

for dirfn in []:
    if os.path.isdir(os.path.abspath(dirfn)):
        winshell.delete_file(os.path.abspath(dirfn), no_confirm=True)
Esempio n. 21
0
def main():
    config_file = "settings.ini"
    # init a configuration instance
    evergreen = configuration(CONFIG_FILE_NAME)
    settings_instance = evergreen.open_instance()
    # write the metadata
    evergreen.write_meta_data(settings_instance, CURRENT_DATE_STR, CURRENT_TIME_STR)
    # check if config options are all present
    settings_required = [
        ['directories', 'game_dir'],
        ['directories', 'makepbo_dir'],
        ['directories', 'repo_dir'],
        ['directories', 'mod_dev_dir'],
        ['paths', 'mission_path'],
        ['paths', 'server_config'],
        ['settings', 'profile_name'],
        ['settings', 'mod_name'],
        ['settings', 'mod_container_name'],
        ['settings', 'arma_exe'],
        ['settings', 'arma_server_exe'],
        ['settings', 'arma_server_pass'],
        ['settings', 'misc_client_params'],
        ['settings', 'launch_dedi']
    ]
    for section, option in settings_required:
        evergreen.check_value(settings_instance, section, option)
    # set global variables
    game_directory = evergreen.return_value(settings_instance, 'directories', 'game_dir')
    makepbo_dir = evergreen.return_value(settings_instance, 'directories', 'makepbo_dir')
    mod_repository_directory = evergreen.return_value(settings_instance, 'directories', 'repo_dir')
    mod_development_directory = evergreen.return_value(settings_instance, 'directories', 'mod_dev_dir')
    mission_path = evergreen.return_value(settings_instance, 'paths', 'mission_path')
    server_config_path = evergreen.return_value(settings_instance, 'paths', 'server_config')
    profile_name = evergreen.return_value(settings_instance, 'settings', 'profile_name')
    mod_name = evergreen.return_value(settings_instance, 'settings', 'mod_name')
    mod_container_name = evergreen.return_value(settings_instance, 'settings', 'mod_container_name')
    executable_name = evergreen.return_value(settings_instance, 'settings', 'arma_exe')
    server_executable_name = evergreen.return_value(settings_instance, 'settings', 'arma_server_exe')
    server_password = evergreen.return_value(settings_instance, 'settings', 'arma_server_pass')
    misc_client_params = evergreen.return_value(settings_instance, 'settings', 'misc_client_params')
    launch_dedicated_server = evergreen.return_value(settings_instance, 'settings', 'launch_dedi')
    # is makepbo present?
    print('Checking for MakePBO')
    # check in the path list
    path_list = (os.environ['PATH']).split(';')
    print_list('PATH list:', path_list)
    if makepbo_dir in path_list:
        print('MakePBO is present in the PATH list')
    else:
        print('MakePBO is not present. Install it!')
        return -1
    # setup the pbo name
    pbo_file = mod_name + ".pbo"
    # remove the old pbo
    print(r'Checking the mod directory for the pbo: {}'.format(pbo_file))
    pbo_dir = os.path.join(mod_repository_directory, mod_container_name, 'addons')
    pbo_dir_contents = os.listdir(pbo_dir)
    pbo_path = os.path.join(pbo_dir, pbo_file)
    print_list('Current mods in the mod container folder:', pbo_dir_contents)
    if pbo_file in pbo_dir_contents:
        print(r'Mod found at the path: {}'.format(pbo_path))
        print('The old m')
        winshell.delete_file(pbo_path, no_confirm=True)
    else:
        print('There is no old version of the mod in the repository')
    # pack the pbo using makepbo
    try:
        subprocess.check_output(['MakePBO', '-P', '-A', '-L', '-N', '-G', mod_development_directory, pbo_dir], stderr=subprocess.STDOUT)
    except Exception as e:
        print('MakePBO broke! It raised the exception: {}'.format(e))
        return -1
    else:
        print('New PBO successfully packaged.')
    # produce a list of mods to run from the whole contents of the repository
    repo_contents = os.listdir(mod_repository_directory)
    if len(repo_contents) > 0:
        addon_params_string = ''
        addon_separator = ';'
        print('Building a list of addons to launch with arma')
        for addon in repo_contents:
            print('\tAdding: {} to the list of addons'.format(addon))
            addon_directory = os.path.join(mod_repository_directory, addon)
            addon_params_string += (addon_directory + addon_separator)
    else:
        print('There are no mods present inside the repository!')
        return -1
    executable_path = os.path.join(game_directory, executable_name)
    mods_used_parameter = '-mod=' + addon_params_string
    world_param = '-world=empty'
    profile_param = '-name=' + profile_name
    client_params = misc_client_params.split(' ')
    client_start_arguments = [executable_path, profile_param, mods_used_parameter, world_param]
    client_start_arguments.extend(client_params)
    if int(launch_dedicated_server) == 1:
        server_executable_path = os.path.join(game_directory, server_executable_name)
        config_param = '-config=' + server_config_path
        server_start_arguments = [server_executable_path, config_param, mods_used_parameter]
        print_list('Starting ArmA dedicated server using the following parameters:', server_start_arguments)
        try:
            process = subprocess.Popen(server_start_arguments)
        except subprocess.CalledProcessError as error:
            print("ArmA 3 Server didn't manage to start!")
            output = process.communicate()[0]
            print(process.returncode)
        else:
            print("ArmA 3 Dedicated Server successfully started")
            pause('Waiting for the server to start ', SERVER_STARTUP_DELAY)
            client_start_arguments.extend(['-connect=127.0.0.1', '-password='******'Starting ArmA in editor')
        client_start_arguments.append(mission_path)
    print_list('Starting ArmA client using the following parameters:', client_start_arguments)
    try:
        process = subprocess.Popen(client_start_arguments)
    except subprocess.CalledProcessError as error:
        print("ArmA 3 didn't manage to start!")
        output = process.communicate()[0]
        print(process.returncode)
    else:
        print("ArmA 3 successfully started")
Esempio n. 22
0
def shred(mode='Basic', path=''):
    """
    The Function shreds files in order to protect the user's identity.
    :param mode: the shredding mode: Basic, Safe, Complete
    :param path: the path to be shredded: Recycle Bin or Temporary files
    :return: None
    """
    start_time = time.perf_counter()
    failed_shredding = list()
    if mode == 'Basic':
        repeat = 1
    elif mode == 'Safe':
        repeat = 5
    else:  # mode == 'Complete':
        repeat = 10

    if path == 'Let Me Choose':
        path = random.choice(['Recycle Bin', 'Temporary Files'])

    executed = False  # An auxiliary boolean variable
    if path == 'Recycle Bin':
        object_list = list(winshell.recycle_bin())
        if object_list:  # if list is not empty
            print(f'Starting Shredding process at {path}\n')
            executed = True
            print(f'We are getting ready to shred {len(object_list)} files')
            time.sleep(1)
            for index, file_path in enumerate(object_list):
                for _ in range(repeat):
                    try:
                        success = False
                        file_path = '\\'.join(
                            file_path.original_filename().split('\\')
                        )  # adding double slash (\\) in the file_path
                        # undeleting the selected file
                        winshell.undelete(file_path.original_filename())
                        if not os.path.isdir(file_path):  # is file
                            success = shred_file(file_path)
                            if not success:  # if didn't succeed shredding the file
                                failed_shredding.append(file_path)
                        # deleting the selected file again
                        winshell.delete_file(file_path.original_filename())
                    except:
                        pass
                if (index + 1) == (len(object_list)):  # last file
                    sys.stdout.write(
                        f'\rShredding ({int(((index + 1) / len(object_list)) * 100)}%): {basename(file_path)}last'
                    )
                else:
                    sys.stdout.write(
                        f'\rShredding ({int(((index + 1) / len(object_list)) * 100)}%): {basename(file_path)}'
                    )

            # Emptying recycle bin.
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=False)
            print('\nShredding Report:')
            print(
                f'Successfully shred: {len(object_list) - len(failed_shredding)} '
                f'out of {len(object_list)} Files || Failed to shred : '
                f'{len(failed_shredding)} files')
            finish_time = time.perf_counter()
        else:
            print('There are no items in the Recycle Bin to be shredded\n')

    elif path == 'Temporary Files':
        directory_path = r'c:\windows\temp'
        object_list = os.listdir(directory_path)
        files_list = []
        if object_list:
            while object_list:
                for file in object_list:
                    file_path = directory_path + file
                    if file_path not in files_list:
                        files_list.append(file_path)
                    object_list.remove(file)
            print(f'Starting Shredding process at {path}\n')
            executed = True
            print(f'We are getting ready to shred {len(files_list)} files')
            time.sleep(1)
            for index, file_path in enumerate(files_list):
                if (index + 1) == len(object_list):  # last file
                    sys.stdout.write(
                        f'\rShredding ({int((index / len(files_list)) * 100)}%): {basename(file_path)}last'
                    )
                else:
                    sys.stdout.write(
                        f'\rShredding ({int((index / len(files_list)) * 100)}%): {basename(file_path)}'
                    )
                for _ in range(repeat):
                    try:
                        if not os.path.isdir(file_path):  # is file
                            success = shred_file(file_path)
                            if not success:  # if didn't succeed shredding the file
                                failed_shredding.append(file_path)
                    except:
                        pass

            for file in files_list:
                os.remove(file)
            process = subprocess.Popen(
                'del /S /Q /F %s\\*.*' % directory_path,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  # deleting all temporary files
            process.communicate()
            finish_time = time.perf_counter()
            print('\n\nShredding Report:')
            print(
                f'Successfully shredded: {len(files_list) - len(failed_shredding)} '
                f'out of {len(files_list)} Files || Failed to shred : '
                f'{len(failed_shredding)} files. Deleted: {len(files_list)}')

    if executed:
        print(
            f'Shredding has been finished in {progress_duration(finish_time - start_time)}'
        )
        from Graphic_Interface import display_notifications
        display_notifications('Shredding process has finished.')
    else:
        print(
            f"""We didn't shred any files since we couldn't find any in {path} """
        )
Esempio n. 23
0
    def FileUI(self, MainWindow, cont, selected, main, lst):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1200, 700)
        MainWindow.setMinimumSize(QtCore.QSize(1200, 700))
        MainWindow.setMaximumSize(QtCore.QSize(1200, 700))
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1200, 100))
        self.label.setStyleSheet(
            "background-image: url(:/header/images/Untitled-1.png);")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(900, 269, 300, 411))
        self.label_2.setStyleSheet("\n"
                                   "background-color: rgb(212, 212, 212);")
        self.label_2.setObjectName("label_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(940, 120, 200, 50))
        self.pushButton.setStyleSheet(
            "background-image: url(:/header/images/btn-1_3.png);")
        self.pushButton.setText("")
        self.pushButton.setCheckable(False)
        self.pushButton.setAutoDefault(False)
        self.pushButton.setDefault(False)
        self.pushButton.setFlat(True)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(940, 190, 200, 50))
        self.pushButton_2.setStyleSheet(
            "background-image: url(:/Buttons/images/btn-2_2.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setFlat(True)
        self.pushButton_2.setObjectName("pushButton_2")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(310, 700, 118, 3))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setGeometry(QtCore.QRect(900, 260, 301, 16))
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(0, 100, 901, 71))
        self.label_5.setStyleSheet(
            "\n"
            "background-image: url(:/pic/images/patti_5.png);")
        self.label_5.setText("")
        self.label_5.setObjectName("label_5")
        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setGeometry(QtCore.QRect(10, 118, 121, 41))
        self.pushButton_3.setStyleSheet(
            "background-image: url(:/Buttons/images/back_3.png);")
        self.pushButton_3.setText("")
        self.pushButton_3.setFlat(True)
        self.pushButton_3.setObjectName("pushButton_3")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(140, 118, 751, 41))
        self.label_6.setStyleSheet("color: rgb(255, 255, 255);\n"
                                   "font: 63 14pt \"Segoe UI Semibold\";")
        self.label_6.setObjectName("label_6")
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(0, 170, 900, 520))
        self.textEdit.setObjectName("textEdit")
        self.label_5.raise_()
        self.label.raise_()
        self.label_2.raise_()
        self.pushButton.raise_()
        self.pushButton_2.raise_()
        self.line.raise_()
        self.line_2.raise_()
        self.pushButton_3.raise_()
        self.label_6.raise_()
        self.textEdit.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1200, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.textEdit.setReadOnly(True)

        # self.pushButton_2.clicked.connect(self.RestoreButton)
        # self.pushButton.clicked.connect(self.DeleteButton)

        try:
            self.lst = lst
            if cont == None:
                winshell.undelete(selected.obj.original_filename())
                file = open(selected.sahiPath, "r")
                content = file.read()
                file.close()
                winshell.delete_file(selected.obj.original_filename())
                self.textEdit.setPlainText(content)
            else:
                _translate = QtCore.QCoreApplication.translate
                self.label_6.setText(
                    _translate(
                        "MainWindow",
                        "Go Back to Main Window before closing the program, unless the folder will be Restored"
                    ))
                self.textEdit.setPlainText(cont)
        except:
            self.msgBox("ERROR", "Can't Open This Type of File")
        if main == True:
            self.pushButton_3.clicked.connect(self.goBack)
        else:

            self.pushButton_3.clicked.connect(self.goCustomBack)
Esempio n. 24
0
    def setupUi(self, MainWindow, c):
        self.currentItem = None
        self.currentItemCheck = False
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1200, 700)
        MainWindow.setMinimumSize(QtCore.QSize(1200, 700))
        MainWindow.setMaximumSize(QtCore.QSize(1200, 700))
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(0, 99, 900, 581))
        self.tableWidget.setObjectName("tableWidget")
        #         self.tableWidget.setColumnCount(1)
        # #         self.tableWidget.setRowCount(1)
        #-----------------------------------columns------------------
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        #-----------------------------------rows-------------------
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        #---------------------------------------------------------

        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 0, item)
        self.tableWidget.horizontalHeader().setVisible(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(220)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(150)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1200, 100))
        self.label.setStyleSheet(
            "background-image: url(:/header/images/Untitled-1.png);")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(900, 269, 300, 411))
        self.label_2.setStyleSheet(
            "\n"
            "background-color: rgb(212, 212, 212); font: 63 10pt \"Segoe UI Semibold\";"
        )
        self.label_2.setObjectName("label_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(940, 120, 200, 50))
        self.pushButton.setStyleSheet(
            "background-image: url(:/header/images/btn-1_3.png);")
        self.pushButton.setText("")
        self.pushButton.setCheckable(False)
        self.pushButton.setAutoDefault(False)
        self.pushButton.setDefault(False)
        self.pushButton.setFlat(True)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(940, 190, 200, 50))
        self.pushButton_2.setStyleSheet(
            "background-image: url(:/Buttons/images/btn-2_2.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setFlat(True)
        self.pushButton_2.setObjectName("pushButton_2")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(310, 700, 118, 3))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setGeometry(QtCore.QRect(900, 260, 301, 16))
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")

        self.pushButton_2.clicked.connect(self.RestoreButton)
        self.pushButton.clicked.connect(self.DeleteButton)

        #------------------------------------------------------
        # self.verticalLayoutWidget.hide()
        # self.verticalLayoutWidget_2.hide()
        self.tableWidget.cellClicked.connect(self.cellClicked)
        self.tableWidget.cellDoubleClicked.connect(self.cellDClicked)
        #-----------------------------------------------------
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1200, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.label_2.setWordWrap(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)

        if c == True:
            #---------------------------------------------------------Listing all the files from Trash---------------------

            r = list(winshell.recycle_bin())
            self.sizeOfList = len(r)
            if self.sizeOfList >= 4:
                self.tableWidget.setColumnCount(4)
                self.tableWidget.setRowCount(math.ceil(self.sizeOfList / 4))

            else:
                self.tableWidget.setColumnCount(self.sizeOfList)
                self.tableWidget.setRowCount(1)

            class DeletedObject:
                def __init__(self, obj, typeOfObj, name, sahiPath, size, addOn,
                             row, col):
                    self.obj = obj
                    self.typeOfObj = typeOfObj
                    self.name = name
                    self.sahiPath = sahiPath
                    self.size = size
                    self.addOn = addOn
                    self.row = row
                    self.col = col

            self.dictOfObjs = {}
            row = 0
            col = 0

            for i, v in enumerate(r):
                addOn = []
                col = i % 4
                if i != 0 and col == 0:
                    row += 1
                total = v.original_filename().split('\\')
                okPath = "\\\\".join(total)
                v.undelete()
                if os.path.isdir(okPath):
                    typee = "Folder"
                    size = self.get_dir_size(okPath)
                    addOn.append([
                        file for file in os.listdir(okPath)
                        if os.path.isdir(okPath + "\\" + file)
                    ])
                    addOn.append([
                        file for file in os.listdir(okPath)
                        if os.path.isfile(okPath + "\\" + file)
                    ])

                    self.FolderCreator(total[-1], row, col)
                elif os.path.isfile(okPath):
                    typee = "File"
                    size = os.path.getsize(okPath)
                    self.FileCreator(total[-1], row, col)
                winshell.delete_file(okPath)
                self.dictOfObjs[i] = DeletedObject(v, typee, total[-1], okPath,
                                                   size, addOn, row, col)

                # item = QTableWidgetItem(str(total[-1]+"|"+typee))
                # item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                # self.tableWidget.setItem(row,col,item )
        elif c == False:
            if self.sizeOfList >= 4:
                self.tableWidget.setColumnCount(4)
                self.tableWidget.setRowCount(math.ceil(self.sizeOfList / 4))

            else:
                self.tableWidget.setColumnCount(self.sizeOfList)
                self.tableWidget.setRowCount(1)
            for k, v in self.dictOfObjs.items():
                if v.typeOfObj == "File":
                    self.FileCreator(v.name, v.row, v.col)
                elif v.typeOfObj == "Folder":
                    self.FolderCreator(v.name, v.row, v.col)
Esempio n. 25
0
# Licence:     <your licence>
#-------------------------------------------------------------------------------

import sys,os,glob,re,winshell

def keepit(fn,words=['fr_','de_','en_','us_','pt_','pl_','uk_']):
    result = False
    for k in words:
        if k.lower() in os.path.basename(fn).lower():
            result = True
            break
    return result

for fn in glob.glob(r'lib\site-packages\babel\locale-data\*'):
    if not keepit(fn):
        os.unlink(fn)

for fn in glob.glob(r'lib\site-packages\pytz\zoneinfo\*'):
    if not keepit(fn,['europe','etc','us','gb','portugal','france','cet','est','gmt','met','poland','utc','zone','universal','factory']):
        if os.path.isdir(os.path.abspath(fn)):
            print('delete %s' %fn)
            winshell.delete_file(os.path.abspath(fn),no_confirm=True)
        else:
            os.unlink(fn)

for dirfn in [
        ]:
    if os.path.isdir(os.path.abspath(dirfn)):
        winshell.delete_file(os.path.abspath(dirfn),no_confirm=True)

Esempio n. 26
0
 def test_simple_delete(self):
     from_filepath, to_filepath = self.tempfiles(
         create_from=True, create_to=False
     )
     winshell.delete_file(from_filepath, no_confirm=True)
     self.assertFalse(os.path.exists(from_filepath))
Esempio n. 27
0
def main():
    colorama.init()
    print("{} {}".format(TITLE, VERSION))
    if VERBOSE:
        print("\a", end="")
        print("Python {}".format(sys.version))
        print("Command '{}'".format(sys.argv[0]))
        print("Arguments {}".format(sys.argv[1:]))
        print("Executed {}".format(now()))
        start = time.time()
    
    parser = argparse.ArgumentParser(description="Finds and deletes duplicate files located under top `directory`.")
    parser.add_argument("directory", nargs="?", default=os.getcwd(), help="set top directory to clean up [%(default)s]")
    parser.add_argument("-a", "--action", choices=['summary', 'list', 'delete'], default='summary', help="set action to perform on found items [%(default)s]")
    parser.add_argument("-m", "--match", nargs="+", choices=['name', 'time', 'size', 'contents'], default=['name', 'time', 'size', 'contents'], help="set criteria to detect duplicate items ["+" ".join(['name', 'time', 'size', 'contents'])+"]")
    parser.add_argument("-t", "--type", choices=['file', 'directory'], default='file', help="set type of items to be searched for and deleted [%(default)s]")
    parser.add_argument("-s", "--silent", action="store_true", default=False, help="suppress progress messages [false]")
    parser.add_argument("-w", "--width", type=int, choices=range(MIN_WIDTH,MAX_WIDTH+1), default=WIDTH, metavar="<{},{}>".format(MIN_WIDTH,MAX_WIDTH), help="set console width for progress indicator [%(default)s]")
    arguments = parser.parse_args()
    directory = arguments.directory
    action = arguments.action
    match = arguments.match
    type = arguments.type
    silent = arguments.silent
    width = arguments.width
    types = {'sing.': "file", 'plur.': "files"} if type == 'file' else {'sing.': "directory", 'plur.': "directories"}
    
    if not silent:
        print("Scanning {} under {}".format(types['plur.'], directory))
        BACKTRACK = ("\r" if width < MAX_WIDTH else ANSI_CURSOR_UP) if sys.stdout.isatty() else "\n"
    started = time.time()
    numDirs, numFiles = (0,) * 2
    class Kind(enum.Enum): master = 0; copy = 1
    Item = collections.namedtuple('Item', ['location', 'name', 'time', 'size', 'group', 'kind'])
    items = []
    for path, dirs, files in os.walk(directory):
        if not silent:
            print("Scanning {: <{}}".format(printable(path[len(directory):] if path[len(directory):] != "" else "\\.", width-9), width-9), end=BACKTRACK)
        dirs  = list(filter(os.path.isdir,  map(lambda dir:  os.path.abspath(os.path.join(path, dir)),  dirs)))
        files = list(filter(os.path.isfile, map(lambda file: os.path.abspath(os.path.join(path, file)), files)))
        numDirs  += len(dirs)
        numFiles += len(files)
        for element in files if type == 'file' else dirs:
            location, name = os.path.split(element)
            mtime = os.path.getmtime(element)
            size = os.path.getsize(element)
            items.append(Item(location=location, name=name, time=mtime, size=size, group=None, kind=None))
    if not silent:
        if sys.stdout.isatty():
            print("         {: <{}}".format("", width-9), end=BACKTRACK)
        seconds = max(1, round(time.time() - started))
        dirRate  = round(numDirs  / seconds, 1)
        fileRate = round(numFiles / seconds, 1)
        print("Found {} director{} with {} file{} in {} second{} ({} director{}/s, {} file{}/s)".format(
            grouped(numDirs),  "y" if numDirs  == 1 else "ies",
            grouped(numFiles), ""  if numFiles == 1 else "s",
            grouped(seconds),  ""  if seconds  == 1 else "s",
            grouped(dirRate),  "y" if dirRate  == 1 else "ies",
            grouped(fileRate), ""  if fileRate == 1 else "s"))
    
    if not silent:
        print("Sorting and grouping {}".format(types['plur.']))
    items.sort(key=lambda item:
        ((item.name,) if 'name' in match else ()) +
        ((item.time,) if 'time' in match else ()) +
        ((item.size,) if 'size' in match else ()) +
        ((item.name,) if 'name' not in match else ()) +
        ((item.time,) if 'time' not in match else ()) +
        ((item.size,) if 'size' not in match else ()) +
        ((item.location,)))
    numUniqs, numDups, numGroups, maxExtra, sizeUniqs, sizeDups = (0,) * 6
    if len(items) > 0:
        numUniqs = 1
        sizeUniqs = items[0].size
        extra = 0
        items[0] = items[0]._replace(group=0, kind=Kind.master)
        prevItem = items[0]
        for index, item in enumerate(items[1:]):
            if ('name' not in match or item.name == prevItem.name) and \
               ('time' not in match or item.time == prevItem.time) and \
               ('size' not in match or item.size == prevItem.size):
                numDups += 1
                if extra == 0:
                    numGroups += 1
                extra += 1
                maxExtra = max(extra, maxExtra)
                sizeDups += item.size
            else:
                numUniqs += 1
                extra = 0
                sizeUniqs += item.size
            items[1+index] = item._replace(group=0 if extra == 0 else numGroups, kind=Kind.master if extra == 0 else Kind.copy)
            prevItem = item
    assert numUniqs + numDups == len(items)
    if not silent:
        print("Found {} total {} ({}), {} unique {} ({}), {} duplicate {} ({}), {} group{} with repeats, max {} extra cop{} in a group".format(
            grouped(len(items)), types['sing.'  if len(items) == 1 else 'plur.'], gazillion(sizeUniqs+sizeDups),
            grouped(numUniqs),   types['sing.'  if numUniqs   == 1 else 'plur.'], gazillion(sizeUniqs),
            grouped(numDups),    types['sing.'  if numDups    == 1 else 'plur.'], gazillion(sizeDups),
            grouped(numGroups),  ""  if numGroups  == 1 else "s",
            grouped(maxExtra),   "y" if maxExtra   == 1 else "ies"))
    
    if 'contents' in match:
        if not silent:
            print("Matching {} contents".format(types['sing.']))
        begin = 0 # first item in pre-qualified group
        uniq = 1
        while begin < len(items):
            if not silent:
                print("Matching {: <{}}".format("{} of {}".format(grouped(uniq), grouped(numUniqs)), width-9), end=BACKTRACK)
            end = begin # last item in pre-qualified group
            while end < len(items)-1 and items[end+1].kind == Kind.copy:
                end += 1
            if begin < end:
                assert items[begin].kind == Kind.master
                assert items[end].kind == Kind.copy
                first = begin # first item in confirmed group
                while first <= end:
                    last = first # last item in confirmed group
                    while last <= end-1 and filecmp.cmp(
                        os.path.join(items[first].location, items[first].name),
                        os.path.join(items[last+1].location, items[last+1].name),
                        shallow=False):
                        last += 1
                    items[first] = items[first]._replace(kind=Kind.master)
                    for dup in range(first+1, last+1):
                        items[dup] = items[dup]._replace(kind=Kind.copy)
                    first = last + 1
            begin = end + 1
            uniq += 1
        if not silent:
            if sys.stdout.isatty():
                print("         {: <{}}".format("", width-9), end=BACKTRACK)
        numUniqs, numDups, numGroups, maxExtra, sizeUniqs, sizeDups = (0,) * 6
        for index, item in enumerate(items):
            if item.kind == Kind.master:
                numUniqs += 1
                sizeUniqs += item.size
                extra = 0
                items[index] = item._replace(group=0)
            else:
                assert item.kind == Kind.copy
                numDups +=1
                sizeDups += item.size
                if extra == 0:
                    numGroups += 1
                extra += 1
                maxExtra = max(extra, maxExtra)
                items[index] = item._replace(group=numGroups)
        assert numUniqs + numDups == len(items)
        if not silent:
            print("Found {} total {} ({}), {} unique {} ({}), {} duplicate {} ({}), {} group{} with repeats, max {} extra cop{} in a group".format(
                grouped(len(items)), types['sing.'  if len(items) == 1 else 'plur.'], gazillion(sizeUniqs+sizeDups),
                grouped(numUniqs),   types['sing.'  if numUniqs   == 1 else 'plur.'], gazillion(sizeUniqs),
                grouped(numDups),    types['sing.'  if numDups    == 1 else 'plur.'], gazillion(sizeDups),
                grouped(numGroups),  ""  if numGroups  == 1 else "s",
                grouped(maxExtra),   "y" if maxExtra   == 1 else "ies"))
    
    if action in ['summary', 'list', 'delete']:
        print(tabulated([
            ["Directory", directory],
            ["Full path", os.path.abspath(directory)]],
            rowSeparator = [True] * 2),
            end="")
        print(tabulated([
            ["",            "Count"],
            ["Directories", grouped(numDirs)],
            ["Files",       grouped(numFiles)]],
            numHeaderRows = 1,
            columnAlign = ['left'] + ['right'] * 1,
            rowSeparator = [True] * 3),
            end="")
        print(tabulated([
            ["Files" if type == "file" else "Directories", "Count",                    "Size",                        "Percent"],
            ["Total",                                      grouped(numUniqs+numDups),  gazillion(sizeUniqs+sizeDups), "100.0%"],
            ["Unique",                                     grouped(numUniqs),          gazillion(sizeUniqs),          "{:.1%}".format(sizeUniqs/(sizeUniqs+sizeDups) if sizeUniqs+sizeDups != 0 else 0)],
            ["Duplicate",                                  grouped(numDups),           gazillion(sizeDups),           "{:.1%}".format(sizeDups/(sizeUniqs+sizeDups) if sizeUniqs+sizeDups != 0 else 0)],
            ["Groups",                                     grouped(numGroups),         "-",                           "-"],
            ["Max extra",                                  grouped(maxExtra),          "-",                           "-"]],
            numHeaderRows = 1,
            columnAlign = ['left'] + ['right'] * 3,
            rowSeparator = [True] * 6),
            end="")
        Location = collections.namedtuple('Location', ['masters', 'copies'])
        location = {}
        for item in items:
            if item.kind == Kind.copy:
                if prevItem.kind == Kind.master:
                    assert prevItem.group == 0
                    if prevItem.location not in location.keys():
                        location[prevItem.location] = Location(masters=0, copies=0)
                    location[prevItem.location] = location[prevItem.location]._replace(masters=location[prevItem.location].masters+1)
                if item.location not in location.keys():
                    location[item.location] = Location(masters=0, copies=0)
                location[item.location] = location[item.location]._replace(copies=location[item.location].copies+1)
            prevItem = item
        data = [["Location", "Master count", "Copy count"]]
        for path in sorted(location.keys(), key=lambda path: (-location[path].masters, -location[path].copies, path)):
            data.append([printable(path), grouped(location[path].masters), grouped(location[path].copies)])
        print(tabulated(data,
            numHeaderRows = 1,
            columnAlign = ['left'] + ['right'] * 2,
            rowSeparator = [True]),
            end="")
    if action in ['list', 'delete']:
        data = [["Group", "Name", "Location", "Time", "Size"]]
        groupEnd = [True]
        for item in items:
            if item.kind == Kind.copy:
                if prevItem.kind == Kind.master:
                    assert prevItem.group == 0
                    groupEnd[-1] = True
                    data.append(["Master", printable(prevItem.name), printable(prevItem.location), timestamp(prevItem.time), gazillion(prevItem.size)])
                    groupEnd.append(False)
                    if action == 'delete':
                        masterName     = prevItem.name
                        masterLocation = prevItem.location
                        master = os.path.join(masterLocation, masterName)
                data.append([grouped(item.group), printable(item.name), printable(item.location), timestamp(item.time), gazillion(item.size)])
                groupEnd.append(False)
                if action == 'delete':
                    copyName     = item.name
                    copyLocation = item.location
                    copy = os.path.join(copyLocation, copyName)
                    link = copy + '.link'
                    try:
                        with open(link, 'w') as link:
                            link.write(master) # Precaution #1: Create a link to the master.
                    except:
                        try:
                            print('Failed to create link to master')
                        except:
                            pass
                    else:
                        winshell.delete_file(copy, no_confirm=True) # Precaution #2: Move copy to the recycle bin.
                        try:
                            print('Deleted "', copy, '"')
                        except:
                            pass
            prevItem = item
        groupEnd[-1] = True
        print(tabulated(data,
            numHeaderRows = 1,
            columnAlign = ['right'] + ['left'] * 2 + ['right'] * 2,
            rowSeparator = groupEnd),
            end="")
    
    if VERBOSE:
        elapsed = time.time() - start
        seconds = round(elapsed)
        minutes, seconds = divmod(seconds, 60)
        hours, minutes = divmod(minutes, 60)
        days, hours = divmod(hours, 24)
        weeks, days = divmod(days, 7)
        print("Completed {}".format(now()))
        print("Elapsed {:d}w {:d}d {:d}h {:d}m {:d}s ({:,.3f}s)".format(weeks, days, hours, minutes, seconds, elapsed))
    print("\a", end="")
Esempio n. 28
0
# find version
version = 0
with open(join(SourceDir, "info.nut"), "r") as VersionFile:
    for line in VersionFile:
        if "GetVersion()" in line:
            version = line[line.find("return") + 6 : line.find(";")].strip()

# Create AI version
WmDOTVersion = "WmDOT-" + version
# LineCount = 0
TarFileName = join(OutputDir, WmDOTVersion + ".tar")
MyTarFile = tarfile.open(name=TarFileName, mode="w")
for File in os.listdir(SourceDir):
    if os.path.isfile(join(SourceDir, File)):
        if File.endswith(".nut"):
            MyTarFile.add(join(SourceDir, File), join(WmDOTVersion, File))
        elif File.endswith(".txt"):
            MyTarFile.add(join(SourceDir, File), join(WmDOTVersion, File))
        elif File.endswith(".md"):
            # create temp copy
            winshell.copy_file(join(SourceDir, File), File, rename_on_collision=False)
            for line in fileinput.input(File, inplace=1):
                # replace the characters escaped for dOxygen
                print(multiple_replace(line, *mdReplacements))
            MyTarFile.add(File, join(WmDOTVersion, File[:-3] + ".txt"))
            winshell.delete_file(File, no_confirm=True, allow_undo=False)
MyTarFile.close()

print("    " + WmDOTVersion + ".tar created!")
# print ("        " + str(LineCount) + " lines of code")
Esempio n. 29
0
#Requirements ---  pip install pypiwin32
#                  pip install winshell

import winshell
import os

try:
    winshell.recycle_bin().empty(confirm=True, show_progress=True,
                                 sound=True)  #empty Recycle Bin

    filepath = os.path.abspath("test.txt")
    with open(filepath, "w") as f:
        f.write("testfile1")

    winshell.delete_file(filepath)  #delete a file

    print(*winshell.recycle_bin().versions(filepath),
          sep="\n")  #versions of file in recycle bin

    winshell.undelete(filepath)  #recovers the latest recycled version

except Exception as e:
    print(str(e))
Esempio n. 30
0
def delete_shortcut_from_sendto(argv):
    target = argv
    s = path.basename(target)
    fname = path.splitext(s)[0]
    delfile = path.join(winshell.sendto(), fname + '.lnk')
    winshell.delete_file(delfile)
Esempio n. 31
0
def delete(sourcePath):
    winshell.delete_file(sourcePath, no_confirm=True)
Esempio n. 32
0
def delete(target, confirm=False, silent=False):
    """Deletes a file or folder."""
    winshell.delete_file(str(target), no_confirm=not confirm, silent=silent)
Esempio n. 33
0
def deletefile(filename):
    if not os.path.exists(filename):
        return True
    filepath = os.path.abspath(filename)
    winshell.delete_file(filepath)