Created
October 2, 2012 14:12
-
-
Save b4n/3819447 to your computer and use it in GitHub Desktop.
Finding file after project move
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
def path_inside(path, dir): | |
path = os.path.normpath(path) | |
dir = os.path.normpath(dir) | |
return os.path.commonprefix([path, dir]) == dir | |
def path_samepath(a, b): | |
return os.path.normpath(a) == os.path.normpath(b) | |
def load_file(actual_project_file, | |
expected_project_file, | |
expected_base_path, | |
expected_file_path): | |
if os.path.exists(expected_file_path): | |
return expected_file_path | |
else: | |
expected_project_file_dir = os.path.dirname(expected_project_file) | |
if (path_inside(expected_project_file_dir, expected_base_path) and | |
path_inside(expected_file_path, expected_base_path)): | |
project_to_base_path = os.path.relpath(expected_base_path, | |
expected_project_file_dir) | |
actual_project_file_dir = os.path.dirname(actual_project_file) | |
actual_base_path = os.path.join(actual_project_file_dir, | |
project_to_base_path) | |
# make sure the project still is inside the tree like it was before | |
base_path_to_project = os.path.relpath(expected_project_file_dir, | |
expected_base_path) | |
actual_project_file_dir_guess = os.path.join(actual_base_path, | |
base_path_to_project) | |
if (path_samepath(actual_project_file_dir, | |
actual_project_file_dir_guess)): | |
file_relpath = os.path.relpath(expected_file_path, | |
expected_base_path) | |
actual_file_path = os.path.join(actual_base_path, file_relpath) | |
actual_file_path = os.path.normpath(actual_file_path) | |
return actual_file_path | |
return None | |
# these ones are correct | |
assert(load_file('/a/b/foo.geany', | |
'/home/user/p/foo/foo.geany', | |
'/home/user/p/foo', | |
'/home/user/p/foo/src/main.c') == | |
'/a/b/src/main.c') | |
assert(load_file('/a/b/project/foo.geany', | |
'/home/user/p/foo/project/foo.geany', | |
'/home/user/p/foo', | |
'/home/user/p/foo/src/main.c') == | |
'/a/b/src/main.c') | |
assert(load_file('/home/user/p/newname/newname.geany', | |
'/home/user/p/foo/foo.geany', | |
'/home/user/p/foo', | |
'/home/user/p/foo/src/main.c') == | |
'/home/user/p/newname/src/main.c') | |
assert(load_file('/home/user/p/newname/project/newname.geany', | |
'/home/user/p/foo/project/foo.geany', | |
'/home/user/p/foo', | |
'/home/user/p/foo/src/main.c') == | |
'/home/user/p/newname/src/main.c') | |
# this one is incorrect, because the project file moved from base path | |
assert(load_file('/a/b/foo.geany', | |
'/home/user/p/foo/project/foo.geany', | |
'/home/user/p/foo', | |
'/home/user/p/foo/src/main.c') == | |
None) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment