コード例 #1
0
def checkRemoveIfExists(path, removeExisting=False, showYesNo=None):
    """
  If path already exists:
    If removeExisting:
      Delete the path
      Return True
    Else if showYesNo:
      Ask the user if it is ok to delete the path
      If yes, delete and return True.  If no return None.
    Else:
      Raise an IOError
  Else:
    Return False
  This function is not intended to be used outside this module but could be.
  """

    if os.path.exists(path):

        if removeExisting:
            removePath(path)
            return True

        elif showYesNo:
            if os.path.isdir(path):
                files = os.listdir(path)
                n = 5
                if len(files) > n:
                    files = files[:n]
                    files.append('...')
                ss = ', '.join(files)
                message = '%s already exists, remove it and all of its contents (%s) (if no, then no action taken)?' % (
                    path, ss)
                if not showYesNo('Remove directory', message):
                    return None
                else:
                    removePath(path)
                    return True
            else:
                message = '%s already exists (not as a directory), remove it?' % path
                if not showYesNo('Remove file', message):
                    return None
                else:
                    removePath(path)
                    return True
        else:
            raise IOError('%s already exists' % path)

    return False
コード例 #2
0
def backupProject(project,
                  dataLocationStores=None,
                  skipRefData=True,
                  clearOutDir=False):
    def modificationTime(path):
        return os.stat(path)[8]

    backupRepository = project.findFirstRepository(name="backup")

    if not backupRepository:
        print('Warning: no backup path set, so no backup done')
        return

    backupUrl = backupRepository.url
    backupPath = backupUrl.path

    if not dataLocationStores:
        dataLocationStores = set()

    if clearOutDir:
        removePath(backupPath)

    topObjects = tuple(project.topObjects) + (project, )

    for topObject in topObjects:
        if skipRefData:
            repository = topObject.findFirstActiveRepository(name='refData')
            if repository:
                continue

        if topObject.isModified:
            topObject.backup()
        else:
            repository = topObject.findFirstActiveRepository()
            if repository:
                origFile = xmlUtil.findTopObjectPath(repository.url.path,
                                                     topObject)
                if os.path.exists(origFile):
                    # problem with appending repository.name is that topObject.backup()
                    # above does not do it this way, so end up with inconsistent backup
                    ###backupDir = joinPath(backupPath, repository.name)
                    # so use same backup pah as topObject.backup()
                    backupDir = backupPath
                    backupFile = xmlUtil.findTopObjectPath(
                        backupDir, topObject)
                    if not os.path.exists(backupFile) or \
                        (modificationTime(backupFile) < modificationTime(origFile)):
                        directory = os.path.dirname(backupFile)
                        if not os.path.exists(directory):
                            os.makedirs(directory)
                        shutil.copy(origFile, backupFile)
                else:
                    # one is stuffed
                    print(
                        'Warning: could not backup %s since could not find original file "%s"'
                        % (topObject, origFile))
            else:
                # one is stuffed
                print(
                    'Warning: could not backup %s since could not find repository'
                    % topObject)

    dataBackupPath = joinPath(backupPath, 'data')
    for dataLocationStore in dataLocationStores:
        dataBackupDir = joinPath(dataBackupPath, dataLocationStore.name)
        for dataStore in dataLocationStore.dataStores:
            origFile = dataStore.dataUrl.url.path
            backupFile = joinPath(dataBackupDir, dataStore.path)

            if os.path.exists(origFile):
                if not os.path.exists(backupFile) or \
                    (modificationTime(backupFile) < modificationTime(origFile)):
                    directory = os.path.dirname(backupFile)
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    shutil.copy(origFile, backupFile)
            else:
                print(
                    'Warning: could not backup dataStore "%s" because could not find original file "%s"'
                    % (dataStore.name, origFile))
