Imported Upstream version 1.57.0
[platform/upstream/boost.git] / tools / build / src / util / path.py
1 # Status: this module is ported on demand by however needs something
2 # from it.  Functionality that is not needed by Python port will
3 # be dropped.
4
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.
9
10 #  Performs various path manipulations. Path are always in a 'normilized' 
11 #  representation. In it, a path may be either:
12 #
13 #     - '.', or
14 #
15 #     - ['/'] [ ( '..' '/' )*  (token '/')* token ]
16
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
19 #   of slash only.
20
21 import os.path
22 from utility import to_seq
23 from glob import glob as builtin_glob
24
25 from b2.util import bjam_signature
26
27 @bjam_signature((["path", "root"],))
28 def root (path, root):
29     """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.
30     """
31     if os.path.isabs (path):
32         return path
33     else:
34         return os.path.join (root, path)
35
36 @bjam_signature((["native"],))
37 def make (native):
38     """ Converts the native path into normalized form.
39     """
40     # TODO: make os selection here.
41     return make_UNIX (native)
42
43 def make_UNIX (native):
44
45     # VP: I have no idea now 'native' can be empty here! But it can!
46     assert (native)
47
48     return os.path.normpath (native)
49
50 @bjam_signature((["path"],))
51 def native (path):
52     """ Builds a native representation of the path.
53     """
54     # TODO: make os selection here.
55     return native_UNIX (path)
56
57 def native_UNIX (path):
58     return path
59
60
61 def pwd ():
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.
65     """
66     return make (os.getcwd ())
67
68 def is_rooted (path):
69     """ Tests if a path is rooted.
70     """
71     return path and path [0] == '/'
72
73
74 ###################################################################
75 # Still to port.
76 # Original lines are prefixed with "#   "
77 #
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.
82 #   
83 #   #  Performs various path manipulations. Path are always in a 'normilized' 
84 #   #  representation. In it, a path may be either:
85 #   #
86 #   #     - '.', or
87 #   #
88 #   #     - ['/'] [ ( '..' '/' )*  (token '/')* token ]
89 #   # 
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
92 #   #   of slash only.
93 #   
94 #   import modules ;
95 #   import sequence ;
96 #   import regex ;
97 #   import errors : error ;
98 #   
99 #   
100 #   os = [ modules.peek : OS ] ;
101 #   if [ modules.peek : UNIX ] 
102 #   {    
103 #       local uname = [ modules.peek : JAMUNAME ] ;
104 #       switch $(uname)
105 #       {
106 #           case CYGWIN* :
107 #             os = CYGWIN ;
108 #           
109 #           case * :
110 #             os = UNIX ;
111 #       }        
112 #   }
113 #   
114 #   #
115 #   #    Tests if a path is rooted.
116 #   #
117 #   rule is-rooted ( path )
118 #   {
119 #       return [ MATCH "^(/)" : $(path) ] ;
120 #   }
121 #   
122 #   #
123 #   #    Tests if a path has a parent.
124 #   #
125 #   rule has-parent ( path )
126 #   {
127 #       if $(path) != / {
128 #           return 1 ;
129 #       } else {
130 #           return ;
131 #       }
132 #   }
133 #   
134 #   #
135 #   #    Returns the path without any directory components.
136 #   #
137 #   rule basename ( path )
138 #   {
139 #       return [ MATCH "([^/]+)$" : $(path) ] ;
140 #   }
141 #   
142 #   #
143 #   #    Returns parent directory of the path. If no parent exists, error is issued.
144 #   #
145 #   rule parent ( path )
146 #   {
147 #       if [ has-parent $(path) ] {
148 #   
149 #           if $(path) = . {
150 #               return .. ;
151 #           } else {
152 #   
153 #               # Strip everything at the end of path up to and including
154 #               # the last slash
155 #               local result = [ regex.match "((.*)/)?([^/]+)" : $(path) : 2 3 ] ;
156 #   
157 #               # Did we strip what we shouldn't?
158 #               if $(result[2]) = ".." {
159 #                   return $(path)/.. ;
160 #               } else {
161 #                   if ! $(result[1]) {
162 #                       if [ is-rooted $(path) ] {
163 #                           result = / ;
164 #                       } else {
165 #                           result = . ;
166 #                       }
167 #                   }
168 #                   return $(result[1]) ;
169 #               }
170 #           }
171 #       } else {
172 #           error "Path '$(path)' has no parent" ;
173 #       }
174 #   }
175 #   
176 #   #
177 #   #    Returns path2 such that "[ join path path2 ] = .".
178 #   #    The path may not contain ".." element or be rooted.
179 #   #
180 #   rule reverse ( path )
181 #   {
182 #       if $(path) = .
183 #       {
184 #           return $(path) ;
185 #       }
186 #       else
187 #       {
188 #           local tokens = [ regex.split $(path) "/" ] ;
189 #           local tokens2 ;
190 #           for local i in $(tokens) {
191 #               tokens2 += .. ;
192 #           }
193 #           return [ sequence.join $(tokens2) : "/" ] ;
194 #       }
195 #   }
196 def reverse(path):
197     """Returns path2 such that `os.path.join(path, path2) == '.'`.
198     `path` may not contain '..' or be rooted.
199
200     Args:
201         path (str): the path to reverse
202
203     Returns:
204         the string of the reversed path
205
206     Example:
207
208         >>> p1 = 'path/to/somewhere'
209         >>> p2 = reverse('path/to/somewhere')
210         >>> p2
211         '../../..'
212         >>> os.path.normpath(os.path.join(p1, p2))
213         '.'
214     """
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')
219     if path == '.':
220         return 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))
225 #   #
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.
229 #   #
230 #   local rule join-imp ( elements + )
231 #   {
232 #       return [ NORMALIZE_PATH $(elements:J="/") ] ;
233 #   }
234 #   
235 #   #
236 #   #    Contanenates the passed path elements. Generates an error if
237 #   #    any element other than the first one is rooted.
238 #   #
239 #   rule join ( elements + )
240 #   {
241 #       if ! $(elements[2]) 
242 #       {
243 #           return $(elements[1]) ;
244 #       }
245 #       else
246 #       {        
247 #           for local e in $(elements[2-])
248 #           {
249 #               if [ is-rooted $(e) ]
250 #               {
251 #                   error only first element may be rooted ;
252 #               }
253 #           }
254 #           return [ join-imp $(elements) ] ;
255 #       }    
256 #   }
257
258
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.
269     
270     For example: 
271         [ glob . : *.cpp ] 
272         [ glob . : */build/Jamfile ] 
273     """
274 #   {
275 #       local result ;
276 #       if $(patterns:D)
277 #       {
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)
281 #           {
282 #               # First glob for directory part.
283 #               local globbed-dirs = [ glob $(dirs) : $(p:D) ] ;
284 #               result += [ glob $(globbed-dirs) : $(p:D="") ] ;
285 #           }        
286 #       }
287 #       else
288 #       {        
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
292 #           # needed so that 
293 #           #
294 #           #    [ glob libs/*/Jamfile ]
295 #           #
296 #           # don't return 
297 #           #
298 #           #    libs/../Jamfile (which is the same as ./Jamfile)
299 #           #
300 #           # On the other hand, when ".." is explicitly present in the pattern
301 #           # we need to return it.
302 #           # 
303 #           for local dir in $(dirs)
304 #           {
305 #               for local p in $(patterns)
306 #               {                
307 #                   if $(p) != ".."
308 #                   {                
309 #                       result += [ sequence.transform make 
310 #                           : [ GLOB [ native $(dir) ] : $(p) ] ] ;
311 #                   }            
312 #                   else
313 #                   {
314 #                       result += [ path.join $(dir) .. ] ;
315 #                   }            
316 #               }            
317 #           }
318 #       }    
319 #       return $(result) ;
320 #   }
321 #   
322
323 # TODO: (PF) I replaced the code above by this. I think it should work but needs to be tested.
324     result = []
325     dirs = to_seq (dirs)
326     patterns = to_seq (patterns)
327
328     splitdirs = []
329     for dir in dirs:
330         splitdirs += dir.split (os.pathsep)
331
332     for dir in splitdirs:
333         for pattern in patterns:
334             p = os.path.join (dir, pattern)
335             import glob
336             result.extend (glob.glob (p))
337     return result
338     
339 #
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.
343 #
344 def all_parents(path, upper_limit=None, cwd=None):
345
346     if not cwd:
347         cwd = os.getcwd()
348
349     path_abs = os.path.join(cwd, path)
350
351     if upper_limit:
352         upper_limit = os.path.join(cwd, upper_limit)
353
354     result = []
355     while path_abs and path_abs != upper_limit:
356         (head, tail) = os.path.split(path)
357         path = os.path.join(path, "..")        
358         result.append(path)
359         path_abs = head
360
361     if upper_limit and path_abs != upper_limit:
362         raise BaseException("'%s' is not a prefix of '%s'" % (upper_limit, path))
363
364     return result
365     
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.
368 #
369 def glob_in_parents(dir, patterns, upper_limit=None):
370
371     result = []
372     parent_dirs = all_parents(dir, upper_limit)
373
374     for p in parent_dirs:
375         result = glob(p, patterns)
376         if result: break
377
378     return result
379
380 #   
381 #   #
382 #   # Assuming 'child' is a subdirectory of 'parent', return the relative
383 #   # path from 'parent' to 'child'
384 #   #
385 #   rule relative ( child parent )
386 #   {
387 #       if $(parent) = "." 
388 #       {
389 #           return $(child) ;
390 #       }
391 #       else 
392 #       {       
393 #           local split1 = [ regex.split $(parent) / ] ;
394 #           local split2 = [ regex.split $(child) / ] ;
395 #       
396 #           while $(split1)
397 #           {
398 #               if $(split1[1]) = $(split2[1])
399 #               {
400 #                   split1 = $(split1[2-]) ;
401 #                   split2 = $(split2[2-]) ;
402 #               }
403 #               else
404 #               {
405 #                   errors.error $(child) is not a subdir of $(parent) ;
406 #               }                
407 #           }    
408 #           return [ join $(split2) ] ;    
409 #       }    
410 #   }
411 #   
412 #   # Returns the minimal path to path2 that is relative path1.
413 #   #
414 #   rule relative-to ( path1 path2 )
415 #   {
416 #       local root_1 = [ regex.split [ reverse $(path1) ] / ] ;
417 #       local split1 = [ regex.split $(path1) / ] ;
418 #       local split2 = [ regex.split $(path2) / ] ;
419 #   
420 #       while $(split1) && $(root_1)
421 #       {
422 #           if $(split1[1]) = $(split2[1])
423 #           {
424 #               root_1 = $(root_1[2-]) ;
425 #               split1 = $(split1[2-]) ;
426 #               split2 = $(split2[2-]) ;
427 #           }
428 #           else
429 #           {
430 #               split1 = ;
431 #           }
432 #       }
433 #       return [ join . $(root_1) $(split2) ] ;
434 #   }
435
436 # Returns the list of paths which are used by the operating system
437 # for looking up programs
438 def programs_path ():
439     raw = []
440     names = ['PATH', 'Path', 'path']
441     
442     for name in names:
443         raw.append(os.environ.get (name, ''))
444     
445     result = []
446     for elem in raw:
447         if elem:
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.
452                 if p:
453                     result.append(make(p))
454
455     return result
456
457 #   rule make-NT ( native )
458 #   {
459 #       local tokens = [ regex.split $(native) "[/\\]" ] ;
460 #       local result ;
461 #   
462 #       # Handle paths ending with slashes
463 #       if $(tokens[-1]) = ""
464 #       {
465 #           tokens = $(tokens[1--2]) ; # discard the empty element
466 #       }
467 #   
468 #       result = [ path.join $(tokens) ] ;
469 #   
470 #       if [ regex.match "(^.:)" : $(native)  ]
471 #       {
472 #           result = /$(result) ;
473 #       }
474 #       
475 #       if $(native) = ""
476 #       {
477 #           result = "." ;
478 #       }
479 #           
480 #       return $(result) ;
481 #   }
482 #   
483 #   rule native-NT ( path )
484 #   {
485 #       local result = [ MATCH "^/?(.*)" : $(path) ] ;
486 #       result = [ sequence.join [ regex.split $(result) "/" ] : "\\" ] ;
487 #       return $(result) ;
488 #   }
489 #   
490 #   rule make-CYGWIN ( path )
491 #   {
492 #       return [ make-NT $(path) ] ;
493 #   }
494 #   
495 #   rule native-CYGWIN ( path )
496 #   {
497 #       local result = $(path) ;
498 #       if [ regex.match "(^/.:)" : $(path)  ] # win absolute
499 #       {
500 #           result = [ MATCH "^/?(.*)" : $(path) ] ; # remove leading '/'
501 #       }
502 #       return [ native-UNIX $(result) ] ;
503 #   }
504 #   
505 #   #
506 #   # split-VMS: splits input native path into
507 #   # device dir file (each part is optional),
508 #   # example:
509 #   #
510 #   # dev:[dir]file.c => dev: [dir] file.c
511 #   #
512 #   rule split-path-VMS ( native )
513 #   {
514 #       local matches = [ MATCH ([a-zA-Z0-9_-]+:)?(\\[[^\]]*\\])?(.*)?$   : $(native) ] ;
515 #       local device = $(matches[1]) ;
516 #       local dir = $(matches[2]) ;
517 #       local file = $(matches[3]) ;
518 #   
519 #       return $(device) $(dir) $(file) ;
520 #   }
521 #   
522 #   #
523 #   # Converts a native VMS path into a portable path spec.
524 #   #
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.
528 #   #
529 #   # Adds a trailing dot (".") to the file part if no extension
530 #   # is present (helps when converting it back into native path).
531 #   #
532 #   rule make-VMS ( native )
533 #   {
534 #       if [ MATCH ^(\\[[a-zA-Z0-9]) : $(native) ]
535 #       {
536 #           errors.error "Can't handle default-device absolute paths: " $(native) ;
537 #       }
538 #           
539 #       local parts = [ split-path-VMS $(native) ] ;
540 #       local device = $(parts[1]) ;
541 #       local dir = $(parts[2]) ;
542 #       local file = $(parts[3]) ;
543 #       local elems ;
544 #       
545 #       if $(device)
546 #       {
547 #           #
548 #           # rooted
549 #           #
550 #           elems = /$(device) ;
551 #       }
552 #       
553 #       if $(dir) = "[]"
554 #       {
555 #           #
556 #           # Special case: current directory
557 #           #
558 #           elems = $(elems) "." ;
559 #       }
560 #       else if $(dir)
561 #       {
562 #           dir = [ regex.replace $(dir) "\\[|\\]" "" ] ;
563 #           local dir_parts = [ regex.split $(dir) \\. ]  ;
564 #       
565 #           if $(dir_parts[1]) = ""
566 #           {
567 #               #
568 #               # Relative path
569 #               #
570 #               dir_parts = $(dir_parts[2--1]) ;
571 #           }
572 #           
573 #           #
574 #           # replace "parent-directory" parts (- => ..)
575 #           #
576 #           dir_parts = [ regex.replace-list $(dir_parts) : - : .. ] ;
577 #           
578 #           elems = $(elems) $(dir_parts) ;
579 #       }
580 #       
581 #       if $(file)
582 #       {
583 #           if ! [ MATCH (\\.) : $(file) ]
584 #           {
585 #               #
586 #               # Always add "." to end of non-extension file
587 #               #
588 #               file = $(file). ;
589 #           }
590 #           elems = $(elems) $(file) ;
591 #       }
592 #   
593 #       local portable = [ path.join $(elems) ] ;
594 #   
595 #       return $(portable) ;
596 #   }
597 #   
598 #   #
599 #   # Converts a portable path spec into a native VMS path.
600 #   #
601 #   # Relies on having at least one dot (".") included in the file
602 #   # name to be able to differentiate it ftom the directory part.
603 #   #
604 #   rule native-VMS ( path )
605 #   {
606 #       local device = "" ;
607 #       local dir = $(path) ;
608 #       local file = "" ;
609 #       local native ;
610 #       local split ;
611 #   
612 #       #
613 #       # Has device ?
614 #       #
615 #       if [ is-rooted $(dir) ]
616 #       {
617 #           split = [ MATCH ^/([^:]+:)/?(.*) : $(dir) ] ;
618 #           device = $(split[1]) ;
619 #           dir = $(split[2]) ;
620 #       }
621 #   
622 #       #
623 #       # Has file ?
624 #       #
625 #       # This is no exact science, just guess work:
626 #       #
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).
631 #       #
632 #       split = [ regex.split $(dir) / ] ;
633 #       local maybe_file = $(split[-1]) ;
634 #   
635 #       if [ MATCH ^([^.]+\\..*) : $(maybe_file) ]
636 #       {
637 #           file = $(maybe_file) ;
638 #           dir = [ sequence.join $(split[1--2]) : / ] ;
639 #       }
640 #       
641 #       #
642 #       # Has dir spec ?
643 #       #
644 #       if $(dir) = "."
645 #       {
646 #           dir = "[]" ;
647 #       }
648 #       else if $(dir)
649 #       {
650 #           dir = [ regex.replace $(dir) \\.\\. - ] ;
651 #           dir = [ regex.replace $(dir) / . ] ;
652 #   
653 #           if $(device) = ""
654 #           {
655 #               #
656 #               # Relative directory
657 #               # 
658 #               dir = "."$(dir) ;
659 #           }
660 #           dir = "["$(dir)"]" ;
661 #       }
662 #       
663 #       native = [ sequence.join $(device) $(dir) $(file) ] ;
664 #   
665 #       return $(native) ;
666 #   }
667 #   
668 #   
669 #   rule __test__ ( ) {
670 #   
671 #       import assert ;
672 #       import errors : try catch ;
673 #   
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" ;
680 #   
681 #       assert.true has-parent "foo" ;
682 #       assert.true has-parent "foo/bar" ;
683 #       assert.true has-parent "." ;
684 #       assert.result : has-parent "/" ;
685 #   
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" ;
692 #   
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" ;
699 #   
700 #   
701 #       assert.result "." : reverse "." ;
702 #       assert.result ".." : reverse "foo" ;
703 #       assert.result "../../.." : reverse "foo/bar/giz" ;
704 #   
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" ".." ;
717 #   
718 #       assert.result /a/b : join /a/b/c .. ;
719 #   
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" ;
723 #   
724 #       try ;
725 #       {
726 #           join "a" "/b" ;
727 #       }
728 #       catch only first element may be rooted ;
729 #   
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) ;
735 #   
736 #       local CWD = "/home/ghost" ;
737 #       assert.result . .. : all-parents "Jamfile" : "/home" : $(CWD) ;
738 #       assert.result . : all-parents "Jamfile" : "/home/ghost" : $(CWD) ;
739 #       
740 #       assert.result "c/d" : relative "a/b/c/d" "a/b" ;
741 #       assert.result "foo" : relative "foo" "." ;
742 #   
743 #       local save-os = [ modules.peek path : os ] ;
744 #       modules.poke path : os : NT ;
745 #   
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" ;
752 #   
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" ;
756 #   
757 #       modules.poke path : os : UNIX ;
758 #   
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" ;
765 #   
766 #       modules.poke path : os : VMS ;
767 #   
768 #       #
769 #       # Don't really need to poke os before these
770 #       #
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 "" ;
779 #   
780 #       #
781 #       # Special case: current directory
782 #       #
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" ;
787 #   
788 #       #
789 #       # Make portable paths
790 #       #
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" ;
802 #   
803 #       #
804 #       # Special case (adds '.' to end of file w/o extension to
805 #       # disambiguate from directory in portable path spec).
806 #       #
807 #       assert.result "Jamfile." : make "Jamfile" ;
808 #       assert.result "dir/Jamfile." : make "[.dir]Jamfile" ;
809 #       assert.result "/disk:/dir/Jamfile." : make "disk:[dir]Jamfile" ;
810 #   
811 #       #
812 #       # Make native paths
813 #       #
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." ;
824 #   
825 #       modules.poke path : os : $(save-os) ;
826 #   
827 #   }
828
829 #
830
831
832 #def glob(dir, patterns):
833 #    result = []
834 #    for pattern in patterns:
835 #        result.extend(builtin_glob(os.path.join(dir, pattern)))
836 #    return result
837
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.
848     For example: 
849         [ glob . : *.cpp ] 
850         [ glob . : */build/Jamfile ]
851     """
852
853     assert(isinstance(patterns, list))
854     assert(isinstance(dirs, list))
855
856     if not exclude_patterns:
857         exclude_patterns = []
858     else:
859        assert(isinstance(exclude_patterns, list))
860
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
863                              for d in dirs]
864
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]
870
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."""
878
879     if not exclude_patterns:
880         exclude_patterns = []
881
882     result = glob(roots, patterns, exclude_patterns)
883     subdirs = [s for s in glob(roots, ["*"]) if s != "." and s != ".." and os.path.isdir(s)]
884     if subdirs:
885         result.extend(glob_tree(subdirs, patterns, exclude_patterns))
886         
887     return result
888
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
892     is found"""    
893     
894     assert(isinstance(dir, str))
895     assert(isinstance(patterns, list))
896
897     result = []
898
899     absolute_dir = os.path.join(os.getcwd(), dir)
900     absolute_dir = os.path.normpath(absolute_dir)
901     while absolute_dir:
902         new_dir = os.path.split(absolute_dir)[0]
903         if new_dir == absolute_dir:
904             break
905         result = glob([new_dir], patterns)
906         if result:
907             break
908         absolute_dir = new_dir
909
910     return result
911
912
913 # The relpath functionality is written by
914 # Cimarron Taylor
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)
920
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]])
926
927 def relpath(p1, p2):
928     (common,l1,l2) = commonpath(split(p1), split(p2))
929     p = []
930     if len(l1) > 0:
931         p = [ '../' * len(l1) ]
932     p = p + l2
933     if p:
934         return os.path.join( *p )
935     else:
936         return "."