libutils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """A few useful functions for using rope as a library"""
  2. import os.path
  3. import rope.base.project
  4. import rope.base.pycore
  5. from rope.base import taskhandle
  6. def path_to_resource(project, path, type=None):
  7. """Get the resource at path
  8. You only need to specify `type` if `path` does not exist. It can
  9. be either 'file' or 'folder'. If the type is `None` it is assumed
  10. that the resource already exists.
  11. Note that this function uses `Project.get_resource()`,
  12. `Project.get_file()`, and `Project.get_folder()` methods.
  13. """
  14. project_path = relative(project.address, path)
  15. if project_path is None:
  16. project_path = rope.base.project._realpath(path)
  17. project = rope.base.project.get_no_project()
  18. if type is None:
  19. return project.get_resource(project_path)
  20. if type == 'file':
  21. return project.get_file(project_path)
  22. if type == 'folder':
  23. return project.get_folder(project_path)
  24. return None
  25. def relative(root, path):
  26. root = rope.base.project._realpath(root).replace(os.path.sep, '/')
  27. path = rope.base.project._realpath(path).replace(os.path.sep, '/')
  28. if path == root:
  29. return ''
  30. if path.startswith(root + '/'):
  31. return path[len(root) + 1:]
  32. def report_change(project, path, old_content):
  33. """Report that the contents of file at `path` was changed
  34. The new contents of file is retrieved by reading the file.
  35. """
  36. resource = path_to_resource(project, path)
  37. if resource is None:
  38. return
  39. for observer in list(project.observers):
  40. observer.resource_changed(resource)
  41. if project.pycore.automatic_soa:
  42. rope.base.pycore.perform_soa_on_changed_scopes(project, resource,
  43. old_content)
  44. def analyze_modules(project, task_handle=taskhandle.NullTaskHandle()):
  45. """Perform static object analysis on all python files in the project
  46. Note that this might be really time consuming.
  47. """
  48. resources = project.pycore.get_python_files()
  49. job_set = task_handle.create_jobset('Analyzing Modules', len(resources))
  50. for resource in resources:
  51. job_set.started_job(resource.path)
  52. project.pycore.analyze_module(resource)
  53. job_set.finished_job()