コード例 #3
0
def saveRepository(repository,
                   newPath=None,
                   createFallback=False,
                   removeExisting=False,
                   showYesNo=None):
    """
  Save the repository to a location given by newPath (the url.path
  of the repository) if set, or the existing location if not. 
  For the userData repository this just calls saveProject instead.
  If createFallback, then makes copy of existing modified repository
    files (in newPath, not oldPath) before doing save.
  If newPath != oldPath and newPath exists (either as file or as directory):
    If removeExisting:
      Delete the newPath.
    Else if showYesNo:
      Ask the user if it is ok to delete the newPath
      If yes, delete.  If no, return without saving.
    Else:
      Raise an IOError
  If there is no exception or early return then at end repository is pointing to newPath.
  Return True if save done, False if not (unless there is an exception)
  """

    project = repository.root
    if repository.name == 'userData':
        saveProject(project,
                    newPath=newPath,
                    createFallback=createFallback,
                    removeExisting=removeExisting,
                    showYesNo=showYesNo)
        return False

    oldPath = repository.url.path

    if newPath:
        # normalise path
        newPath = normalisePath(newPath, makeAbsolute=True)
    else:
        newPath = oldPath

    if newPath != oldPath:
        answer = checkRemoveIfExists(newPath, removeExisting, showYesNo)
        if answer is None:
            return False

    # check which topObjects have this repository as activeRepositories[0]
    # and are modified but not deleted
    topObjects = set()
    for topObject in project.topObjects:
        if topObject.isModified and not topObject.isDeleted and \
               repository == topObject.findFirstActiveRepository():
            topObjects.add(topObject)

    # TBD: should this be done here?
    for topObject in topObjects:
        topObject.checkAllValid()

    # copy repository files over
    if newPath != oldPath:
        if os.path.exists(oldPath):
            # just copy everything from oldPath to newPath
            shutil.copytree(oldPath, newPath)

        # change repository url to point to new newPath
        oldUrl = repository.url
        repository.url = Implementation.Url(path=newPath)
        # above will set project.isModified = True

    # save modifications
    try:
        if createFallback:
            for topObject in topObjects:
                createTopObjectFallback(topObject)

            for topObject in topObjects:
                topObject.save()

        # the paths have changed so also need to save project
        project.save()

        return True

    except:
        # something failed so revert to old path
        if newPath != oldPath:
            repository.url = oldUrl
            try:
                removePath(newPath)
            except:
                pass

        raise
