def move(src, dst):
    print_with_script_name(f'Moved {src}')
    # ignore(src)
    try:
        shmove(f'{DOWNLOADS_PATH}/{src}', dst)
    except Exception as e:
        print_with_script_name(f'{src} caused {e.__class__}')
Esempio n. 2
0
def reorg(*search, ignore=None, purge=False, verbose=False, commit=False, **kwargs):
    """
    Move character files into the correct paths.

    Character files are moved so that their path matches the ideal path as
    closely as possible. No new directories are created.

    This function ignores tags not found in Character.KNOWN_TAGS.

    Args:
        search (list): Paths to search for character files. Items can be strings
            or lists of strings.
        ignore (list): Paths to ignore
        purge (bool): Whether empty directories should be deleted after all
            files have been moved.
        verbose (bool): Whether to print changes as they are made
        commit (bool): Whether to actually move files around
        prefs (Settings): Settings object to use. Uses internal settings by
            default.

    Returns:
        Result object. Openable will be empty.
    """
    prefs = kwargs.get('prefs', settings.InternalSettings())
    if not ignore:
        ignore = []
    ignore.extend(prefs.get_ignored_paths('reorg'))
    show_changes = verbose or not commit

    changelog = []

    base_path = prefs.get('paths.required.characters')
    if not path.exists(base_path):
        return result.FSError(errmsg="Cannot access '{}'".format(base_path))

    if show_changes:
        changelog.append("Move characters")
    for parsed_character in parser.get_characters(flatten(search), ignore):
        new_path = util.create_path_from_character(parsed_character, base_path=base_path)
        if path.normcase(path.normpath(new_path)) != path.normcase(path.normpath(path.dirname(parsed_character['path']))):
            if show_changes:
                changelog.append("* Move {} to {}".format(parsed_character['path'], new_path))
            if commit:
                try:
                    shmove(parsed_character['path'], new_path)
                except OSError as e:
                    if show_changes:
                        changelog.append("\t- dest path already exists; skipping")

    if purge:
        if show_changes:
            changelog.append("Purge empty directories")
        for empty_path in util.find_empty_dirs(base_path):
            if show_changes:
                changelog.append("* Remove empty directory {}".format(empty_path))
            if commit:
                rmdir(empty_path)

    return result.Success(printables=changelog)
Esempio n. 3
0
 def move_opted(file_from, file_to):
     if options.verbose:
         print file_from, '->', file_to
     if exists(file_to):
         warn("%s è già usato!" % file_to)
     else:
         if not options.test:
             shmove(file_from, file_to)
Esempio n. 4
0
def reorg(*search, ignore=None, purge=False, verbose=False, dry=False, **kwargs):
    """
    Move character files into the correct paths.

    Character files are moved so that their path matches the ideal path as
    closely as possible. No new directories are created.

    Args:
        search (list): Paths to search for character files. Items can be strings
            or lists of strings.
        ignore (list): Paths to ignore
        purge (bool): Whether empty directories should be deleted after all
            files have been moved.
        verbose (bool): Whether to print changes as they are made
        dry (bool): Whether to show the changes that would be made, but not
            enact them.
        prefs (Settings): Settings object to use. Uses internal settings by
            default.

    Returns:
        Result object. Openable will be empty.
    """
    prefs = kwargs.get('prefs', settings.InternalSettings())
    if not ignore:
        ignore = []
    ignore.extend(prefs.get('paths.ignore'))
    verbose = verbose or dry

    base_path = prefs.get('paths.characters')
    if not path.exists(base_path):
        return Result(False, errmsg="Cannot access '{}'".format(base_path), errcode=4)

    for parsed_character in parser.get_characters(flatten(search), ignore):
        new_path = create_path_from_character(parsed_character, target_path=base_path)
        if new_path != path.dirname(parsed_character['path']):
            if verbose:
                print("Moving {} to {}".format(parsed_character['path'], new_path))
            if not dry:
                shmove(parsed_character['path'], new_path)

    if purge:
        for empty_path in find_empty_dirs(base_path):
            if verbose:
                print("Removing empty directory {}".format(empty_path))
            if not dry:
                rmdir(empty_path)

    return Result(True)
 def move(self) -> str:
     destpath = self.dest
     if destpath != "" and os.path.isdir(destpath):
         try:
             shmove(self.path, os.path.join(destpath, self.name.get()))
             self.moved = True
             self.show = False
             self.guidata["frame"].configure(highlightbackground="green",
                                             highlightthickness=2)
             self.path = os.path.join(destpath, self.name.get())
             returnstr = ("Moved:" + self.name.get() + " -> " + destpath +
                          "\n")
             destpath = ""
             return returnstr
         except Exception as e:
             logging.error("Error moving: %s . File: %s", e,
                           self.name.get())
             self.guidata["frame"].configure(highlightbackground="red",
                                             highlightthickness=2)
             return ("Error moving: %s . File: %s", e, self.name.get())
