1 ! Copyright (C) 2004, 2008 Slava Pestov, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors combinators io.backend kernel math math.order
4 namespaces sequences splitting strings system ;
7 SYMBOL: current-directory
9 : path-separator? ( ch -- ? ) os windows? "/\\" "/" ? member? ;
11 : path-separator ( -- string ) os windows? "\\" "/" ? ;
13 : trim-right-separators ( str -- newstr )
14 [ path-separator? ] trim-right ;
16 : trim-left-separators ( str -- newstr )
17 [ path-separator? ] trim-left ;
19 : last-path-separator ( path -- n ? )
20 [ length 1- ] keep [ path-separator? ] find-last-from ;
22 HOOK: root-directory? io-backend ( path -- ? )
24 M: object root-directory? ( path -- ? )
25 [ f ] [ [ path-separator? ] all? ] if-empty ;
27 ERROR: no-parent-directory path ;
29 : parent-directory ( path -- parent )
32 dup last-path-separator [
37 { "" "." ".." } member? [
44 : head-path-separator? ( path1 ? -- ?' )
46 [ t ] [ first path-separator? ] if-empty
51 : head.? ( path -- ? ) "." ?head head-path-separator? ;
53 : head..? ( path -- ? ) ".." ?head head-path-separator? ;
55 : append-path-empty ( path1 path2 -- path' )
58 rest trim-left-separators append-path-empty
60 { [ dup head..? ] [ drop no-parent-directory ] }
66 : windows-absolute-path? ( path -- path ? )
68 { [ dup "\\\\?\\" head? ] [ t ] }
69 { [ dup length 2 < ] [ f ] }
70 { [ dup second CHAR: : = ] [ t ] }
74 : absolute-path? ( path -- ? )
76 { [ dup empty? ] [ f ] }
77 { [ dup "resource:" head? ] [ t ] }
78 { [ os windows? ] [ windows-absolute-path? ] }
79 { [ dup first path-separator? ] [ t ] }
83 : append-path ( str1 str2 -- str )
85 { [ over empty? ] [ append-path-empty ] }
86 { [ dup empty? ] [ drop ] }
87 { [ over trim-right-separators "." = ] [ nip ] }
88 { [ dup absolute-path? ] [ nip ] }
89 { [ dup head.? ] [ rest trim-left-separators append-path ] }
91 2 tail trim-left-separators
92 [ parent-directory ] dip append-path
94 { [ over absolute-path? over first path-separator? and ] [
98 [ trim-right-separators "/" ] dip
99 trim-left-separators 3append
103 : prepend-path ( str1 str2 -- str )
104 swap append-path ; inline
106 : file-name ( path -- string )
107 dup root-directory? [
108 trim-right-separators
109 dup last-path-separator [ 1+ tail ] [
110 drop "resource:" ?head [ file-name ] when
114 : file-extension ( filename -- extension )
115 "." split1-last nip ;
117 : resource-path ( path -- newpath )
118 "resource-path" get prepend-path ;
120 GENERIC: (normalize-path) ( path -- path' )
122 M: string (normalize-path)
124 trim-left-separators resource-path
127 current-directory get prepend-path
130 M: object normalize-path ( path -- path' )
133 TUPLE: pathname string ;
135 C: <pathname> pathname
137 M: pathname (normalize-path) string>> (normalize-path) ;
139 M: pathname <=> [ string>> ] compare ;
141 HOOK: home io-backend ( -- dir )
143 M: object home "" resource-path ;