1 # Status: this module is ported on demand by however needs something
2 # from it. Functionality that is not needed by Python port will
5 # Copyright (C) Vladimir Prus 2002. Permission to copy, use, modify, sell and
6 # distribute this software is granted provided this copyright notice appears in
7 # all copies. This software is provided "as is" without express or implied
8 # warranty, and with no claim as to its suitability for any purpose.
10 # Performs various path manipulations. Path are always in a 'normilized'
11 # representation. In it, a path may be either:
15 # - ['/'] [ ( '..' '/' )* (token '/')* token ]
17 # In plain english, path can be rooted, '..' elements are allowed only
18 # at the beginning, and it never ends in slash, except for path consisting
22 from utility import to_seq
23 from glob import glob as builtin_glob
25 from b2.util import bjam_signature
27 @bjam_signature((["path", "root"],))
28 def root (path, root):
29 """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
31 if os.path.isabs (path):
34 return os.path.join (root, path)
36 @bjam_signature((["native"],))
38 """ Converts the native path into normalized form.
40 # TODO: make os selection here.
41 return make_UNIX (native)
43 def make_UNIX (native):
45 # VP: I have no idea now 'native' can be empty here! But it can!
48 return os.path.normpath (native)
50 @bjam_signature((["path"],))
52 """ Builds a native representation of the path.
54 # TODO: make os selection here.
55 return native_UNIX (path)
57 def native_UNIX (path):
62 """ Returns the current working directory.
63 # TODO: is it a good idea to use the current dir? Some use-cases
64 may not allow us to depend on the current dir.
66 return make (os.getcwd ())
69 """ Tests if a path is rooted.
71 return path and path [0] == '/'
74 ###################################################################
76 # Original lines are prefixed with "# "
78 # # Copyright (C) Vladimir Prus 2002. Permission to copy, use, modify, sell and
79 # # distribute this software is granted provided this copyright notice appears in
80 # # all copies. This software is provided "as is" without express or implied
81 # # warranty, and with no claim as to its suitability for any purpose.
83 # # Performs various path manipulations. Path are always in a 'normilized'
84 # # representation. In it, a path may be either:
88 # # - ['/'] [ ( '..' '/' )* (token '/')* token ]
90 # # In plain english, path can be rooted, '..' elements are allowed only
91 # # at the beginning, and it never ends in slash, except for path consisting
97 # import errors : error ;
100 # os = [ modules.peek : OS ] ;
101 # if [ modules.peek : UNIX ]
103 # local uname = [ modules.peek : JAMUNAME ] ;
115 # # Tests if a path is rooted.
117 # rule is-rooted ( path )
119 # return [ MATCH "^(/)" : $(path) ] ;
123 # # Tests if a path has a parent.
125 # rule has-parent ( path )
135 # # Returns the path without any directory components.
137 # rule basename ( path )
139 # return [ MATCH "([^/]+)$" : $(path) ] ;
143 # # Returns parent directory of the path. If no parent exists, error is issued.
145 # rule parent ( path )
147 # if [ has-parent $(path) ] {
153 # # Strip everything at the end of path up to and including
155 # local result = [ regex.match "((.*)/)?([^/]+)" : $(path) : 2 3 ] ;
157 # # Did we strip what we shouldn't?
158 # if $(result[2]) = ".." {
159 # return $(path)/.. ;
161 # if ! $(result[1]) {
162 # if [ is-rooted $(path) ] {
168 # return $(result[1]) ;
172 # error "Path '$(path)' has no parent" ;
177 # # Returns path2 such that "[ join path path2 ] = .".
178 # # The path may not contain ".." element or be rooted.
180 # rule reverse ( path )
188 # local tokens = [ regex.split $(path) "/" ] ;
190 # for local i in $(tokens) {
193 # return [ sequence.join $(tokens2) : "/" ] ;
197 """Returns path2 such that `os.path.join(path, path2) == '.'`.
198 `path` may not contain '..' or be rooted.
201 path (str): the path to reverse
204 the string of the reversed path
208 >>> p1 = 'path/to/somewhere'
209 >>> p2 = reverse('path/to/somewhere')
212 >>> os.path.normpath(os.path.join(p1, p2))
215 if is_rooted(path) or '..' in path:
216 from b2.manager import get_manager
217 get_manager().errors()(
218 'reverse(path): path is either rooted or contains ".." in the path')
221 path = os.path.normpath(path)
222 # os.sep.join() is being used over os.path.join() due
223 # to an extra '..' that is created by os.path.join()
224 return os.sep.join('..' for t in path.split(os.sep))
226 # # Auxillary rule: does all the semantic of 'join', except for error cheching.
227 # # The error checking is separated because this rule is recursive, and I don't
228 # # like the idea of checking the same input over and over.
230 # local rule join-imp ( elements + )
232 # return [ NORMALIZE_PATH $(elements:J="/") ] ;
236 # # Contanenates the passed path elements. Generates an error if
237 # # any element other than the first one is rooted.
239 # rule join ( elements + )
241 # if ! $(elements[2])
243 # return $(elements[1]) ;
247 # for local e in $(elements[2-])
249 # if [ is-rooted $(e) ]
251 # error only first element may be rooted ;
254 # return [ join-imp $(elements) ] ;
259 def glob (dirs, patterns):
260 """ Returns the list of files matching the given pattern in the
261 specified directory. Both directories and patterns are
262 supplied as portable paths. Each pattern should be non-absolute
263 path, and can't contain "." or ".." elements. Each slash separated
264 element of pattern can contain the following special characters:
265 - '?', which match any character
266 - '*', which matches arbitrary number of characters.
267 A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3
268 if and only if e1 matches p1, e2 matches p2 and so on.
272 [ glob . : */build/Jamfile ]
278 # # When a pattern has a directory element, we first glob for
279 # # directory, and then glob for file name is the found directories.
280 # for local p in $(patterns)
282 # # First glob for directory part.
283 # local globbed-dirs = [ glob $(dirs) : $(p:D) ] ;
284 # result += [ glob $(globbed-dirs) : $(p:D="") ] ;
289 # # When a pattern has not directory, we glob directly.
290 # # Take care of special ".." value. The "GLOB" rule simply ignores
291 # # the ".." element (and ".") element in directory listings. This is
294 # # [ glob libs/*/Jamfile ]
298 # # libs/../Jamfile (which is the same as ./Jamfile)
300 # # On the other hand, when ".." is explicitly present in the pattern
301 # # we need to return it.
303 # for local dir in $(dirs)
305 # for local p in $(patterns)
309 # result += [ sequence.transform make
310 # : [ GLOB [ native $(dir) ] : $(p) ] ] ;
314 # result += [ path.join $(dir) .. ] ;
323 # TODO: (PF) I replaced the code above by this. I think it should work but needs to be tested.
326 patterns = to_seq (patterns)
330 splitdirs += dir.split (os.pathsep)
332 for dir in splitdirs:
333 for pattern in patterns:
334 p = os.path.join (dir, pattern)
336 result.extend (glob.glob (p))
340 # Find out the absolute name of path and returns the list of all the parents,
341 # starting with the immediate one. Parents are returned as relative names.
342 # If 'upper_limit' is specified, directories above it will be pruned.
344 def all_parents(path, upper_limit=None, cwd=None):
349 path_abs = os.path.join(cwd, path)
352 upper_limit = os.path.join(cwd, upper_limit)
355 while path_abs and path_abs != upper_limit:
356 (head, tail) = os.path.split(path)
357 path = os.path.join(path, "..")
361 if upper_limit and path_abs != upper_limit:
362 raise BaseException("'%s' is not a prefix of '%s'" % (upper_limit, path))
366 # Search for 'pattern' in parent directories of 'dir', up till and including
367 # 'upper_limit', if it is specified, or till the filesystem root otherwise.
369 def glob_in_parents(dir, patterns, upper_limit=None):
372 parent_dirs = all_parents(dir, upper_limit)
374 for p in parent_dirs:
375 result = glob(p, patterns)
382 # # Assuming 'child' is a subdirectory of 'parent', return the relative
383 # # path from 'parent' to 'child'
385 # rule relative ( child parent )
393 # local split1 = [ regex.split $(parent) / ] ;
394 # local split2 = [ regex.split $(child) / ] ;
398 # if $(split1[1]) = $(split2[1])
400 # split1 = $(split1[2-]) ;
401 # split2 = $(split2[2-]) ;
405 # errors.error $(child) is not a subdir of $(parent) ;
408 # return [ join $(split2) ] ;
412 # # Returns the minimal path to path2 that is relative path1.
414 # rule relative-to ( path1 path2 )
416 # local root_1 = [ regex.split [ reverse $(path1) ] / ] ;
417 # local split1 = [ regex.split $(path1) / ] ;
418 # local split2 = [ regex.split $(path2) / ] ;
420 # while $(split1) && $(root_1)
422 # if $(split1[1]) = $(split2[1])
424 # root_1 = $(root_1[2-]) ;
425 # split1 = $(split1[2-]) ;
426 # split2 = $(split2[2-]) ;
433 # return [ join . $(root_1) $(split2) ] ;
436 # Returns the list of paths which are used by the operating system
437 # for looking up programs
438 def programs_path ():
440 names = ['PATH', 'Path', 'path']
443 raw.append(os.environ.get (name, ''))
448 for p in elem.split(os.path.pathsep):
449 # it's possible that the user's Path has
450 # double path separators, thus it is possible
451 # for p to be an empty string.
453 result.append(make(p))
457 # rule make-NT ( native )
459 # local tokens = [ regex.split $(native) "[/\\]" ] ;
462 # # Handle paths ending with slashes
463 # if $(tokens[-1]) = ""
465 # tokens = $(tokens[1--2]) ; # discard the empty element
468 # result = [ path.join $(tokens) ] ;
470 # if [ regex.match "(^.:)" : $(native) ]
472 # result = /$(result) ;
483 # rule native-NT ( path )
485 # local result = [ MATCH "^/?(.*)" : $(path) ] ;
486 # result = [ sequence.join [ regex.split $(result) "/" ] : "\\" ] ;
490 # rule make-CYGWIN ( path )
492 # return [ make-NT $(path) ] ;
495 # rule native-CYGWIN ( path )
497 # local result = $(path) ;
498 # if [ regex.match "(^/.:)" : $(path) ] # win absolute
500 # result = [ MATCH "^/?(.*)" : $(path) ] ; # remove leading '/'
502 # return [ native-UNIX $(result) ] ;
506 # # split-VMS: splits input native path into
507 # # device dir file (each part is optional),
510 # # dev:[dir]file.c => dev: [dir] file.c
512 # rule split-path-VMS ( native )
514 # local matches = [ MATCH ([a-zA-Z0-9_-]+:)?(\\[[^\]]*\\])?(.*)?$ : $(native) ] ;
515 # local device = $(matches[1]) ;
516 # local dir = $(matches[2]) ;
517 # local file = $(matches[3]) ;
519 # return $(device) $(dir) $(file) ;
523 # # Converts a native VMS path into a portable path spec.
525 # # Does not handle current-device absolute paths such
526 # # as "[dir]File.c" as it is not clear how to represent
527 # # them in the portable path notation.
529 # # Adds a trailing dot (".") to the file part if no extension
530 # # is present (helps when converting it back into native path).
532 # rule make-VMS ( native )
534 # if [ MATCH ^(\\[[a-zA-Z0-9]) : $(native) ]
536 # errors.error "Can't handle default-device absolute paths: " $(native) ;
539 # local parts = [ split-path-VMS $(native) ] ;
540 # local device = $(parts[1]) ;
541 # local dir = $(parts[2]) ;
542 # local file = $(parts[3]) ;
550 # elems = /$(device) ;
556 # # Special case: current directory
558 # elems = $(elems) "." ;
562 # dir = [ regex.replace $(dir) "\\[|\\]" "" ] ;
563 # local dir_parts = [ regex.split $(dir) \\. ] ;
565 # if $(dir_parts[1]) = ""
570 # dir_parts = $(dir_parts[2--1]) ;
574 # # replace "parent-directory" parts (- => ..)
576 # dir_parts = [ regex.replace-list $(dir_parts) : - : .. ] ;
578 # elems = $(elems) $(dir_parts) ;
583 # if ! [ MATCH (\\.) : $(file) ]
586 # # Always add "." to end of non-extension file
590 # elems = $(elems) $(file) ;
593 # local portable = [ path.join $(elems) ] ;
595 # return $(portable) ;
599 # # Converts a portable path spec into a native VMS path.
601 # # Relies on having at least one dot (".") included in the file
602 # # name to be able to differentiate it ftom the directory part.
604 # rule native-VMS ( path )
606 # local device = "" ;
607 # local dir = $(path) ;
615 # if [ is-rooted $(dir) ]
617 # split = [ MATCH ^/([^:]+:)/?(.*) : $(dir) ] ;
618 # device = $(split[1]) ;
619 # dir = $(split[2]) ;
625 # # This is no exact science, just guess work:
627 # # If the last part of the current path spec
628 # # includes some chars, followed by a dot,
629 # # optionally followed by more chars -
630 # # then it is a file (keep your fingers crossed).
632 # split = [ regex.split $(dir) / ] ;
633 # local maybe_file = $(split[-1]) ;
635 # if [ MATCH ^([^.]+\\..*) : $(maybe_file) ]
637 # file = $(maybe_file) ;
638 # dir = [ sequence.join $(split[1--2]) : / ] ;
650 # dir = [ regex.replace $(dir) \\.\\. - ] ;
651 # dir = [ regex.replace $(dir) / . ] ;
656 # # Relative directory
660 # dir = "["$(dir)"]" ;
663 # native = [ sequence.join $(device) $(dir) $(file) ] ;
669 # rule __test__ ( ) {
672 # import errors : try catch ;
674 # assert.true is-rooted "/" ;
675 # assert.true is-rooted "/foo" ;
676 # assert.true is-rooted "/foo/bar" ;
677 # assert.result : is-rooted "." ;
678 # assert.result : is-rooted "foo" ;
679 # assert.result : is-rooted "foo/bar" ;
681 # assert.true has-parent "foo" ;
682 # assert.true has-parent "foo/bar" ;
683 # assert.true has-parent "." ;
684 # assert.result : has-parent "/" ;
686 # assert.result "." : basename "." ;
687 # assert.result ".." : basename ".." ;
688 # assert.result "foo" : basename "foo" ;
689 # assert.result "foo" : basename "bar/foo" ;
690 # assert.result "foo" : basename "gaz/bar/foo" ;
691 # assert.result "foo" : basename "/gaz/bar/foo" ;
693 # assert.result "." : parent "foo" ;
694 # assert.result "/" : parent "/foo" ;
695 # assert.result "foo/bar" : parent "foo/bar/giz" ;
696 # assert.result ".." : parent "." ;
697 # assert.result ".." : parent "../foo" ;
698 # assert.result "../../foo" : parent "../../foo/bar" ;
701 # assert.result "." : reverse "." ;
702 # assert.result ".." : reverse "foo" ;
703 # assert.result "../../.." : reverse "foo/bar/giz" ;
705 # assert.result "foo" : join "foo" ;
706 # assert.result "/foo" : join "/" "foo" ;
707 # assert.result "foo/bar" : join "foo" "bar" ;
708 # assert.result "foo/bar" : join "foo/giz" "../bar" ;
709 # assert.result "foo/giz" : join "foo/bar/baz" "../../giz" ;
710 # assert.result ".." : join "." ".." ;
711 # assert.result ".." : join "foo" "../.." ;
712 # assert.result "../.." : join "../foo" "../.." ;
713 # assert.result "/foo" : join "/bar" "../foo" ;
714 # assert.result "foo/giz" : join "foo/giz" "." ;
715 # assert.result "." : join lib2 ".." ;
716 # assert.result "/" : join "/a" ".." ;
718 # assert.result /a/b : join /a/b/c .. ;
720 # assert.result "foo/bar/giz" : join "foo" "bar" "giz" ;
721 # assert.result "giz" : join "foo" ".." "giz" ;
722 # assert.result "foo/giz" : join "foo" "." "giz" ;
728 # catch only first element may be rooted ;
730 # local CWD = "/home/ghost/build" ;
731 # assert.result : all-parents . : . : $(CWD) ;
732 # assert.result . .. ../.. ../../.. : all-parents "Jamfile" : "" : $(CWD) ;
733 # assert.result foo . .. ../.. ../../.. : all-parents "foo/Jamfile" : "" : $(CWD) ;
734 # assert.result ../Work .. ../.. ../../.. : all-parents "../Work/Jamfile" : "" : $(CWD) ;
736 # local CWD = "/home/ghost" ;
737 # assert.result . .. : all-parents "Jamfile" : "/home" : $(CWD) ;
738 # assert.result . : all-parents "Jamfile" : "/home/ghost" : $(CWD) ;
740 # assert.result "c/d" : relative "a/b/c/d" "a/b" ;
741 # assert.result "foo" : relative "foo" "." ;
743 # local save-os = [ modules.peek path : os ] ;
744 # modules.poke path : os : NT ;
746 # assert.result "foo/bar/giz" : make "foo/bar/giz" ;
747 # assert.result "foo/bar/giz" : make "foo\\bar\\giz" ;
748 # assert.result "foo" : make "foo/." ;
749 # assert.result "foo" : make "foo/bar/.." ;
750 # assert.result "/D:/My Documents" : make "D:\\My Documents" ;
751 # assert.result "/c:/boost/tools/build/new/project.jam" : make "c:\\boost\\tools\\build\\test\\..\\new\\project.jam" ;
753 # assert.result "foo\\bar\\giz" : native "foo/bar/giz" ;
754 # assert.result "foo" : native "foo" ;
755 # assert.result "D:\\My Documents\\Work" : native "/D:/My Documents/Work" ;
757 # modules.poke path : os : UNIX ;
759 # assert.result "foo/bar/giz" : make "foo/bar/giz" ;
760 # assert.result "/sub1" : make "/sub1/." ;
761 # assert.result "/sub1" : make "/sub1/sub2/.." ;
762 # assert.result "sub1" : make "sub1/." ;
763 # assert.result "sub1" : make "sub1/sub2/.." ;
764 # assert.result "/foo/bar" : native "/foo/bar" ;
766 # modules.poke path : os : VMS ;
769 # # Don't really need to poke os before these
771 # assert.result "disk:" "[dir]" "file" : split-path-VMS "disk:[dir]file" ;
772 # assert.result "disk:" "[dir]" "" : split-path-VMS "disk:[dir]" ;
773 # assert.result "disk:" "" "" : split-path-VMS "disk:" ;
774 # assert.result "disk:" "" "file" : split-path-VMS "disk:file" ;
775 # assert.result "" "[dir]" "file" : split-path-VMS "[dir]file" ;
776 # assert.result "" "[dir]" "" : split-path-VMS "[dir]" ;
777 # assert.result "" "" "file" : split-path-VMS "file" ;
778 # assert.result "" "" "" : split-path-VMS "" ;
781 # # Special case: current directory
783 # assert.result "" "[]" "" : split-path-VMS "[]" ;
784 # assert.result "disk:" "[]" "" : split-path-VMS "disk:[]" ;
785 # assert.result "" "[]" "file" : split-path-VMS "[]file" ;
786 # assert.result "disk:" "[]" "file" : split-path-VMS "disk:[]file" ;
789 # # Make portable paths
791 # assert.result "/disk:" : make "disk:" ;
792 # assert.result "foo/bar/giz" : make "[.foo.bar.giz]" ;
793 # assert.result "foo" : make "[.foo]" ;
794 # assert.result "foo" : make "[.foo.bar.-]" ;
795 # assert.result ".." : make "[.-]" ;
796 # assert.result ".." : make "[-]" ;
797 # assert.result "." : make "[]" ;
798 # assert.result "giz.h" : make "giz.h" ;
799 # assert.result "foo/bar/giz.h" : make "[.foo.bar]giz.h" ;
800 # assert.result "/disk:/my_docs" : make "disk:[my_docs]" ;
801 # assert.result "/disk:/boost/tools/build/new/project.jam" : make "disk:[boost.tools.build.test.-.new]project.jam" ;
804 # # Special case (adds '.' to end of file w/o extension to
805 # # disambiguate from directory in portable path spec).
807 # assert.result "Jamfile." : make "Jamfile" ;
808 # assert.result "dir/Jamfile." : make "[.dir]Jamfile" ;
809 # assert.result "/disk:/dir/Jamfile." : make "disk:[dir]Jamfile" ;
812 # # Make native paths
814 # assert.result "disk:" : native "/disk:" ;
815 # assert.result "[.foo.bar.giz]" : native "foo/bar/giz" ;
816 # assert.result "[.foo]" : native "foo" ;
817 # assert.result "[.-]" : native ".." ;
818 # assert.result "[.foo.-]" : native "foo/.." ;
819 # assert.result "[]" : native "." ;
820 # assert.result "disk:[my_docs.work]" : native "/disk:/my_docs/work" ;
821 # assert.result "giz.h" : native "giz.h" ;
822 # assert.result "disk:Jamfile." : native "/disk:Jamfile." ;
823 # assert.result "disk:[my_docs.work]Jamfile." : native "/disk:/my_docs/work/Jamfile." ;
825 # modules.poke path : os : $(save-os) ;
832 #def glob(dir, patterns):
834 # for pattern in patterns:
835 # result.extend(builtin_glob(os.path.join(dir, pattern)))
838 def glob(dirs, patterns, exclude_patterns=None):
839 """Returns the list of files matching the given pattern in the
840 specified directory. Both directories and patterns are
841 supplied as portable paths. Each pattern should be non-absolute
842 path, and can't contain '.' or '..' elements. Each slash separated
843 element of pattern can contain the following special characters:
844 - '?', which match any character
845 - '*', which matches arbitrary number of characters.
846 A file $(d)/e1/e2/e3 (where 'd' is in $(dirs)) matches pattern p1/p2/p3
847 if and only if e1 matches p1, e2 matches p2 and so on.
850 [ glob . : */build/Jamfile ]
853 assert(isinstance(patterns, list))
854 assert(isinstance(dirs, list))
856 if not exclude_patterns:
857 exclude_patterns = []
859 assert(isinstance(exclude_patterns, list))
861 real_patterns = [os.path.join(d, p) for p in patterns for d in dirs]
862 real_exclude_patterns = [os.path.join(d, p) for p in exclude_patterns
865 inc = [os.path.normpath(name) for p in real_patterns
866 for name in builtin_glob(p)]
867 exc = [os.path.normpath(name) for p in real_exclude_patterns
868 for name in builtin_glob(p)]
869 return [x for x in inc if x not in exc]
871 def glob_tree(roots, patterns, exclude_patterns=None):
872 """Recursive version of GLOB. Builds the glob of files while
873 also searching in the subdirectories of the given roots. An
874 optional set of exclusion patterns will filter out the
875 matching entries from the result. The exclusions also apply
876 to the subdirectory scanning, such that directories that
877 match the exclusion patterns will not be searched."""
879 if not exclude_patterns:
880 exclude_patterns = []
882 result = glob(roots, patterns, exclude_patterns)
883 subdirs = [s for s in glob(roots, ["*"]) if s != "." and s != ".." and os.path.isdir(s)]
885 result.extend(glob_tree(subdirs, patterns, exclude_patterns))
889 def glob_in_parents(dir, patterns, upper_limit=None):
890 """Recursive version of GLOB which glob sall parent directories
891 of dir until the first match is found. Returns an empty result if no match
894 assert(isinstance(dir, str))
895 assert(isinstance(patterns, list))
899 absolute_dir = os.path.join(os.getcwd(), dir)
900 absolute_dir = os.path.normpath(absolute_dir)
902 new_dir = os.path.split(absolute_dir)[0]
903 if new_dir == absolute_dir:
905 result = glob([new_dir], patterns)
908 absolute_dir = new_dir
913 # The relpath functionality is written by
915 def split(p, rest=[]):
916 (h,t) = os.path.split(p)
917 if len(h) < 1: return [t]+rest
918 if len(t) < 1: return [h]+rest
919 return split(h,[t]+rest)
921 def commonpath(l1, l2, common=[]):
922 if len(l1) < 1: return (common, l1, l2)
923 if len(l2) < 1: return (common, l1, l2)
924 if l1[0] != l2[0]: return (common, l1, l2)
925 return commonpath(l1[1:], l2[1:], common+[l1[0]])
928 (common,l1,l2) = commonpath(split(p1), split(p2))
931 p = [ '../' * len(l1) ]
934 return os.path.join( *p )