Esempio n. 6
0
    def _move(file1, file2, overwrite=True, filetype1=None, filetype2=None):
        """
		Move a file
		@params:
			`file1`    : The source
			`file2`    : The destination
			`overwrite`: Overwrite the destination? Default: `True`
			`filetype1`: The file type of file1
			`filetype2`: The file type of file2
		@returns:
			`True` if succeed else `False`
		"""
        try:
            filetype1 = filetype1 or SafeFs._filetype(file1)
            filetype2 = filetype2 or SafeFs._filetype(file2)
            rel = SafeFs._filerel(file1, file2, filetype1, filetype2)

            if rel in [
                    SafeFs.FILES_DIFF_BOTHNOENT,
                    SafeFs.FILES_DIFF_NOENT1,
                    SafeFs.FILES_SAME_STRNOENT,
                    # I can't copy the source link to itself
                    SafeFs.FILES_SAME_BOTHLINKS1,
                    SafeFs.FILES_SAME_REAL2
            ]:
                return False
            elif rel in [
                    # assume file linked from the same file path
                    SafeFs.FILES_SAME_STRENT
            ]:
                return True
            else:
                # NOENTLINK may be removed somewhere else
                # if SafeFs._exists(file2, filetype2):
                if SafeFs._exists(file2):
                    if not overwrite or not SafeFs._remove(file2, filetype2):
                        return False
                shmove(file1, file2)
                return True
        except OSError:  # pragma: no cover
            return False
Esempio n. 7
0
 def prepend_shebang(self):
   """
   Effectively iter through the wanted files and prepend shebang
   """
   files_to_change = [fn for fn in self.list_and_filter(
                       self.target, self.path)]
   path = getoutput("which env")
   shebang = "#!%s%s\n\n" %(path, self.interpreter)
   for fn in files_to_change:
     print "%s..." %(fn),
     try:
       newf = open("/tmp/prependshebang", "w")
       f = open(fn, 'r')
       newf.write(shebang)
       for line in f.readlines():
         newf.write(line)
       f.close()
       newf.close()
       shmove("/tmp/prependshebang", fn)
       print "[OK]"
     except IOError, e:
       print "[NO]"
       print "\tERROR DETAILS:"
       print "\t\t%s\n" %(e)
def move_binary(arch, pyver, cwd, scipy_verstr):
    if not pexists(pjoin(cwd, "binaries")):
        os.makedirs(pjoin(cwd, "binaries"))

    shmove(pjoin(cwd, 'dist', get_windist_exec(pyver, scipy_verstr)),
           pjoin(cwd, 'binaries', get_binary_name(arch, scipy_verstr)))
Esempio n. 9
0
def move_binary(arch, pyver, cwd, scipy_verstr):
    if not pexists(pjoin(cwd, "binaries")):
        os.makedirs(pjoin(cwd, "binaries"))

    shmove(pjoin(cwd, 'dist', get_windist_exec(pyver, scipy_verstr)),
           pjoin(cwd, 'binaries', get_binary_name(arch, scipy_verstr)))
