123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876(*
* Path - Path and directory manipulation
* Copyright (C) 2008 Dawid Toton
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)(* TODO
- test PathGen.OfRope
- what about path components of length 0?
- test on Windows
- decide about platform-dependent val compare : t -> t -> int (useless?)
- adopt from legacy Filename: is_implicit, check_suffix, chop_suffix, chop_extension, quote
In related modules:
- Windows: read directories and open files using Unicode functions
- Directory.exists, Directory.make, etc.
*)(* ----------------------- Copy of (most of) Path.mli
How to avoid having the copy here?
*)(** This signature lists few basic operations provided by all string types. *)moduletypeStringType=sig(** The actual implementation may use any (coherent) scheme of indexing of strings. Below the term 'indexing unit' can stay either for byte or character (or whatever employed by the implementation).
This determines meaning of all [int] arguments and results (excluding result of [compare]).
*)typet(** Type for strings. *)vallength:t->int(** Length - number of indexing units *)typetcharvalget:t->int->tcharvallift_char:char->tcharvallift:string->t(** Convert from UTF-8 encoded string of primitive [string] type.
*)(*
[PathGen] implementation requires [lift] to understand few characters which all have codes <128.
Therefore [PathGen] can live with either latin1 or UTF-8 put into any primitive strings.
[PathGen.OfString] uses [Str], which is byte-oriented and happy with UTF-8.
However, if encoding of the argument of [lift] was left unspecified,
it would be unusable outside this module.
Sice primitive strings are UTF-8 encoded almost everywhere, we want to be UTF-8 friendly here.
*)valto_string:t->stringvalconcat_with_separators:t->tlist->t(** [concat_with_separators sep lst] catenates all {i n} elements of [lst] inserting {i (n-1)} copies of [sep] in between. *)valcompare:t->t->int(** Usual comparison function. *)valiter:(tchar->unit)->t->unitvaliteri :(int->tchar ->unit)->t->unitvalsub:t->int-> int->t(** As {!String.sub}, but indexed in specific way. *)valrindex:t->char->intmoduleParse:sigvalsource:t->(tchar,BatCharParser.position)BatParserCo.Source.tvalletter:(tchar,tchar,BatCharParser.position)BatParserCo.tendend(** All implementations of [Path] functionality have this module type. *)moduletypePathType=sigtypeustring(** Type of strings used. In case of {!Path.OfRope} it is {!Rope.t} and in {!Path.OfString} module it is [string].
*)typeuchar(** Type of characters. It corresponds to [ustring] type. *)(** Convenience operator for lifting primitive strings to [ustring] type.
@documents Future.Path.OperatorLift
*)moduleOperatorLift:sigval(!!):string->ustring(** Prefix operator that converts primitive string to [ustring]. May raise some exceptions depending on actual strings implementation.
You might want to [open Path.OperatorLift] to improve readability of path construction using string literals. Example:
[Path.root/:!!"foo"/:!!"bar"] = [Path.root/:(S.lift "foo")/:(S.lift "bar")] (where [S.lift] converts to [ustring] type)
*)endtypet=ustringlist(** A type for storing paths. It is reversed list of names. In case of absolute path, the last element of the list is empty string ({e Windows:} empty or letter-colon; details below). Empty list represents empty relative path.
Examples: [\["a";"b";"c"\]] is c/b/a (relative path); [\["d";"e";""\]] stays for /e/d (absolute path).
All examples here and below are given for [ustring]=[string] case for clarity. To have the code working with other string types, one should prepend the [!!] operator ({!OperatorLift.(!!)}) to all string literals.
There are two infix operators provided to allow to write expressions in natural order. For example, to build a path using {!PathType.Operators.(/:)} one can write:
[base_dir/:"bar"] instead of ["bar"::base_dir]
However it may be sometimes inevitable to write components in reverse, for example:
[let whose_readme = function "README"::app::"doc"::"share"::_ -> Some app | _ -> None]
{e Windows:} Windows absolute paths start with "\\" or with drive letter. Use following representation:
- [Path.root/:"."/:"pipe" = \["pipe";".";""\]] for "\\.\pipe"
- [\["C:"\]/:"foo" = \["foo";"C:"\]] for "C:\foo"
In principle the first type of paths has broader range of allowed characters, but this implementation applies more strict rules to both ({!default_validator}).
*)(* If we wanted more safety, we'd have (making usage inconvenient):
type t = private P of ustring list
*)valis_relative:t->boolvalis_absolute:t-> bool(** {6 Construction} *)valroot:t(** Root of the filesystem ([\[""\]]). It is minimal absolute path. Below it is called 'empty'. However it yields "/" or "\\" when converted to a string.
{e Windows:} This path (root and nothing more) is meaningless, but for simplicity it is considered valid here. To create absolute path starting with drive letter, construct the list explicitly (as in [\["C:"\]/:"foo"]).
A path consisting of drive letter only is also called 'empty' here.
*)(* ocamldoc problem: try to get double_quot-backslash-double_quot in a docstring! *)valappend:t->ustring->t(** Alternative name for {!Operators.(/:)} *)valconcat:t->t->t(** Alternative name for {!Operators.(//@)} *)(**
Infix operators for path construction. They are in separate module, so one can [open Path.Operators] to use them.
@documents Future.Path.Operators
*)moduleOperators:sigval(/:):t->ustring->t(** [path/:name] is a path of [name] located in a directory [path]. For example:
- {!PathType.root}[/:"var"/:"log"] builds absolute path "/var/log"
- [\[user\]/:".ssh"] can be either:
{ul {- absolute path "/.ssh" in case [user] is an empty string}
{- relative path otherwise}}
{!PathType.default_validator} is applied to the argument. [name] must not contain path separator (causes Illegal_char exception).
@raise Illegal_char (raised by validator on any bad character)
*)val(//@):t->t->t(** [basepath//\@relpath] catenates two paths.
{e Windows:} As a special exception it is possible to pass absolute path as [relpath], provided that [basepath] is simple absolute path (i.e. of the form [\[...; ""\]]) and [relpath] is not simple absolute path.
@raise Invalid_argument if the second argument is an absolute path ({e Windows:} see above). *)end(**
As other Operators modules in batteries are named "Infix" we provide Infix as well.
This is a mere copy of Operators.
*)moduleInfix:sigval(/:):t->ustring->tval(//@):t->t->tendexceptionMalformed_pathvalnormalize_filepath :t->t(**
Consumes single dots where possible, e.g.:
[normalize (\[".."\]/:"foo"/:"."/:"bar"/:"sub1"/:".."/:"sub2") = \[".."\]/:"foo"/:"bar"/:"sub1"/:".."/:"sub2"]
{e Windows:} If single dot is next to root, it is preserved.
*)valnormalize_in_graph:t->t(** Another name for {!normalize_filepath}. *)valnormalize_in_tree:t->t(**
Consumes single dots and applies double dots where possible, e.g.:
[normalize (\[".."\]/:"foo"/:"."/:"bar"/:"sub1"/:".."/:"sub2") = \[".."\]/:"foo"/:"bar"/:"sub2"]
{e Windows:} If single dot is next to root, it is preserved.
@raise Malformed_path when absolute path is given that contains double dots that would be applied to the root.
*)valnormalize:t->t(** Deprecated name for {!normalize_in_tree} *)valparent:t->t(** Returns parent path, i.e. immediate ancestor: [parent (foo/:bar) = foo]
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)valbelongs:t->t->bool(** [belongs base sub] is [true] when [sub] descends from [base], i.e. [base] is a prefix of [sub]. If [base]=[sub] the function returns [true]. It is otherwise [false].
Both arguments must be absolute paths or both relative.
If both arguments have a root portion with drive letter and these letters are different, [belongs base sub] returns false.
@raise Invalid_argument if exactly one of given arguments is absolute path
*) (* Should this function normalize its arguments? *)valrelative_to_any:t->t->t(** [relative_to_any base sub] returns relative path [rel] such that
[normalize (base/:rel) = normalize sub], i.e. common base is stripped and ".." are added if necessary.
Both arguments must be absolute paths or both relative.
This function normalizes [base] and [sub] before calculation of the relative path.
{e Windows:} If [base] and [sub] are absolute, they must have the same root element: have the same drive letter or both starting with {!root} (i.e. [""] is the last element of the list).
Exceptionally it is possible to get an absolute path as a result if drive letter is in [sub] but not as a root element (e .g. [base = root/:"bar"] and [sub = root/:bar//@(\["C:"\]/:"foo"]).
@see 'relative_to_parent' may be sometimes more suitable
@raise Invalid_argument if exactly one of given arguments is an absolute path
@raise Malformed_path if normalization fails (see {!PathType.normalize})
*)exceptionNot_parentvalrelative_to_parent :t->t->t(** [relative_to_parent parent sub] returns relative path [rel] such that
[(normalize parent)/:rel = normalize sub]. It is checked if [parent] is really a parent of [sub].
Both arguments must be absolute paths or both relative.
This function normalizes [base] and [sub] before calculation of the relative path.
{e Windows:} Exceptionally it is possible to get an absolute path as a result if drive letter is in [sub] but not as a root element (e .g. [base = root/:"bar"] and [sub = root/:bar//@(\["C:"\]/:"foo")]).
@raise Not_parent if [sub] is not descendant of [parent]
@raise Invalid_argument if exactly one of given arguments is absolute path
@raise Malformed_path if normalization fails (see {!PathType.normalize})
*)(** {6 Validation} *)exceptionIllegal_char(** Raised by {!PathType.of_string}, {!PathType.append} and {!PathType.Operators.(/:)} when used validator finds illegal character. *)typevalidator=ustring->bool(**
Validators should check if all characters of given string can be used in a name (path component). Return true if the name is valid. Return false if illegal character is found.
If a name should be rejected for some other reason, user defined validator may raise an exception.
*)valdefault_validator:validatorref(**
Forward slash and code zero are considered invalid.
{e Windows:} Invalid characters are *?:\/<> and all with code <32. Exception: the function {!PathType.of_string} doesn't use validator against drive letter with colon.
*)(*TODO: Windows:
On reserved names and ones ending with dot (except "." and "..") Illegal_name is raised.
*)(** {6 Conversions} *)valto_ustring:t->ustring(** Convert to the chosen [ustring] type. Empty relative path is converted to "." (single dot).
{e Windows:} backslash is used as a separator and double backslash for root. If the path is only a drive letter (empty absolute path) trailing backslash is added (e.g. [to_string \["C:"\] = "C:\"]).
@see 'to_string' is likely to bo more useful
"*)(* Dangling quote character because of ocamldoc lexer being apparently incompatible with OCaml. *)valto_string:t->string(** Convert to type primitive string with UTF-8 content. The string is built in the same way as by [to_ustring] function. *)valof_string:ustring->t(** Parse path in a given string. Any number of consecutive separators collapse ("a//b" becomes "a/b"). [Path.default_validator] is applied to each resulting name.
{e Windows:} both slashes '\' and '/' are accepted as separators. Paths of the 'semi-relative' form "C:foo\bar" are not recognized. For example "C:" string is parsed as [\["C:"\]] which has different meaning (see {!to_string}).
@raise Illegal_char when a character not allowed in paths is found.
*)(** {7 Convenience aliases} *)vals:t->string(** = {!to_string} *)valp:ustring->t(** = {!of_string} *)(** {6 Name related functions}
These functions do not accept empty paths, i.e. [\[\]], [\[""\]] or [\["C:"\]].
*)valname:t->ustring(** Returns name of the object the pathname points to, i.e.
[name (foo/:bar) = bar]
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)valmap_name:(ustring->ustring)->t->t(** [map_name fu path] returns [path] with the name replaced by [fu (]{!PathType.name}[ path)].
Example: [map_name (fun nn -> nn ^ ".backup") (["foo"]/:"bar") = ["foo"]/:"bar.backup"]
{!PathType.default_validator} is applied to new name.
@raise Illegal_char (raised by validator if any bad character is found)
*)valext:t->ustringoption(** Returns extension of the name of the object the pathname points to. Examples:
[ext ["aa.bb"] = Some "bb"]
[ext ["aa."] = Some ""]
[ext ["aa"] = None]
[ext [".hidden"] = Some "hidden"] {e (!)}
Extension begins where the rightmost dot in the name is found. If the name ends with a dot, the extension is empty and [Some ""] is returned. If there is no extension (no dot) the function returns [None].
@example "Count unfinished music downloads (files ending with '.ogg.part')."
{[
let count_music_parts download_dir =
let files = Directory.files download_dir in
let check file =
match Path.ext file with
| Some "part" -> ((Path.ext (Path.name_core file)) = "ogg")
| _ -> false
in
let music_parts = List.filter check files in
List.length music_parts
]}
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)valmap_ext:(ustringoption->ustringoption)->t->t(** [map_ext fu path] returns [path] but with the name with extension given by [fu (]{!PathType.ext}[ path)]. If [fu] returns [Some _], the original extension may be replaced (when [Some ext] is passed to [fu]) or new added (when [fu] gets [None]). In case [fu] returns [None], the extension is removed (if exists).
@example "A name for file being encoded in a new format."
{[
let pngname file = map_ext (function Some _ | None -> Some "png") file
let new_bar = pngname (["foo"]/:"bar.jpeg") (* = ["foo"]/:"bar.png" *)
]}
{!PathType.default_validator} is applied to the resulting name.
The replacement string returned by the mapping function [fu] can contain dots. Consequently, this string doesn't need to be an extension as defined by the {!ext} function. Consider for example:
{[
let before = foo/:"bar.mli"
let replacement = "mli.off"
let ext_before = Path.ext before (* = Some "mli" *)
let after = Path.map_ext (fun _ -> Some replacement) before (* = foo/:"bar.mli.off" *)
let ext_after = Path.ext after (* = Some "off" *)
]}
Note the difference between [replacement] and [ext_after]!
[(map_ext fu)] is idempotent only if [fu] always returns [Some _]. Otherwise it can remove the extension, possibly exposing part of the name that becomes the new extension.
{e Windows:} If [fu] returns [Some ""] (to make a name with trailing period) [map_ext] returns a path that shouldn't be passed to the operating system (it is invalid).
@raise Illegal_char (raised by validator if any bad character is found)
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)valname_core:t->ustring(**
Returns part of the name to the left of rightmost dot. Returns empty string if the name starts with a dot.
@example "Label for a piece of GUI in which a file is edited."
{[
let tab_label modified file =
let text = (if modified then "*" else "") ^ (Path.name_core file) in
GMisc.label ~text ()
]}
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)typecomponents=t*ustring*ustringoption(** A [path] can be represented by the following triple:
[(Path.parent path, Path.name_core path, Path.ext path)]
*)valsplit:t->components(** Dissect the path to its components (parent path, core part of name and possibly an extension).
Resulting [name_core] string can be empty. For example,
[Path.split (Path.root/:"home"/:"user"/:".bashrc")] equals [(Path.root/:"home"/:"user", "", Some "bashrc")].
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
*)valjoin:components->t(** Create a path from given components.
@raise Illegal_char (raised by validator on any bad character)
@example "Creating paths for a series of numbered images."
{[
let get_animation_frames working_dir count =
let frame_file num = Path.join
(working_dir/:"rendering"
,"frame"^(stirng_of_int num)
,Some "png"
)
in
BatEnum.map frame_file (1 -- count)
]}
*)valmap:(components->components)->t->t(** Map a path through a function that operates on separate components.
@raise Illegal_char (raised by validator on any bad character)
@raise Invalid_argument if empty path (relative [\[\]] or absolute [\[""\]]) is given
@example "Insert a string just before file extension."
{[
let extract_first_page file =
let insert (parent, name_core, ext) = (parent, name_core ^ "_page1", ext) in
let result_file = Path.map insert file in
let code = Sys.command
(String.concat ' '
["psselect -p1 <"; P.s file
;" >"; P.s result_file
]
)
in
if code = 0 then result_file else failwith "psselect"
]}
*)(** {6 Supplementary functions} *)valdrive_letter:t->ucharoption(**
Return drive letter of the given absolute path.
{e Windows:} [drive_letter abs] returns [None] if [abs] is simple absolute path (i.e. begins with a separator), otherwise the root element of [abs] consists of a letter [ch] with a colon - in this case [Some ch] is returned.
{e Other systems:} Returns [None] on all absolute paths.
@example "(Windows only) Are the locations on the same partition?"
{[let can_move_quickly ~path_from ~path_to =
(drive_letter path_from) = (drive_letter path_to)
]}
@raise Invalid_argument if relative path is given
*)end(* End of the copy *)moduleMake=functor(S:StringType)->structexceptionNot_parentexceptionIllegal_charexceptionMalformed_pathletwindows=matchSys.os_typewith|"Win32"->true|_->falsetypeustring=S.ttypeuchar=S.tcharletstrequals1s2=(S.compares1s2)=0letliftss=S.liftssmoduleOperatorLift =structlet(!!)=liftendopenOperatorLiftletfull_matchparsss=letparser_final =BatParserCo.(>>>)parsBatParserCo.eofinmatchBatParserCo.runparser_final(S.Parse.sourcess)with|BatPervasives.Ok_->true|_->false(* let full_match_none_of raw_excluded ss =
let excluded = List.map S.lift_char raw_excluded in
let pars = ParserCo.ignore_zero_plus (ParserCo.none_of excluded) in
full_match pars ss
*)letsplit_delimseparator_predss=letvirtual_sep=(-1,0)inletrev_separators =ref[virtual_sep]inlet seen_sep_begin=refNoneinletsee_sep_endssbsse=rev_separators :=(ssb,sse)::!rev_separatorsinletscanixch=match!seen_sep_begin,separator_predchwith|None,false ->()|None,true->seen_sep_begin:=Someix|Some_,true->()|Somessb,false->(seen_sep_begin:=None;see_sep_endssbix)inS.iteri scanss;(match!seen_sep_beginwith|None->()|Somessb->see_sep_endssb(S.length ss));letfold(right_sep_beg,result)(sep_beg,sep_end)=letbeg=sep_end inletthis_chunk=S.subssbeg(right_sep_beg-beg)in(sep_beg,this_chunk::result)inlet _,result =List.fold_leftfold(S.lengthss,[])!rev_separatorsinresult(* Returns true if windows and the argument is letter-colon, false otherwise *)letis_win_disk_letter=ifwindowsthenletpars=BatParserCo.(>>>)S.Parse.letter(BatParserCo.exactly(S.lift_char':'))in(funname->full_matchparsname)else(fun_->false)letisnulss=strequal!!""ssletisrootss=(isnulss)||(is_win_disk_letterss)letisdotss=strequal!!"."sslet isdotdotss=strequal!!".."sstypet=ustringlistletis_relativepath=matchList.revpathwith|nm::_whenisrootnm->false|_->trueletis_absolutepath=not(is_relativepath)let root=[!!""]typevalidator=ustring->boolletvalidator_none_of forbidden=letlifted_forbidden=List.mapS.lift_charforbiddeninletensurech=ifList.memchlifted_forbidden thenraise Illegal_charelse()in(funname->S.iterensurename;true)(* (funname -> full_match_none_of forbidden name) *)letvalidator_simple=validator_none_of['/';'\000']letvalidator_windows=validator_none_of['/';'\\';'*';'?';'<';'>';':';'\000';'\001';(*...*)'\031'](*TODO: improve the validator *)(* (fun name -> full_match_none_of forbidden name) *)letdefault_validator=ref(ifwindowsthenvalidator_windowselsevalidator_simple)letapply_default_validatorname=ifnot(!default_validator name)thenraiseIllegal_charelsenameletappendpathname=(apply_default_validatorname)::pathletconcatbasepathrelpath=letsimple_concat()=ifis_relative relpaththenrelpath@basepathelseinvalid_arg "PathGen.concat"inifwindowsthenbeginmatchbasepathwith|nm::_whenisnulnm->(* special rules *)beginmatchrelpathwith|nm:: _whenisnulnm->invalid_arg "PathGen.concat"|_->relpath@basepath(* allow drive-letter inside the path *)end|_->simple_concat()endelsesimple_concat()moduleOperators=structlet(/:)=appendlet(//@)=concatendmodule Infix=Operatorsletnormalize_gen~assume path=letcan_dotdot=matchassumewith|`Tree->true(* dealing with a tree => can apply ".." normally *)|`Graph->false(* dealing with a graph => ".." has special meaning *)inletrecdoitcbackpath=matchcback,path with|0,[]->[]|nn,[]->!!".."::(doit(nn-1)[])|0,[rt]whenisrootrt->path|_nn,[rt]whenisrootrt->raiseMalformed_path|_,dotdot::restwhencan_dotdot&&isdotdot dotdot->doit(cback+1)rest|0,[dot;nu]when windows&&(isdotdot)&&(isnulnu)->path|_nn,[dot;nu]whenwindows&&(isdotdot)&&(isnulnu)->raiseMalformed_path|_,dot::restwhenisdotdot->doitcbackrest|0,name::rest ->name::(doit 0rest)|nn,_name ::rest ->doit(nn-1)restindoit0pathletnormalize_in_graphpath=normalize_gen~assume:`Graphpathletnormalize_in_treepath=normalize_gen~assume:`Treepathletnormalize_filepathpath=normalize_gen~assume:`Graphpathletnormalizepath=normalize_gen~assume:`Treepath(* should be removed *)letparentpath=matchpathwith|[]->invalid_arg"PathGen.parent"|[rt]whenisrootrt->invalid_arg"PathGen.parent"|_::par->parletbelongsbasesub=(* Would normalization be useful here?
let base = normalize base in
let sub = normalize sub in
*)letrecfoldrbasersub=matchrbase,rsub with|bname::brest,sname::srestwhenbname =sname->fold brestsrest|_::_brest,_->false|[],_->trueinletrbase=List.revbaseinletrsub=List.revsubinmatch rbase,rsubwith|hb::_,hs::_whenhb=hs->foldrbasersub|_hb::_,_hs::_->false|rt::_,_whenisrootrt->invalid_arg"PathGen.belongs"|_,rt::_whenisrootrt->invalid_arg"PathGen.belongs"|_,_->foldrbasersubletgen_relative_toparent_onlybasesub=letbase=normalize baseinletsub=normalizesubinletrecfoldrbasersub=matchrbase,rsub with|bname::brest,sname::srestwhenbname =sname->fold brestsrest|_::brest,_->ifparent_onlythenraiseNot_parentelsefoldbrest(!!".."::rsub)|[],_->rsubinletrbase=List.revbaseinletrsub=List.revsubinlet rrel=matchrbase,rsubwith|hb::_,hs::_whenhb=hs->foldrbasersub|rt::_,_when isroot rt->invalid_arg"PathGen.relative_to_*"|_,rt::_whenisrootrt->invalid_arg"PathGen.relative_to_*"|_,_->foldrbasersubinList.revrrelletrelative_to_anybasesub=gen_relative_to falsebasesubletrelative_to_parentbasesub=gen_relative_to true basesubletto_ustringpath=letseparator=if windowsthen!!"\\"else!!"/"inmatchList.revpathwith|[]->!!"."|nl::abswhenisnulnl->letroot=ifwindowsthen!!"\\\\"else!!"/"inS.concat_with_separators!!""[root;S.concat_with_separatorsseparatorabs]|rel->S.concat_with_separators separatorrel(* also absolute but with drive letter *)letseparator_pred=letcharlist=List.mapS.lift_char(ifwindowsthen['/';'\\']else['/'])in(funch->List.memchcharlist)letto_string path=S.to_string(to_ustringpath)letof_stringstr=letparts=split_delim separator_predstrin(* Special rules apply to the first separator or leading win-disk-letter *)lethead,relparts=matchpartswith|nm::restwhenisrootnm->Somenm,rest|other->None,otherin(* Filter out redundant separator (at most one is removed here since separator_regexp is built with + operator) *)letfiltered_relparts=List.filter(functionnmwhenisnulnm->false|_->true)relpartsinletpath=List.rev(match headwith|Somenm->nm::filtered_relparts|None->filtered_relparts)in(* Validation excluding [head] contents: win-disk-letter or an empty string is omitted *)List.iter(funname->ignore(apply_default_validatorname))filtered_relparts;pathlets=to_stringletp=of_stringletwith_nonemptypathfu=matchpathwith|[]->invalid_arg"PathGen.name"|[rt]whenisrootrt->invalid_arg"PathGen.name"|name::parent->(funameparent)letnamepath=with_nonempty path(funname_->name)letmap_namefupath =with_nonemptypath(funnameparent->(apply_default_validator(funame))::parent)letsplit_on_last_dot =(funname->letlen=S.length nameintrylet dot_index=S.rindexname'.'inletlen_ext=len-(dot_index+1)inletext=S.subname(dot_index+1)len_extin(S.subname0dot_index,(* excluding the dot *)Someext(* possibly empty extension *))withNot_found->(name,None))letextpath=letname=name path insnd(split_on_last_dotname)letmap_extfupath=with_nonemptypath(funnameparent->letpart1,part2=split_on_last_dotnameinmatchfupart2 with|Somenew_ext->(apply_default_validator(S.concat_with_separators!!"."[part1;new_ext]))::parent|None->part1::parent)let name_corepath=with_nonemptypath(funname_->letname_core,_=split_on_last_dotnameinname_core)typecomponents=t*ustring*ustringoptionletsplitpath=with_nonemptypath(funnameparent->letname_core,ext=split_on_last_dotnamein(parent,name_core,ext))letjoin(parent,name_core,ext)=letname=matchextwith|Someext->S.concat_with_separators!!"."[name_core;ext]|None->name_corein(apply_default_validatorname)::parentletmapfupath=join(fu(splitpath))letdrive_letterabs=matchList.revabs with|nul::_whenisnulnul->None|drv::_whenis_win_disk_letterdrv->Some(S.getdrv0)|_->invalid_arg"PathGen.drive_letter"endmoduleStringAdapter(*: StringType*) =structtypet=stringletlength=String.lengthtypetchar=charletget=String.getletlift_charch=chletliftss=ssletto_stringss =ssletconcat_with_separators seplst=String.concatseplstletcompare(r1:string)(r2:string)=comparer1r2letsub=String.subletiter=String.iterletiteri =BatString.iterilet rindex=String.rindexmodule Parse=struct(* type source = (char, CharParser.position) ParserCo.Source.t*)letsource=BatCharParser.source_of_stringletletter=BatCharParser.letterendendmoduleOfString:PathType withtypeustring=stringandtypeuchar=char=Make(StringAdapter)(*
module TextAdapter = struct
type t = Ulib.Text.t
let length = Ulib.Text.length
type tchar = Ulib.UChar.t
let get = Ulib.Text.get
let lift_char ch = Ulib.UChar.of_char ch
let lift = Ulib.Text.of_string
let to_string = Ulib.Text.to_string
let concat_with_separators sep lst = Ulib.Text.concat sep lst
let compare = Ulib.Text.compare
let iter = Ulib.Text.iter
let iteri fu ss = Ulib.Text.iteri fu ss
let sub = Ulib.Text.sub
let rindex ss pch = Ulib.Text.rindex ss (Ulib.UChar.of_char pch)
module Parse = struct
let source = BatUCharParser.source_of_rope
let letter = BatUCharParser.letter
end
end
module OfText = Make (TextAdapter)
*)