コード例 #4
0
def saveProject(project,
                newPath=None,
                newProjectName=None,
                changeBackup=True,
                createFallback=False,
                removeExisting=False,
                showYesNo=None,
                checkValid=False,
                changeDataLocations=False,
                showWarning=None,
                revertToOriginal=False):
    """
  Save the userData for a project to a location given by newPath (the url.path
  of the userData repository) if set, or the existing location if not. 
  If userData does not exist then throws IOError.
  If newPath is not specified then it is set to oldPath.
  If newProjectName is not specified then it is set to oldProjectName if
    newPath==oldPath, otherwise it is set to basename(newPath).
  If changeBackup, then also changes backup URL path for project.
  If createFallback, then makes copy of existing modified topObjects
    files (in newPath, not oldPath) before doing save.
  If newPath != oldPath and newPath exists (either as file or as directory):
    If removeExisting:
      Delete the newPath.
    Else if showYesNo:
      Ask the user if it is ok to delete the newPath
      If yes, delete.  If no, return without saving.
    Else:
      Raise an IOError
  Elif newProjectName != oldProjectName and there exists corresponding path (file/directory):
    If removeExisting:
      Delete the path.
    Else if showYesNo:
      Ask the user if it is ok to delete the path.
      If yes, delete.  If no, return without saving.
    Else:
      Raise an IOError
  If checkValid then does checkAllValid on project
  If changeDataLocations then copy to project directory
  If revertToOriginal then after the save changes paths back to as they were originally
  If there is no exception or early return then at end userData is pointing to newPath.
  Return True if save done, False if not (unless there is an exception)
  """

    # check project valid (so don't save an obviously invalid project)
    if checkValid:
        project.checkAllValid()

    # only want to change path for userData
    userData = project.findFirstRepository(name='userData')
    if not userData:
        raise IOError('Problem: userData not found')

    oldPath = userData.url.path
    oldProjectName = project.name

    if newPath:
        # normalise newPath
        newPath = normalisePath(newPath, makeAbsolute=True)
    else:
        newPath = oldPath

    # if newProjectName isn't specified then use default
    if not newProjectName:
        if newPath == oldPath:
            newProjectName = oldProjectName
        else:
            newProjectName = os.path.basename(newPath)
            # below is because of data model limit
            newProjectName = newProjectName[:32]

    renameProject(project, newProjectName)

    # if newPath same as oldPath, check if newProjectName already exists if it's not same as oldProjectName
    if newPath == oldPath:
        if newProjectName != oldProjectName:
            location = xmlUtil.getTopObjectPath(project)
            if os.path.exists(location):
                answer = checkRemoveIfExists(location, removeExisting,
                                             showYesNo)
                if answer is None:
                    project.__dict__[
                        'name'] = oldProjectName  # TBD: for now name is frozen so change this way
                    return False
    else:  # check instead if newPath already exists
        if os.path.exists(newPath):
            answer = checkRemoveIfExists(newPath, removeExisting, showYesNo)
            if answer is None:
                if newProjectName != oldProjectName:
                    project.__dict__[
                        'name'] = oldProjectName  # TBD: for now name is frozen so change this way
                return False
            # TBD: should we be removing it?
            removePath(newPath)
        else:
            # NBNB 2008/04/03 Rasmus Fogh. Added because it otherwise fell over when
            # target path did not exist
            upDir = os.path.dirname(newPath)
            if not os.path.exists(upDir):
                os.makedirs(upDir)

        # check if any topObject activeRepository is not either of above
        refData = project.findFirstRepository(name='refData')
        genData = project.findFirstRepository(name='generalData')
        topObjects = []
        repositories = set()
        for topObject in project.topObjects:
            repository = topObject.findFirstActiveRepository()
            if repository and repository not in (userData, refData, genData):
                topObjects.append(topObject)
                repositories.add(repository)
        if topObjects:
            print(
                'Warning, topObjects %s, in repositories %s, being left in original locations'
                % (topObjects, repositories))

    try:
        oldUrl = userData.url
        if changeBackup:
            # change project backup url to point to new path
            backupRepository = project.findFirstRepository(name="backup")
            if backupRepository:
                oldBackupUrl = backupRepository.url
            else:
                changeBackup = False

        # copy userData files over
        if newPath != oldPath:
            # if os.path.exists(oldPath):  # only copy if this is a directory
            if os.path.isdir(oldPath):
                # just copy everything from oldPath to newPath
                print(
                    'Copying directory %s to %s (this might take some time if there are big files)'
                    % (oldPath, newPath))
                shutil.copytree(oldPath, newPath)

                # but need toz remove all implementation files
                implPath = joinPath(newPath, ImpConstants.modellingPackageName,
                                    ImpConstants.implementationPackageName)
                #implPath = pathImplDirectory(newPath)
                removePath(implPath)

                # and need to repoint dataUrl's that were copied over
                oldPathP = oldPath + '/'
                for dataLocationStore in project.dataLocationStores:
                    for dataStore in dataLocationStore.dataStores:
                        oldDataPath = dataStore.fullPath
                        if oldDataPath.startswith(oldPathP):
                            dataUrl = dataStore.dataUrl
                            oldDataUrlPath = dataUrl.url.dataLocation
                            if oldDataUrlPath.startswith(
                                    oldPathP):  # normally true
                                newDataUrlPath = newPath + oldDataUrlPath[
                                    len(oldPath):]
                                dataUrl.url = Implementation.Url(
                                    path=newDataUrlPath)
                            else:  # path split awkwardly between absolute and relative
                                newDataUrlPath = newPath
                                dataUrl.url = Implementation.Url(
                                    path=newDataUrlPath)
                                dataStore.path = oldDataPath[len(oldPath):]

            # change userData url to point to new path
            userData.url = Implementation.Url(path=newPath)
            # above will set project.isModified = True

            if changeBackup:
                # change project backup repository url to point to new path
                backupRepository.url = Implementation.Url(path=newPath +
                                                          '_backup')

        # change project name
        if newProjectName != oldProjectName:
            if not project.isModified:  # if it isModified it will be saved below
                if createFallback:
                    createTopObjectFallback(project)
                project.save()

        # create fallbacks and keep track of modified topObjects
        modifiedTopObjects = []
        if createFallback:
            for topObject in (project, ) + tuple(project.topObjects):
                if not topObject.isDeleted and topObject.isModified:
                    createTopObjectFallback(topObject)
                    modifiedTopObjects.append(topObject)

        if changeDataLocations:
            dataLocationStores = project.sortedDataLocationStores()

            userRepository = project.findFirstRepository(name='userData')
            userPath = userRepository.url.dataLocation
            # 2010 Aug 11: remove data directory from path
            #dataPath = joinPath(userPath, 'data')
            dataPath = userPath

            # 2010 Aug 11: change name
            #dataStorePrefix = 'dataStore'
            dataStorePrefix = 'spectra'
            if os.path.exists(dataPath):
                files = [
                    xx for xx in os.listdir(dataPath)
                    if xx.startswith(dataStorePrefix)
                ]
                offset = len(files)
            else:
                offset = 0

            copyingList = []
            dataUrlDict = {}
            for dataLocationStore in dataLocationStores:
                for dataStore in dataLocationStore.sortedDataStores():

                    # wb104: 24 Mar 2010: below check is a complete kludge
                    # we should check whether dataStore is instance of
                    # NumericMatrix, etc., but those are in ccp so should
                    # not be imported here
                    # in any case, there is no proper way to find out if
                    # a dataStore is used without explicit knowledge of class
                    knt = 0
                    # hicard = 1
                    for attr in ('nmrDataSourceImage', ):
                        if hasattr(dataStore, attr):
                            if getattr(dataStore, attr):
                                knt += 1
                    # hicard > 1
                    for attr in ('externalDatas', 'nmrDataSources'):
                        if hasattr(dataStore, attr):
                            knt += len(getattr(dataStore, attr))
                    if knt == 0:
                        continue

                    oldFullPath = dataStore.fullPath
                    if not oldFullPath.startswith(userPath + '/'):
                        # first figure out new dataUrl path
                        dataUrl = dataStore.dataUrl
                        oldPath = dataUrl.url.dataLocation
                        if dataUrl in dataUrlDict:
                            newUrl = dataUrlDict[dataUrl]
                        else:
                            offset += 1
                            newUrlPath = '%s%d' % (dataStorePrefix, offset)
                            newUrlPath = joinPath(dataPath, newUrlPath)
                            newUrl = dataUrlDict[dataUrl] = Implementation.Url(
                                path=newUrlPath)
                        # then add to list to copy over if original data exists
                        if os.path.exists(oldFullPath):
                            newFullPath = joinPath(newUrl.dataLocation,
                                                   dataStore.path)
                            copyingList.append((oldFullPath, newFullPath))

            # now copy data files over
            nfilesToCopy = len(copyingList)
            for n, (oldFullPath, newFullPath) in enumerate(copyingList):
                dirName = os.path.dirname(newFullPath)
                if not os.path.exists(dirName):
                    os.makedirs(dirName)
                print('Copying file %s to %s (%d of %d)' %
                      (oldFullPath, newFullPath, n + 1, nfilesToCopy))
                shutil.copy(oldFullPath, newFullPath)

            # finally change dataUrl paths
            for dataUrl in dataUrlDict:
                dataUrl.url = dataUrlDict[dataUrl]

        # save modifications
        # change way doing save in case exception is thrown
        if createFallback:
            for topObject in modifiedTopObjects:
                try:
                    topObject.save()
                except:
                    location = xmlUtil.getTopObjectPath(topObject)
                    print('Exception working on topObject %s, file %s' %
                          (topObject, location))
                    raise
            # be safe and do below in case new modifications after
            # modifiedTopObjects has been created
            project.saveModified()
        else:
            project.saveModified()

        if not isWindowsOS():
            os.system('touch "%s"' %
                      newPath)  # so that user can see which are most recent

        badTopObjects = []
        for topObject in modifiedTopObjects:
            if not checkFileIntegrity(topObject):
                badTopObjects.append(topObject)

        if badTopObjects:
            if showWarning:
                showWarning(
                    'Incomplete save',
                    'It looks like one or more files did not save completely, see console for list'
                )
            print(
                'It looks like one or more files did not save completely, you should check them:'
            )
            for topObject in badTopObjects:
                print
                print('%s, path:' % topObject)
                print(xmlUtil.getTopObjectPath(topObject))
            return False

        if revertToOriginal:  # TBD: the below does not change back dataUrl paths
            if newProjectName != oldProjectName:
                project.__dict__[
                    'name'] = oldProjectName  # TBD: for now name is frozen so change this way

            if newPath != oldPath:
                userData.url = oldUrl
                if changeBackup:
                    backupRepository.url = oldBackupUrl

        return True

    except:
        # saveModified failed so revert to old values
        if newProjectName != oldProjectName:
            project.__dict__[
                'name'] = oldProjectName  # TBD: for now name is frozen so change this way

        if newPath != oldPath:
            userData.url = oldUrl
            if changeBackup:
                backupRepository.url = oldBackupUrl
            try:
                removePath(newPath)
            except:
                pass

        raise