Esempio n. 10
0
 def append_license(self):
     """Effectively iter through the wanted files and append the license
 header."""
     if os.path.isfile(self.path):
         # Only 1 file
         files_to_change = [self.path]
     else:
         files_to_change = [
             fn for fn in self.list_and_filter(self.target, self.path)
         ]
         comment_start, comment_end, license_file = self.languages_comments_exts[
             self.language]
         license = None
         license_number = 0
         if "2" in self.license:
             license_number = 2
         elif "3" in self.license:
             license_number = 3
         if self.project_name:
             f = open("licenses/appendlicenseproject.txt", 'r')
         else:
             f = open("licenses/appendlicense.txt", 'r')
         try:
             # Open license file
             if "lgpl" in self.license:
                 license = f.read() % {
                     "projectname": self.project_name,
                     "licensetype": "Lesser",
                     "licenseversion": license_number
                 }
             elif "agpl" in self.license:
                 license = f.read() % {
                     "projectname": self.project_name,
                     "licensetype": "Affero",
                     "licenseversion": license_number
                 }
             else:
                 license = f.read() % {
                     "projectname": self.project_name,
                     "licensetype": "",
                     "licenseversion": license_number
                 }
             f.close()
         except IOError, e:
             print _("Unable to open license file:")
             print e
             return 9
         for fn in files_to_change:
             print "%s..." % (fn),
             try:
                 newf = open("/tmp/appendgpllicense", "w")
                 oldf = open(fn, "r")
                 # one line for the shebang
                 # If there is not a "comment_end", we have to prepend the
                 # comment_start to all the lines
                 lines = license.split("\n")
                 oldlines = oldf.readlines()
                 oldf.close()
                 iterl = 0
                 while iterl < self.skiplines:
                     newf.write(oldlines[iterl])
                     iterl += 1
                 if not comment_end:
                     lines = [comment_start + line for line in lines]
                 else:
                     lines[0] = comment_start + lines[0]
                     lines[-1] = lines[-1] + comment_end
                 for line in lines:
                     newf.write(line + "\n")
                 # loop for the original file without 1st line
                 for line in oldlines[self.skiplines:]:
                     newf.write(line)
                 newf.close()
                 # time to rename
                 shmove("/tmp/appendgpllicense", fn)
                 print "[OK]"
             except IOError, e:
                 print "[NO]"
                 print "\tERROR DETAILS:"
                 print "\t\t%s\n" % (e)
Esempio n. 11
0
 def append_license(self):
   """Effectively iter through the wanted files and append the license
   header."""
   if os.path.isfile(self.path):
     # Only 1 file
     files_to_change = [self.path]
   else:
     files_to_change = [fn for fn in self.list_and_filter(
                         self.target, self.path)]
     comment_start, comment_end, license_file = self.languages_comments_exts[
                                                           self.language]
     license = None
     license_number = 0
     if "2" in self.license:
       license_number = 2
     elif "3" in self.license:
       license_number = 3
     if self.project_name:
       f = open("licenses/appendlicenseproject.txt", 'r')
     else:
       f = open("licenses/appendlicense.txt", 'r')
     try:
       # Open license file
       if "lgpl" in self.license:
         license = f.read() %{
             "projectname": self.project_name,
             "licensetype": "Lesser",
             "licenseversion": license_number
         }
       elif "agpl" in self.license:
         license = f.read() %{
             "projectname": self.project_name,
             "licensetype": "Affero",
             "licenseversion": license_number
         }
       else:
         license = f.read() %{
             "projectname": self.project_name,
             "licensetype": "",
             "licenseversion": license_number
         }
       f.close()
     except IOError, e:
       print _("Unable to open license file:")
       print e
       return 9
     for fn in files_to_change:
       print "%s..." %(fn),
       try:
         newf = open("/tmp/appendgpllicense", "w")
         oldf = open(fn, "r")
         # one line for the shebang
         # If there is not a "comment_end", we have to prepend the 
         # comment_start to all the lines
         lines = license.split("\n")
         oldlines = oldf.readlines()
         oldf.close()
         iterl = 0
         while iterl < self.skiplines:
           newf.write(oldlines[iterl])
           iterl += 1
         if not comment_end:
           lines = [comment_start + line for line in lines]
         else:
           lines[0] = comment_start + lines[0]
           lines[-1] = lines[-1] + comment_end
         for line in lines:
           newf.write(line + "\n")
         # loop for the original file without 1st line
         for line in oldlines[self.skiplines:]:
           newf.write(line)
         newf.close()
         # time to rename
         shmove("/tmp/appendgpllicense", fn)
         print "[OK]"
       except IOError, e:
         print "[NO]"
         print "\tERROR DETAILS:"
         print "\t\t%s\n" %(e)