コード例 #5
0
def saveProject(project, newPath = None, newProjectName = None, changeBackup = True,
                createFallback = False, removeExisting = False, showYesNo = None,
                checkValid = False):
  """
  Save the userData for a project to a location given by newPath (the url.path
  of the userData repository) if set, or the existing location if not. 
  If userData does not exist then throws IOError.
  If newPath is not specified then it is set to oldPath.
  If newProjectName is not specified then it is set to oldProjectName if
    newPath==oldPath, otherwise it is set to basename(newPath).
  If changeBackup, then also changes backup URL path for project.
  If createFallback, then makes copy of existing modified topObjects
    files (in newPath, not oldPath) before doing save.
  If newPath != oldPath and newPath exists (either as file or as directory):
    If removeExisting:
      Delete the newPath.
    Else if showYesNo:
      Ask the user if it is ok to delete the newPath
      If yes, delete.  If no, return without saving.
    Else:
      Raise an IOError
  Elif newProjectName != oldProjectName and there exists corresponding path (file/directory):
    If removeExisting:
      Delete the path.
    Else if showYesNo:
      Ask the user if it is ok to delete the path.
      If yes, delete.  If no, return without saving.
    Else:
      Raise an IOError
  if checkValid then does checkAllValid on project
  If there is no exception or early return then at end userData is pointing to newPath.
  Return True if save done, False if not (unless there is an exception)
  """

  # check project valid (so don't save an obviously invalid project)
  if checkValid:
    project.checkAllValid()

  # only want to change path for userData
  userData = project.findFirstRepository(name='userData')
  if not userData:
    raise IOError('Problem: userData not found')

  oldPath = userData.url.path
  oldProjectName = project.name

  if newPath:
    # normalise newPath
    newPath = normalisePath(newPath, makeAbsolute=True)
  else:
    newPath = oldPath

  # if newProjectName isn't specified then use default
  if not newProjectName:
    if newPath == oldPath:
      newProjectName = oldProjectName
    else:
      newProjectName = os.path.basename(newPath)

  # change project name
  if newProjectName != oldProjectName:
    project.override = True # TBD: for now name is frozen so change this way
    try:
      # below constraint is not checked in setName() if override is True so repeat here
      isValid = newProjectName.isalnum()  # superfluous but faster in most cases
      if not isValid:
        for cc in newProjectName:
          if cc != '_' and not cc.isalnum():
            isValid = False
            break
        else:
          isValid = True
      if (not (isValid)):
        raise ApiError('project name must only have characters that are alphanumeric or underscore')

      # below checks for length of name as well
      project.name = newProjectName
    finally:
      project.override = False

  # if newPath same as oldPath, check if newProjectName already exists if it's not same as oldProjectName
  if newPath == oldPath:
    if newProjectName != oldProjectName:
      location = xmlUtil.getTopObjectPath(project)
      if os.path.exists(location):
        answer = checkRemoveIfExists(location, removeExisting, showYesNo)
        if answer is None:
          project.__dict__['name'] = oldProjectName  # TBD: for now name is frozen so change this way
          return False
  else: # check instead if newPath already exists
    if os.path.exists(newPath):
      answer = checkRemoveIfExists(newPath, removeExisting, showYesNo)
      if answer is None:
        if newProjectName != oldProjectName:
          project.__dict__['name'] = oldProjectName  # TBD: for now name is frozen so change this way
        return False
      # TBD: should we be removing it?
      removePath(newPath)
    else:
      # NBNB 2008/04/03 Rasmus Fogh. Added because it otherwise fell over when
      # target path did not exist
      upDir = os.path.dirname(newPath)
      if not os.path.exists(upDir):
        os.makedirs(upDir)

    # check if any topObject activeRepository is not either of above
    refData = project.findFirstRepository(name='refData')
    genData = project.findFirstRepository(name='generalData')
    topObjects = []
    repositories = set()
    for topObject in project.topObjects:
      repository = topObject.findFirstActiveRepository()
      if repository and repository not in (userData, refData, genData):
        topObjects.append(topObject)
        repositories.add(repository)
    if topObjects:
      print 'Warning, topObjects %s, in repositories %s, being left in original locations' % (topObjects, repositories)

  try:
    oldUrl = userData.url
    if changeBackup:
      # change project backup url to point to new path
      backupRepository = project.findFirstRepository(name="backup")
      if backupRepository:
        oldBackupUrl = backupRepository.url
      else:
        changeBackup = False

    # copy userData files over
    if newPath != oldPath:
      # if os.path.exists(oldPath):  # only copy if this is a directory
      if os.path.isdir(oldPath):
        # just copy everything from oldPath to newPath
        shutil.copytree(oldPath, newPath)

        # but need to remove all implementation files
        implPath = joinPath(newPath, ImpConstants.modellingPackageName,
                            ImpConstants.implementationPackageName)
        #implPath = pathImplDirectory(newPath)
        removePath(implPath)

      # change userData url to point to new path
      userData.url = Implementation.Url(path=newPath)
      # above will set project.isModified = True

      if changeBackup:
        # change project backup repository url to point to new path
        backupRepository.url = Implementation.Url(path=newPath+'_backup')

    # change project name
    if newProjectName != oldProjectName:
      if not project.isModified: # if it isModified it will be saved below
        if createFallback:
          createTopObjectFallback(project)
        project.save()

    # create fallbacks
    if createFallback:
      for topObject in (project,)+tuple(project.topObjects):
        if not topObject.isDeleted and topObject.isModified:
          createTopObjectFallback(topObject)

    # save modifications
    project.saveModified()

    if not isWindowsOS():
      os.system('touch %s' % newPath)  # so that user can see which are most recent

    return True

  except:
    # saveModified failed so revert to old values
    if newProjectName != oldProjectName:
      project.__dict__['name'] = oldProjectName  # TBD: for now name is frozen so change this way

    if newPath != oldPath:
      userData.url = oldUrl
      if changeBackup:
        backupRepository.url = oldBackupUrl
      try:
        removePath(newPath)
      except:
        pass

    raise