Chris@529: (* Chris@529: DO NOT EDIT THIS FILE. Chris@529: This file is automatically generated from the individual Chris@529: source files in the Vext repository. Chris@529: *) Chris@523: Chris@523: (* Chris@523: Vext Chris@523: Chris@523: A simple manager for third-party source code dependencies Chris@523: Chris@529: Copyright 2017 Chris Cannam, Particular Programs Ltd, Chris@529: and Queen Mary, University of London Chris@523: Chris@523: Permission is hereby granted, free of charge, to any person Chris@523: obtaining a copy of this software and associated documentation Chris@523: files (the "Software"), to deal in the Software without Chris@523: restriction, including without limitation the rights to use, copy, Chris@523: modify, merge, publish, distribute, sublicense, and/or sell copies Chris@523: of the Software, and to permit persons to whom the Software is Chris@523: furnished to do so, subject to the following conditions: Chris@523: Chris@523: The above copyright notice and this permission notice shall be Chris@523: included in all copies or substantial portions of the Software. Chris@523: Chris@523: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@523: EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@523: MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND Chris@523: NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR Chris@523: ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF Chris@523: CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@523: WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@523: Chris@529: Except as contained in this notice, the names of Chris Cannam, Chris@529: Particular Programs Ltd, and Queen Mary, University of London Chris@529: shall not be used in advertising or otherwise to promote the sale, Chris@529: use or other dealings in this Software without prior written Chris@529: authorization. Chris@523: *) Chris@523: Chris@529: val vext_version = "0.9.8" Chris@523: Chris@523: Chris@523: datatype vcs = Chris@523: HG | Chris@523: GIT Chris@523: Chris@523: datatype source = Chris@523: URL_SOURCE of string | Chris@523: SERVICE_SOURCE of { Chris@523: service : string, Chris@523: owner : string option, Chris@523: repo : string option Chris@523: } Chris@523: Chris@529: type id_or_tag = string Chris@529: Chris@523: datatype pin = Chris@523: UNPINNED | Chris@529: PINNED of id_or_tag Chris@523: Chris@523: datatype libstate = Chris@523: ABSENT | Chris@523: CORRECT | Chris@523: SUPERSEDED | Chris@523: WRONG Chris@523: Chris@523: datatype localstate = Chris@523: MODIFIED | Chris@529: LOCK_MISMATCHED | Chris@529: CLEAN Chris@523: Chris@523: datatype branch = Chris@523: BRANCH of string | Chris@523: DEFAULT_BRANCH Chris@523: Chris@523: (* If we can recover from an error, for example by reporting failure Chris@523: for this one thing and going on to the next thing, then the error Chris@523: should usually be returned through a result type rather than an Chris@523: exception. *) Chris@523: Chris@523: datatype 'a result = Chris@523: OK of 'a | Chris@523: ERROR of string Chris@523: Chris@523: type libname = string Chris@523: Chris@523: type libspec = { Chris@523: libname : libname, Chris@523: vcs : vcs, Chris@523: source : source, Chris@523: branch : branch, Chris@529: project_pin : pin, Chris@529: lock_pin : pin Chris@523: } Chris@523: Chris@523: type lock = { Chris@523: libname : libname, Chris@523: id_or_tag : id_or_tag Chris@523: } Chris@529: Chris@523: type remote_spec = { Chris@523: anon : string option, Chris@523: auth : string option Chris@523: } Chris@523: Chris@523: type provider = { Chris@523: service : string, Chris@523: supports : vcs list, Chris@523: remote_spec : remote_spec Chris@523: } Chris@523: Chris@523: type account = { Chris@523: service : string, Chris@523: login : string Chris@523: } Chris@523: Chris@523: type context = { Chris@523: rootpath : string, Chris@523: extdir : string, Chris@523: providers : provider list, Chris@523: accounts : account list Chris@523: } Chris@523: Chris@523: type userconfig = { Chris@523: providers : provider list, Chris@523: accounts : account list Chris@523: } Chris@523: Chris@523: type project = { Chris@523: context : context, Chris@523: libs : libspec list Chris@523: } Chris@523: Chris@523: structure VextFilenames = struct Chris@523: val project_file = "vext-project.json" Chris@523: val project_lock_file = "vext-lock.json" Chris@523: val user_config_file = ".vext.json" Chris@529: val archive_dir = ".vext-archive" Chris@523: end Chris@523: Chris@523: signature VCS_CONTROL = sig Chris@523: Chris@523: (** Test whether the library is present locally at all *) Chris@523: val exists : context -> libname -> bool result Chris@523: Chris@523: (** Return the id (hash) of the current revision for the library *) Chris@523: val id_of : context -> libname -> id_or_tag result Chris@523: Chris@523: (** Test whether the library is at the given id *) Chris@523: val is_at : context -> libname * id_or_tag -> bool result Chris@523: Chris@523: (** Test whether the library is on the given branch, i.e. is at Chris@523: the branch tip or an ancestor of it *) Chris@523: val is_on_branch : context -> libname * branch -> bool result Chris@523: Chris@523: (** Test whether the library is at the newest revision for the Chris@523: given branch. False may indicate that the branch has advanced Chris@523: or that the library is not on the branch at all. This function Chris@523: may use the network to check for new revisions *) Chris@523: val is_newest : context -> libname * branch -> bool result Chris@523: Chris@523: (** Test whether the library is at the newest revision available Chris@523: locally for the given branch. False may indicate that the Chris@523: branch has advanced or that the library is not on the branch Chris@523: at all. This function must not use the network *) Chris@523: val is_newest_locally : context -> libname * branch -> bool result Chris@523: Chris@523: (** Test whether the library has been modified in the local Chris@523: working copy *) Chris@523: val is_modified_locally : context -> libname -> bool result Chris@523: Chris@523: (** Check out, i.e. clone a fresh copy of, the repo for the given Chris@523: library on the given branch *) Chris@523: val checkout : context -> libname * source * branch -> unit result Chris@523: Chris@523: (** Update the library to the given branch tip *) Chris@523: val update : context -> libname * branch -> id_or_tag result Chris@523: Chris@523: (** Update the library to the given specific id or tag *) Chris@523: val update_to : context -> libname * id_or_tag -> id_or_tag result Chris@523: end Chris@523: Chris@523: signature LIB_CONTROL = sig Chris@523: val review : context -> libspec -> (libstate * localstate) result Chris@523: val status : context -> libspec -> (libstate * localstate) result Chris@523: val update : context -> libspec -> id_or_tag result Chris@529: val id_of : context -> libspec -> id_or_tag result Chris@523: end Chris@523: Chris@523: structure FileBits :> sig Chris@523: val extpath : context -> string Chris@523: val libpath : context -> libname -> string Chris@523: val subpath : context -> libname -> string -> string Chris@523: val command_output : context -> libname -> string list -> string result Chris@523: val command : context -> libname -> string list -> unit result Chris@523: val file_contents : string -> string Chris@523: val mydir : unit -> string Chris@523: val homedir : unit -> string Chris@523: val mkpath : string -> unit result Chris@529: val rmpath : string -> unit result Chris@523: val project_spec_path : string -> string Chris@523: val project_lock_path : string -> string Chris@523: val verbose : unit -> bool Chris@523: end = struct Chris@523: Chris@523: fun verbose () = Chris@523: case OS.Process.getEnv "VEXT_VERBOSE" of Chris@523: SOME "0" => false Chris@523: | SOME _ => true Chris@523: | NONE => false Chris@523: Chris@523: fun extpath ({ rootpath, extdir, ... } : context) = Chris@523: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@523: in OS.Path.toString { Chris@523: isAbs = isAbs, Chris@523: vol = vol, Chris@523: arcs = arcs @ [ extdir ] Chris@523: } Chris@523: end Chris@523: Chris@523: fun subpath ({ rootpath, extdir, ... } : context) libname remainder = Chris@523: (* NB libname is allowed to be a path fragment, e.g. foo/bar *) Chris@523: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@523: val split = String.fields (fn c => c = #"/") Chris@523: in OS.Path.toString { Chris@523: isAbs = isAbs, Chris@523: vol = vol, Chris@523: arcs = arcs @ [ extdir ] @ split libname @ split remainder Chris@523: } Chris@523: end Chris@523: Chris@523: fun libpath context "" = Chris@523: extpath context Chris@523: | libpath context libname = Chris@523: subpath context libname "" Chris@523: Chris@523: fun project_file_path rootpath filename = Chris@523: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@523: in OS.Path.toString { Chris@523: isAbs = isAbs, Chris@523: vol = vol, Chris@523: arcs = arcs @ [ filename ] Chris@523: } Chris@523: end Chris@523: Chris@523: fun project_spec_path rootpath = Chris@523: project_file_path rootpath (VextFilenames.project_file) Chris@523: Chris@523: fun project_lock_path rootpath = Chris@523: project_file_path rootpath (VextFilenames.project_lock_file) Chris@523: Chris@523: fun trim str = Chris@523: hd (String.fields (fn x => x = #"\n" orelse x = #"\r") str) Chris@523: Chris@523: fun file_contents filename = Chris@523: let val stream = TextIO.openIn filename Chris@523: fun read_all str acc = Chris@523: case TextIO.inputLine str of Chris@523: SOME line => read_all str (trim line :: acc) Chris@523: | NONE => rev acc Chris@523: val contents = read_all stream [] Chris@523: val _ = TextIO.closeIn stream Chris@523: in Chris@523: String.concatWith "\n" contents Chris@523: end Chris@523: Chris@523: fun expand_commandline cmdlist = Chris@523: (* We are quite [too] strict about what we accept here, except Chris@523: for the first element in cmdlist which is assumed to be a Chris@523: known command location rather than arbitrary user input. NB Chris@523: only ASCII accepted at this point. *) Chris@523: let open Char Chris@523: fun quote arg = Chris@523: if List.all Chris@523: (fn c => isAlphaNum c orelse c = #"-" orelse c = #"_") Chris@523: (explode arg) Chris@523: then arg Chris@523: else "\"" ^ arg ^ "\"" Chris@523: fun check arg = Chris@523: let val valid = explode " /#:;?,._-{}@=" Chris@523: in Chris@523: app (fn c => Chris@523: if isAlphaNum c orelse Chris@523: List.exists (fn v => v = c) valid Chris@523: then () Chris@523: else raise Fail ("Invalid character '" ^ Chris@523: (Char.toString c) ^ Chris@523: "' in command list")) Chris@523: (explode arg); Chris@523: arg Chris@523: end Chris@523: in Chris@523: String.concatWith " " Chris@523: (map quote Chris@523: (hd cmdlist :: map check (tl cmdlist))) Chris@523: end Chris@523: Chris@523: val tick_cycle = ref 0 Chris@523: val tick_chars = Vector.fromList (map String.str (explode "|/-\\")) Chris@523: Chris@523: fun tick libname cmdlist = Chris@523: let val n = Vector.length tick_chars Chris@523: fun pad_to n str = Chris@523: if n <= String.size str then str Chris@523: else pad_to n (str ^ " ") Chris@523: val name = if libname <> "" then libname Chris@523: else if cmdlist = nil then "" Chris@523: else hd (rev cmdlist) Chris@523: in Chris@523: print (" " ^ Chris@523: Vector.sub(tick_chars, !tick_cycle) ^ " " ^ Chris@523: pad_to 24 name ^ Chris@523: "\r"); Chris@523: tick_cycle := (if !tick_cycle = n - 1 then 0 else 1 + !tick_cycle) Chris@523: end Chris@523: Chris@523: fun run_command context libname cmdlist redirect = Chris@523: let open OS Chris@523: val dir = libpath context libname Chris@523: val cmd = expand_commandline cmdlist Chris@523: val _ = if verbose () Chris@523: then print ("Running: " ^ cmd ^ Chris@523: " (in dir " ^ dir ^ ")...\n") Chris@523: else tick libname cmdlist Chris@523: val _ = FileSys.chDir dir Chris@523: val status = case redirect of Chris@523: NONE => Process.system cmd Chris@523: | SOME file => Process.system (cmd ^ ">" ^ file) Chris@523: in Chris@523: if Process.isSuccess status Chris@523: then OK () Chris@523: else ERROR ("Command failed: " ^ cmd ^ " (in dir " ^ dir ^ ")") Chris@523: end Chris@523: handle ex => ERROR ("Unable to run command: " ^ exnMessage ex) Chris@523: Chris@523: fun command context libname cmdlist = Chris@523: run_command context libname cmdlist NONE Chris@523: Chris@523: fun command_output context libname cmdlist = Chris@523: let open OS Chris@523: val tmpFile = FileSys.tmpName () Chris@523: val result = run_command context libname cmdlist (SOME tmpFile) Chris@523: val contents = file_contents tmpFile Chris@523: in Chris@523: FileSys.remove tmpFile handle _ => (); Chris@523: case result of Chris@523: OK () => OK contents Chris@523: | ERROR e => ERROR e Chris@523: end Chris@523: Chris@523: fun mydir () = Chris@523: let open OS Chris@523: val { dir, file } = Path.splitDirFile (CommandLine.name ()) Chris@523: in Chris@523: FileSys.realPath Chris@523: (if Path.isAbsolute dir Chris@523: then dir Chris@523: else Path.concat (FileSys.getDir (), dir)) Chris@523: end Chris@523: Chris@523: fun homedir () = Chris@523: (* Failure is not routine, so we use an exception here *) Chris@523: case (OS.Process.getEnv "HOME", Chris@523: OS.Process.getEnv "HOMEPATH") of Chris@523: (SOME home, _) => home Chris@523: | (NONE, SOME home) => home Chris@523: | (NONE, NONE) => Chris@523: raise Fail "Failed to look up home directory from environment" Chris@523: Chris@523: fun mkpath path = Chris@523: if OS.FileSys.isDir path handle _ => false Chris@523: then OK () Chris@523: else case OS.Path.fromString path of Chris@523: { arcs = nil, ... } => OK () Chris@523: | { isAbs = false, ... } => ERROR "mkpath requires absolute path" Chris@523: | { isAbs, vol, arcs } => Chris@523: case mkpath (OS.Path.toString { (* parent *) Chris@523: isAbs = isAbs, Chris@523: vol = vol, Chris@523: arcs = rev (tl (rev arcs)) }) of Chris@523: ERROR e => ERROR e Chris@523: | OK () => ((OS.FileSys.mkDir path; OK ()) Chris@523: handle OS.SysErr (e, _) => Chris@523: ERROR ("Directory creation failed: " ^ e)) Chris@529: Chris@529: fun rmpath path = Chris@529: let open OS Chris@529: fun files_from dirstream = Chris@529: case FileSys.readDir dirstream of Chris@529: NONE => [] Chris@529: | SOME file => Chris@529: (* readDir is supposed to filter these, Chris@529: but let's be extra cautious: *) Chris@529: if file = Path.parentArc orelse file = Path.currentArc Chris@529: then files_from dirstream Chris@529: else file :: files_from dirstream Chris@529: fun contents dir = Chris@529: let val stream = FileSys.openDir dir Chris@529: val files = map (fn f => Path.joinDirFile Chris@529: { dir = dir, file = f }) Chris@529: (files_from stream) Chris@529: val _ = FileSys.closeDir stream Chris@529: in files Chris@529: end Chris@529: fun remove path = Chris@529: if FileSys.isLink path (* dangling links bother isDir *) Chris@529: then FileSys.remove path Chris@529: else if FileSys.isDir path Chris@529: then (app remove (contents path); FileSys.rmDir path) Chris@529: else FileSys.remove path Chris@529: in Chris@529: (remove path; OK ()) Chris@529: handle SysErr (e, _) => ERROR ("Path removal failed: " ^ e) Chris@529: end Chris@523: end Chris@523: Chris@523: functor LibControlFn (V: VCS_CONTROL) :> LIB_CONTROL = struct Chris@523: Chris@523: (* Valid states for unpinned libraries: Chris@523: Chris@523: - CORRECT: We are on the right branch and are up-to-date with Chris@523: it as far as we can tell. (If not using the network, this Chris@523: should be reported to user as "Present" rather than "Correct" Chris@523: as the remote repo may have advanced without us knowing.) Chris@523: Chris@523: - SUPERSEDED: We are on the right branch but we can see that Chris@523: there is a newer revision either locally or on the remote (in Chris@523: Git terms, we are at an ancestor of the desired branch tip). Chris@523: Chris@523: - WRONG: We are on the wrong branch (in Git terms, we are not Chris@523: at the desired branch tip or any ancestor of it). Chris@523: Chris@523: - ABSENT: Repo doesn't exist here at all. Chris@523: Chris@523: Valid states for pinned libraries: Chris@523: Chris@523: - CORRECT: We are at the pinned revision. Chris@523: Chris@523: - WRONG: We are at any revision other than the pinned one. Chris@523: Chris@523: - ABSENT: Repo doesn't exist here at all. Chris@523: *) Chris@523: Chris@529: fun check with_network context Chris@529: ({ libname, branch, project_pin, lock_pin, ... } : libspec) = Chris@523: let fun check_unpinned () = Chris@523: let val is_newest = if with_network Chris@523: then V.is_newest Chris@523: else V.is_newest_locally Chris@523: in Chris@523: case is_newest context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => OK CORRECT Chris@523: | OK false => Chris@523: case V.is_on_branch context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => OK SUPERSEDED Chris@523: | OK false => OK WRONG Chris@523: end Chris@523: fun check_pinned target = Chris@523: case V.is_at context (libname, target) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => OK CORRECT Chris@523: | OK false => OK WRONG Chris@529: fun check_remote () = Chris@529: case project_pin of Chris@523: UNPINNED => check_unpinned () Chris@523: | PINNED target => check_pinned target Chris@529: fun check_local () = Chris@529: case V.is_modified_locally context libname of Chris@529: ERROR e => ERROR e Chris@529: | OK true => OK MODIFIED Chris@529: | OK false => Chris@529: case lock_pin of Chris@529: UNPINNED => OK CLEAN Chris@529: | PINNED target => Chris@529: case V.is_at context (libname, target) of Chris@529: ERROR e => ERROR e Chris@529: | OK true => OK CLEAN Chris@529: | OK false => OK LOCK_MISMATCHED Chris@523: in Chris@523: case V.exists context libname of Chris@523: ERROR e => ERROR e Chris@529: | OK false => OK (ABSENT, CLEAN) Chris@523: | OK true => Chris@529: case (check_remote (), check_local ()) of Chris@523: (ERROR e, _) => ERROR e Chris@523: | (_, ERROR e) => ERROR e Chris@529: | (OK r, OK l) => OK (r, l) Chris@523: end Chris@523: Chris@523: val review = check true Chris@523: val status = check false Chris@529: Chris@529: fun update context Chris@529: ({ libname, source, branch, Chris@529: project_pin, lock_pin, ... } : libspec) = Chris@523: let fun update_unpinned () = Chris@523: case V.is_newest context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => V.id_of context libname Chris@523: | OK false => V.update context (libname, branch) Chris@523: fun update_pinned target = Chris@523: case V.is_at context (libname, target) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => OK target Chris@523: | OK false => V.update_to context (libname, target) Chris@523: fun update' () = Chris@529: case lock_pin of Chris@529: PINNED target => update_pinned target Chris@529: | UNPINNED => Chris@529: case project_pin of Chris@529: PINNED target => update_pinned target Chris@529: | UNPINNED => update_unpinned () Chris@523: in Chris@523: case V.exists context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK true => update' () Chris@523: | OK false => Chris@523: case V.checkout context (libname, source, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK () => update' () Chris@523: end Chris@529: Chris@529: fun id_of context ({ libname, ... } : libspec) = Chris@529: V.id_of context libname Chris@529: Chris@523: end Chris@523: Chris@523: (* Simple Standard ML JSON parser Chris@523: ============================== Chris@523: Chris@523: https://bitbucket.org/cannam/sml-simplejson Chris@523: Chris@523: An RFC-compliant JSON parser in one SML file with no dependency Chris@523: on anything outside the Basis library. Also includes a simple Chris@523: serialiser. Chris@523: Chris@523: Tested with MLton, Poly/ML, and SML/NJ compilers. Chris@523: Chris@523: Parser notes: Chris@523: Chris@523: * Complies with RFC 7159, The JavaScript Object Notation (JSON) Chris@523: Data Interchange Format Chris@523: Chris@523: * Passes all of the JSONTestSuite parser accept/reject tests that Chris@523: exist at the time of writing, as listed in "Parsing JSON is a Chris@523: Minefield" (http://seriot.ch/parsing_json.php) Chris@523: Chris@523: * Two-pass parser using naive exploded strings, therefore not Chris@523: particularly fast and not suitable for large input files Chris@523: Chris@523: * Only supports UTF-8 input, not UTF-16 or UTF-32. Doesn't check Chris@523: that JSON strings are valid UTF-8 -- the caller must do that -- Chris@523: but does handle \u escapes Chris@523: Chris@523: * Converts all numbers to type "real". If that is a 64-bit IEEE Chris@523: float type (common but not guaranteed in SML) then we're pretty Chris@523: standard for a JSON parser Chris@523: Chris@523: Copyright 2017 Chris Cannam. Chris@523: Parts based on the JSON parser in the Ponyo library by Phil Eaton. Chris@523: Chris@523: Permission is hereby granted, free of charge, to any person Chris@523: obtaining a copy of this software and associated documentation Chris@523: files (the "Software"), to deal in the Software without Chris@523: restriction, including without limitation the rights to use, copy, Chris@523: modify, merge, publish, distribute, sublicense, and/or sell copies Chris@523: of the Software, and to permit persons to whom the Software is Chris@523: furnished to do so, subject to the following conditions: Chris@523: Chris@523: The above copyright notice and this permission notice shall be Chris@523: included in all copies or substantial portions of the Software. Chris@523: Chris@523: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@523: EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@523: MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND Chris@523: NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR Chris@523: ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF Chris@523: CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@523: WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@523: Chris@523: Except as contained in this notice, the names of Chris Cannam and Chris@523: Particular Programs Ltd shall not be used in advertising or Chris@523: otherwise to promote the sale, use or other dealings in this Chris@523: Software without prior written authorization. Chris@523: *) Chris@523: Chris@523: signature JSON = sig Chris@523: Chris@523: datatype json = OBJECT of (string * json) list Chris@523: | ARRAY of json list Chris@523: | NUMBER of real Chris@523: | STRING of string Chris@523: | BOOL of bool Chris@523: | NULL Chris@523: Chris@523: datatype 'a result = OK of 'a Chris@523: | ERROR of string Chris@523: Chris@523: val parse : string -> json result Chris@523: val serialise : json -> string Chris@523: val serialiseIndented : json -> string Chris@523: Chris@523: end Chris@523: Chris@523: structure Json :> JSON = struct Chris@523: Chris@523: datatype json = OBJECT of (string * json) list Chris@523: | ARRAY of json list Chris@523: | NUMBER of real Chris@523: | STRING of string Chris@523: | BOOL of bool Chris@523: | NULL Chris@523: Chris@523: datatype 'a result = OK of 'a Chris@523: | ERROR of string Chris@523: Chris@523: structure T = struct Chris@523: datatype token = NUMBER of char list Chris@523: | STRING of string Chris@523: | BOOL of bool Chris@523: | NULL Chris@523: | CURLY_L Chris@523: | CURLY_R Chris@523: | SQUARE_L Chris@523: | SQUARE_R Chris@523: | COLON Chris@523: | COMMA Chris@523: Chris@523: fun toString t = Chris@523: case t of NUMBER digits => implode digits Chris@523: | STRING s => s Chris@523: | BOOL b => Bool.toString b Chris@523: | NULL => "null" Chris@523: | CURLY_L => "{" Chris@523: | CURLY_R => "}" Chris@523: | SQUARE_L => "[" Chris@523: | SQUARE_R => "]" Chris@523: | COLON => ":" Chris@523: | COMMA => "," Chris@523: end Chris@523: Chris@523: fun bmpToUtf8 cp = (* convert a codepoint in Unicode BMP to utf8 bytes *) Chris@523: let open Word Chris@523: infix 6 orb andb >> Chris@523: in Chris@523: map (Char.chr o toInt) Chris@523: (if cp < 0wx80 then Chris@523: [cp] Chris@523: else if cp < 0wx800 then Chris@523: [0wxc0 orb (cp >> 0w6), 0wx80 orb (cp andb 0wx3f)] Chris@523: else if cp < 0wx10000 then Chris@523: [0wxe0 orb (cp >> 0w12), Chris@523: 0wx80 orb ((cp >> 0w6) andb 0wx3f), Chris@523: 0wx80 orb (cp andb 0wx3f)] Chris@523: else raise Fail ("Invalid BMP point " ^ (Word.toString cp))) Chris@523: end Chris@523: Chris@523: fun error pos text = ERROR (text ^ " at character position " ^ Chris@523: Int.toString (pos - 1)) Chris@523: fun token_error pos = error pos ("Unexpected token") Chris@523: Chris@523: fun lexNull pos acc (#"u" :: #"l" :: #"l" :: xs) = Chris@523: lex (pos + 3) (T.NULL :: acc) xs Chris@523: | lexNull pos acc _ = token_error pos Chris@523: Chris@523: and lexTrue pos acc (#"r" :: #"u" :: #"e" :: xs) = Chris@523: lex (pos + 3) (T.BOOL true :: acc) xs Chris@523: | lexTrue pos acc _ = token_error pos Chris@523: Chris@523: and lexFalse pos acc (#"a" :: #"l" :: #"s" :: #"e" :: xs) = Chris@523: lex (pos + 4) (T.BOOL false :: acc) xs Chris@523: | lexFalse pos acc _ = token_error pos Chris@523: Chris@523: and lexChar tok pos acc xs = Chris@523: lex pos (tok :: acc) xs Chris@523: Chris@523: and lexString pos acc cc = Chris@523: let datatype escaped = ESCAPED | NORMAL Chris@523: fun lexString' pos text ESCAPED [] = Chris@523: error pos "End of input during escape sequence" Chris@523: | lexString' pos text NORMAL [] = Chris@523: error pos "End of input during string" Chris@523: | lexString' pos text ESCAPED (x :: xs) = Chris@523: let fun esc c = lexString' (pos + 1) (c :: text) NORMAL xs Chris@523: in case x of Chris@523: #"\"" => esc x Chris@523: | #"\\" => esc x Chris@523: | #"/" => esc x Chris@523: | #"b" => esc #"\b" Chris@523: | #"f" => esc #"\f" Chris@523: | #"n" => esc #"\n" Chris@523: | #"r" => esc #"\r" Chris@523: | #"t" => esc #"\t" Chris@523: | _ => error pos ("Invalid escape \\" ^ Chris@523: Char.toString x) Chris@523: end Chris@523: | lexString' pos text NORMAL (#"\\" :: #"u" ::a::b::c::d:: xs) = Chris@523: if List.all Char.isHexDigit [a,b,c,d] Chris@523: then case Word.fromString ("0wx" ^ (implode [a,b,c,d])) of Chris@523: SOME w => (let val utf = rev (bmpToUtf8 w) in Chris@523: lexString' (pos + 6) (utf @ text) Chris@523: NORMAL xs Chris@523: end Chris@523: handle Fail err => error pos err) Chris@523: | NONE => error pos "Invalid Unicode BMP escape sequence" Chris@523: else error pos "Invalid Unicode BMP escape sequence" Chris@523: | lexString' pos text NORMAL (x :: xs) = Chris@523: if Char.ord x < 0x20 Chris@523: then error pos "Invalid unescaped control character" Chris@523: else Chris@523: case x of Chris@523: #"\"" => OK (rev text, xs, pos + 1) Chris@523: | #"\\" => lexString' (pos + 1) text ESCAPED xs Chris@523: | _ => lexString' (pos + 1) (x :: text) NORMAL xs Chris@523: in Chris@523: case lexString' pos [] NORMAL cc of Chris@523: OK (text, rest, newpos) => Chris@523: lex newpos (T.STRING (implode text) :: acc) rest Chris@523: | ERROR e => ERROR e Chris@523: end Chris@523: Chris@523: and lexNumber firstChar pos acc cc = Chris@523: let val valid = explode ".+-e" Chris@523: fun lexNumber' pos digits [] = (rev digits, [], pos) Chris@523: | lexNumber' pos digits (x :: xs) = Chris@523: if x = #"E" then lexNumber' (pos + 1) (#"e" :: digits) xs Chris@523: else if Char.isDigit x orelse List.exists (fn c => x = c) valid Chris@523: then lexNumber' (pos + 1) (x :: digits) xs Chris@523: else (rev digits, x :: xs, pos) Chris@523: val (digits, rest, newpos) = Chris@523: lexNumber' (pos - 1) [] (firstChar :: cc) Chris@523: in Chris@523: case digits of Chris@523: [] => token_error pos Chris@523: | _ => lex newpos (T.NUMBER digits :: acc) rest Chris@523: end Chris@523: Chris@523: and lex pos acc [] = OK (rev acc) Chris@523: | lex pos acc (x::xs) = Chris@523: (case x of Chris@523: #" " => lex Chris@523: | #"\t" => lex Chris@523: | #"\n" => lex Chris@523: | #"\r" => lex Chris@523: | #"{" => lexChar T.CURLY_L Chris@523: | #"}" => lexChar T.CURLY_R Chris@523: | #"[" => lexChar T.SQUARE_L Chris@523: | #"]" => lexChar T.SQUARE_R Chris@523: | #":" => lexChar T.COLON Chris@523: | #"," => lexChar T.COMMA Chris@523: | #"\"" => lexString Chris@523: | #"t" => lexTrue Chris@523: | #"f" => lexFalse Chris@523: | #"n" => lexNull Chris@523: | x => lexNumber x) (pos + 1) acc xs Chris@523: Chris@523: fun show [] = "end of input" Chris@523: | show (tok :: _) = T.toString tok Chris@523: Chris@523: fun parseNumber digits = Chris@523: (* Note lexNumber already case-insensitised the E for us *) Chris@523: let open Char Chris@523: Chris@523: fun okExpDigits [] = false Chris@523: | okExpDigits (c :: []) = isDigit c Chris@523: | okExpDigits (c :: cs) = isDigit c andalso okExpDigits cs Chris@523: Chris@523: fun okExponent [] = false Chris@523: | okExponent (#"+" :: cs) = okExpDigits cs Chris@523: | okExponent (#"-" :: cs) = okExpDigits cs Chris@523: | okExponent cc = okExpDigits cc Chris@523: Chris@523: fun okFracTrailing [] = true Chris@523: | okFracTrailing (c :: cs) = Chris@523: (isDigit c andalso okFracTrailing cs) orelse Chris@523: (c = #"e" andalso okExponent cs) Chris@523: Chris@523: fun okFraction [] = false Chris@523: | okFraction (c :: cs) = Chris@523: isDigit c andalso okFracTrailing cs Chris@523: Chris@523: fun okPosTrailing [] = true Chris@523: | okPosTrailing (#"." :: cs) = okFraction cs Chris@523: | okPosTrailing (#"e" :: cs) = okExponent cs Chris@523: | okPosTrailing (c :: cs) = Chris@523: isDigit c andalso okPosTrailing cs Chris@523: Chris@523: fun okPositive [] = false Chris@523: | okPositive (#"0" :: []) = true Chris@523: | okPositive (#"0" :: #"." :: cs) = okFraction cs Chris@523: | okPositive (#"0" :: #"e" :: cs) = okExponent cs Chris@523: | okPositive (#"0" :: cs) = false Chris@523: | okPositive (c :: cs) = isDigit c andalso okPosTrailing cs Chris@523: Chris@523: fun okNumber (#"-" :: cs) = okPositive cs Chris@523: | okNumber cc = okPositive cc Chris@523: in Chris@523: if okNumber digits Chris@523: then case Real.fromString (implode digits) of Chris@523: NONE => ERROR "Number out of range" Chris@523: | SOME r => OK r Chris@523: else ERROR ("Invalid number \"" ^ (implode digits) ^ "\"") Chris@523: end Chris@523: Chris@523: fun parseObject (T.CURLY_R :: xs) = OK (OBJECT [], xs) Chris@523: | parseObject tokens = Chris@523: let fun parsePair (T.STRING key :: T.COLON :: xs) = Chris@523: (case parseTokens xs of Chris@523: ERROR e => ERROR e Chris@523: | OK (j, xs) => OK ((key, j), xs)) Chris@523: | parsePair other = Chris@523: ERROR ("Object key/value pair expected around \"" ^ Chris@523: show other ^ "\"") Chris@523: fun parseObject' acc [] = ERROR "End of input during object" Chris@523: | parseObject' acc tokens = Chris@523: case parsePair tokens of Chris@523: ERROR e => ERROR e Chris@523: | OK (pair, T.COMMA :: xs) => Chris@523: parseObject' (pair :: acc) xs Chris@523: | OK (pair, T.CURLY_R :: xs) => Chris@523: OK (OBJECT (rev (pair :: acc)), xs) Chris@523: | OK (_, _) => ERROR "Expected , or } after object element" Chris@523: in Chris@523: parseObject' [] tokens Chris@523: end Chris@523: Chris@523: and parseArray (T.SQUARE_R :: xs) = OK (ARRAY [], xs) Chris@523: | parseArray tokens = Chris@523: let fun parseArray' acc [] = ERROR "End of input during array" Chris@523: | parseArray' acc tokens = Chris@523: case parseTokens tokens of Chris@523: ERROR e => ERROR e Chris@523: | OK (j, T.COMMA :: xs) => parseArray' (j :: acc) xs Chris@523: | OK (j, T.SQUARE_R :: xs) => OK (ARRAY (rev (j :: acc)), xs) Chris@523: | OK (_, _) => ERROR "Expected , or ] after array element" Chris@523: in Chris@523: parseArray' [] tokens Chris@523: end Chris@523: Chris@523: and parseTokens [] = ERROR "Value expected" Chris@523: | parseTokens (tok :: xs) = Chris@523: (case tok of Chris@523: T.NUMBER d => (case parseNumber d of Chris@523: OK r => OK (NUMBER r, xs) Chris@523: | ERROR e => ERROR e) Chris@523: | T.STRING s => OK (STRING s, xs) Chris@523: | T.BOOL b => OK (BOOL b, xs) Chris@523: | T.NULL => OK (NULL, xs) Chris@523: | T.CURLY_L => parseObject xs Chris@523: | T.SQUARE_L => parseArray xs Chris@523: | _ => ERROR ("Unexpected token " ^ T.toString tok ^ Chris@523: " before " ^ show xs)) Chris@523: Chris@523: fun parse str = Chris@523: case lex 1 [] (explode str) of Chris@523: ERROR e => ERROR e Chris@523: | OK tokens => case parseTokens tokens of Chris@523: OK (value, []) => OK value Chris@523: | OK (_, _) => ERROR "Extra data after input" Chris@523: | ERROR e => ERROR e Chris@523: Chris@523: fun stringEscape s = Chris@523: let fun esc x = [x, #"\\"] Chris@523: fun escape' acc [] = rev acc Chris@523: | escape' acc (x :: xs) = Chris@523: escape' (case x of Chris@523: #"\"" => esc x @ acc Chris@523: | #"\\" => esc x @ acc Chris@523: | #"\b" => esc #"b" @ acc Chris@523: | #"\f" => esc #"f" @ acc Chris@523: | #"\n" => esc #"n" @ acc Chris@523: | #"\r" => esc #"r" @ acc Chris@523: | #"\t" => esc #"t" @ acc Chris@523: | _ => Chris@523: let val c = Char.ord x Chris@523: in Chris@523: if c < 0x20 Chris@523: then let val hex = Word.toString (Word.fromInt c) Chris@523: in (rev o explode) (if c < 0x10 Chris@523: then ("\\u000" ^ hex) Chris@523: else ("\\u00" ^ hex)) Chris@523: end @ acc Chris@523: else Chris@523: x :: acc Chris@523: end) Chris@523: xs Chris@523: in Chris@523: implode (escape' [] (explode s)) Chris@523: end Chris@523: Chris@523: fun serialise json = Chris@523: case json of Chris@523: OBJECT pp => "{" ^ String.concatWith Chris@523: "," (map (fn (key, value) => Chris@523: serialise (STRING key) ^ ":" ^ Chris@523: serialise value) pp) ^ Chris@523: "}" Chris@523: | ARRAY arr => "[" ^ String.concatWith "," (map serialise arr) ^ "]" Chris@523: | NUMBER n => implode (map (fn #"~" => #"-" | c => c) Chris@523: (explode (Real.toString n))) Chris@523: | STRING s => "\"" ^ stringEscape s ^ "\"" Chris@523: | BOOL b => Bool.toString b Chris@523: | NULL => "null" Chris@523: Chris@523: fun serialiseIndented json = Chris@523: let fun indent 0 = "" Chris@523: | indent i = " " ^ indent (i - 1) Chris@523: fun serialiseIndented' i json = Chris@523: let val ser = serialiseIndented' (i + 1) Chris@523: in Chris@523: case json of Chris@523: OBJECT [] => "{}" Chris@523: | ARRAY [] => "[]" Chris@523: | OBJECT pp => "{\n" ^ indent (i + 1) ^ Chris@523: String.concatWith Chris@523: (",\n" ^ indent (i + 1)) Chris@523: (map (fn (key, value) => Chris@523: ser (STRING key) ^ ": " ^ Chris@523: ser value) pp) ^ Chris@523: "\n" ^ indent i ^ "}" Chris@523: | ARRAY arr => "[\n" ^ indent (i + 1) ^ Chris@523: String.concatWith Chris@523: (",\n" ^ indent (i + 1)) Chris@523: (map ser arr) ^ Chris@523: "\n" ^ indent i ^ "]" Chris@523: | other => serialise other Chris@523: end Chris@523: in Chris@523: serialiseIndented' 0 json ^ "\n" Chris@523: end Chris@523: Chris@523: end Chris@523: Chris@523: Chris@523: structure JsonBits :> sig Chris@523: val load_json_from : string -> Json.json (* filename -> json *) Chris@523: val save_json_to : string -> Json.json -> unit Chris@523: val lookup_optional : Json.json -> string list -> Json.json option Chris@523: val lookup_optional_string : Json.json -> string list -> string option Chris@523: val lookup_mandatory : Json.json -> string list -> Json.json Chris@523: val lookup_mandatory_string : Json.json -> string list -> string Chris@523: end = struct Chris@523: Chris@523: fun load_json_from filename = Chris@523: case Json.parse (FileBits.file_contents filename) of Chris@523: Json.OK json => json Chris@523: | Json.ERROR e => raise Fail ("Failed to parse file: " ^ e) Chris@523: Chris@523: fun save_json_to filename json = Chris@523: (* using binary I/O to avoid ever writing CR/LF line endings *) Chris@523: let val jstr = Json.serialiseIndented json Chris@523: val stream = BinIO.openOut filename Chris@523: in Chris@523: BinIO.output (stream, Byte.stringToBytes jstr); Chris@523: BinIO.closeOut stream Chris@523: end Chris@523: Chris@523: fun lookup_optional json kk = Chris@523: let fun lookup key = Chris@523: case json of Chris@523: Json.OBJECT kvs => Chris@523: (case List.find (fn (k, v) => k = key) kvs of Chris@523: SOME (k, v) => SOME v Chris@523: | NONE => NONE) Chris@523: | _ => raise Fail "Object expected" Chris@523: in Chris@523: case kk of Chris@523: [] => NONE Chris@523: | key::[] => lookup key Chris@523: | key::kk => case lookup key of Chris@523: NONE => NONE Chris@523: | SOME j => lookup_optional j kk Chris@523: end Chris@523: Chris@523: fun lookup_optional_string json kk = Chris@523: case lookup_optional json kk of Chris@523: SOME (Json.STRING s) => SOME s Chris@523: | SOME _ => raise Fail ("Value (if present) must be string: " ^ Chris@523: (String.concatWith " -> " kk)) Chris@523: | NONE => NONE Chris@523: Chris@523: fun lookup_mandatory json kk = Chris@523: case lookup_optional json kk of Chris@523: SOME v => v Chris@523: | NONE => raise Fail ("Value is mandatory: " ^ Chris@523: (String.concatWith " -> " kk) ^ " in json: " ^ Chris@523: (Json.serialise json)) Chris@523: Chris@523: fun lookup_mandatory_string json kk = Chris@523: case lookup_optional json kk of Chris@523: SOME (Json.STRING s) => s Chris@523: | _ => raise Fail ("Value must be string: " ^ Chris@523: (String.concatWith " -> " kk)) Chris@523: end Chris@523: Chris@523: structure Provider :> sig Chris@523: val load_providers : Json.json -> provider list Chris@523: val load_more_providers : provider list -> Json.json -> provider list Chris@523: val remote_url : context -> vcs -> source -> libname -> string Chris@523: end = struct Chris@523: Chris@523: val known_providers : provider list = Chris@523: [ { Chris@523: service = "bitbucket", Chris@523: supports = [HG, GIT], Chris@523: remote_spec = { Chris@523: anon = SOME "https://bitbucket.org/{owner}/{repository}", Chris@523: auth = SOME "ssh://{vcs}@bitbucket.org/{owner}/{repository}" Chris@523: } Chris@523: }, Chris@523: { Chris@523: service = "github", Chris@523: supports = [GIT], Chris@523: remote_spec = { Chris@523: anon = SOME "https://github.com/{owner}/{repository}", Chris@523: auth = SOME "ssh://{vcs}@github.com/{owner}/{repository}" Chris@523: } Chris@523: } Chris@523: ] Chris@523: Chris@523: fun vcs_name vcs = Chris@523: case vcs of GIT => "git" | Chris@523: HG => "hg" Chris@523: Chris@523: fun vcs_from_name name = Chris@523: case name of "git" => GIT Chris@523: | "hg" => HG Chris@523: | other => raise Fail ("Unknown vcs name \"" ^ name ^ "\"") Chris@523: Chris@523: fun load_more_providers previously_loaded json = Chris@523: let open JsonBits Chris@523: fun load pjson pname : provider = Chris@523: { Chris@523: service = pname, Chris@523: supports = Chris@523: case lookup_mandatory pjson ["vcs"] of Chris@523: Json.ARRAY vv => Chris@523: map (fn (Json.STRING v) => vcs_from_name v Chris@523: | _ => raise Fail "Strings expected in vcs array") Chris@523: vv Chris@523: | _ => raise Fail "Array expected for vcs", Chris@523: remote_spec = { Chris@523: anon = lookup_optional_string pjson ["anonymous"], Chris@523: auth = lookup_optional_string pjson ["authenticated"] Chris@523: } Chris@523: } Chris@523: val loaded = Chris@523: case lookup_optional json ["services"] of Chris@523: NONE => [] Chris@523: | SOME (Json.OBJECT pl) => map (fn (k, v) => load v k) pl Chris@523: | _ => raise Fail "Object expected for services in config" Chris@523: val newly_loaded = Chris@523: List.filter (fn p => not (List.exists (fn pp => #service p = Chris@523: #service pp) Chris@523: previously_loaded)) Chris@523: loaded Chris@523: in Chris@523: previously_loaded @ newly_loaded Chris@523: end Chris@523: Chris@523: fun load_providers json = Chris@523: load_more_providers known_providers json Chris@523: Chris@523: fun expand_spec spec { vcs, service, owner, repo } login = Chris@523: (* ugly *) Chris@523: let fun replace str = Chris@523: case str of Chris@523: "vcs" => vcs_name vcs Chris@523: | "service" => service Chris@523: | "owner" => Chris@523: (case owner of Chris@523: SOME ostr => ostr Chris@523: | NONE => raise Fail ("Owner not specified for service " ^ Chris@523: service)) Chris@523: | "repository" => repo Chris@523: | "account" => Chris@523: (case login of Chris@523: SOME acc => acc Chris@523: | NONE => raise Fail ("Account not given for service " ^ Chris@523: service)) Chris@523: | other => raise Fail ("Unknown variable \"" ^ other ^ Chris@523: "\" in spec for service " ^ service) Chris@523: fun expand' acc sstr = Chris@523: case Substring.splitl (fn c => c <> #"{") sstr of Chris@523: (pfx, sfx) => Chris@523: if Substring.isEmpty sfx Chris@523: then rev (pfx :: acc) Chris@523: else Chris@523: case Substring.splitl (fn c => c <> #"}") sfx of Chris@523: (tok, remainder) => Chris@523: if Substring.isEmpty remainder Chris@523: then rev (tok :: pfx :: acc) Chris@523: else let val replacement = Chris@523: replace Chris@523: (* tok begins with "{": *) Chris@523: (Substring.string Chris@523: (Substring.triml 1 tok)) Chris@523: in Chris@523: expand' (Substring.full replacement :: Chris@523: pfx :: acc) Chris@523: (* remainder begins with "}": *) Chris@523: (Substring.triml 1 remainder) Chris@523: end Chris@523: in Chris@523: Substring.concat (expand' [] (Substring.full spec)) Chris@523: end Chris@523: Chris@523: fun provider_url req login providers = Chris@523: case providers of Chris@523: [] => raise Fail ("Unknown service \"" ^ (#service req) ^ Chris@523: "\" for vcs \"" ^ (vcs_name (#vcs req)) ^ "\"") Chris@523: | ({ service, supports, remote_spec : remote_spec } :: rest) => Chris@523: if service <> (#service req) orelse Chris@523: not (List.exists (fn v => v = (#vcs req)) supports) Chris@523: then provider_url req login rest Chris@523: else Chris@523: case (login, #auth remote_spec, #anon remote_spec) of Chris@523: (SOME _, SOME auth, _) => expand_spec auth req login Chris@523: | (SOME _, _, SOME anon) => expand_spec anon req NONE Chris@523: | (NONE, _, SOME anon) => expand_spec anon req NONE Chris@523: | _ => raise Fail ("No suitable anonymous or authenticated " ^ Chris@523: "URL spec provided for service \"" ^ Chris@523: service ^ "\"") Chris@523: Chris@523: fun login_for ({ accounts, ... } : context) service = Chris@523: case List.find (fn a => service = #service a) accounts of Chris@523: SOME { login, ... } => SOME login Chris@523: | NONE => NONE Chris@523: Chris@523: fun remote_url (context : context) vcs source libname = Chris@523: case source of Chris@523: URL_SOURCE u => u Chris@523: | SERVICE_SOURCE { service, owner, repo } => Chris@523: provider_url { vcs = vcs, Chris@523: service = service, Chris@523: owner = owner, Chris@523: repo = case repo of Chris@523: SOME r => r Chris@523: | NONE => libname } Chris@523: (login_for context service) Chris@523: (#providers context) Chris@523: end Chris@523: Chris@523: structure HgControl :> VCS_CONTROL = struct Chris@523: Chris@523: type vcsstate = { id: string, modified: bool, Chris@523: branch: string, tags: string list } Chris@523: Chris@523: val hg_args = [ "--config", "ui.interactive=true" ] Chris@523: Chris@523: fun hg_command context libname args = Chris@523: FileBits.command context libname ("hg" :: hg_args @ args) Chris@523: Chris@523: fun hg_command_output context libname args = Chris@523: FileBits.command_output context libname ("hg" :: hg_args @ args) Chris@523: Chris@523: fun exists context libname = Chris@523: OK (OS.FileSys.isDir (FileBits.subpath context libname ".hg")) Chris@523: handle _ => OK false Chris@523: Chris@523: fun remote_for context (libname, source) = Chris@523: Provider.remote_url context HG source libname Chris@523: Chris@523: fun current_state context libname : vcsstate result = Chris@523: let fun is_branch text = text <> "" andalso #"(" = hd (explode text) Chris@523: and extract_branch b = Chris@523: if is_branch b (* need to remove enclosing parens *) Chris@523: then (implode o rev o tl o rev o tl o explode) b Chris@523: else "default" Chris@523: and is_modified id = id <> "" andalso #"+" = hd (rev (explode id)) Chris@523: and extract_id id = Chris@523: if is_modified id (* need to remove trailing "+" *) Chris@523: then (implode o rev o tl o rev o explode) id Chris@523: else id Chris@523: and split_tags tags = String.tokens (fn c => c = #"/") tags Chris@523: and state_for (id, branch, tags) = Chris@523: OK { id = extract_id id, Chris@523: modified = is_modified id, Chris@523: branch = extract_branch branch, Chris@523: tags = split_tags tags } Chris@523: in Chris@523: case hg_command_output context libname ["id"] of Chris@523: ERROR e => ERROR e Chris@523: | OK out => Chris@523: case String.tokens (fn x => x = #" ") out of Chris@523: [id, branch, tags] => state_for (id, branch, tags) Chris@523: | [id, other] => if is_branch other Chris@523: then state_for (id, other, "") Chris@523: else state_for (id, "", other) Chris@523: | [id] => state_for (id, "", "") Chris@523: | _ => ERROR ("Unexpected output from hg id: " ^ out) Chris@523: end Chris@523: Chris@523: fun branch_name branch = case branch of Chris@523: DEFAULT_BRANCH => "default" Chris@523: | BRANCH "" => "default" Chris@523: | BRANCH b => b Chris@523: Chris@523: fun id_of context libname = Chris@523: case current_state context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK { id, ... } => OK id Chris@523: Chris@523: fun is_at context (libname, id_or_tag) = Chris@523: case current_state context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK { id, tags, ... } => Chris@523: OK (String.isPrefix id_or_tag id orelse Chris@523: String.isPrefix id id_or_tag orelse Chris@523: List.exists (fn t => t = id_or_tag) tags) Chris@523: Chris@523: fun is_on_branch context (libname, b) = Chris@523: case current_state context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK { branch, ... } => OK (branch = branch_name b) Chris@523: Chris@523: fun is_newest_locally context (libname, branch) = Chris@523: case hg_command_output context libname Chris@523: ["log", "-l1", Chris@523: "-b", branch_name branch, Chris@523: "--template", "{node}"] of Chris@523: ERROR e => ERROR e Chris@523: | OK newest_in_repo => is_at context (libname, newest_in_repo) Chris@523: Chris@523: fun pull context libname = Chris@523: hg_command context libname Chris@523: (if FileBits.verbose () Chris@523: then ["pull"] Chris@523: else ["pull", "-q"]) Chris@523: Chris@523: fun is_newest context (libname, branch) = Chris@523: case is_newest_locally context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK false => OK false Chris@523: | OK true => Chris@523: case pull context libname of Chris@523: ERROR e => ERROR e Chris@523: | _ => is_newest_locally context (libname, branch) Chris@523: Chris@523: fun is_modified_locally context libname = Chris@523: case current_state context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK { modified, ... } => OK modified Chris@523: Chris@523: fun checkout context (libname, source, branch) = Chris@523: let val url = remote_for context (libname, source) Chris@523: in Chris@523: case FileBits.mkpath (FileBits.extpath context) of Chris@523: ERROR e => ERROR e Chris@523: | _ => hg_command context "" Chris@523: ["clone", "-u", branch_name branch, Chris@523: url, libname] Chris@523: end Chris@523: Chris@523: fun update context (libname, branch) = Chris@523: let val pull_result = pull context libname Chris@523: in Chris@523: case hg_command context libname ["update", branch_name branch] of Chris@523: ERROR e => ERROR e Chris@523: | _ => Chris@523: case pull_result of Chris@523: ERROR e => ERROR e Chris@523: | _ => id_of context libname Chris@523: end Chris@523: Chris@523: fun update_to context (libname, "") = Chris@523: ERROR "Non-empty id (tag or revision id) required for update_to" Chris@523: | update_to context (libname, id) = Chris@523: let val pull_result = pull context libname Chris@523: in Chris@523: case hg_command context libname ["update", "-r", id] of Chris@523: OK _ => id_of context libname Chris@523: | ERROR e => Chris@523: case pull_result of Chris@523: ERROR e' => ERROR e' (* this was the ur-error *) Chris@523: | _ => ERROR e Chris@523: end Chris@523: Chris@523: end Chris@523: Chris@523: structure GitControl :> VCS_CONTROL = struct Chris@523: Chris@523: (* With Git repos we always operate in detached HEAD state. Even Chris@523: the master branch is checked out using the remote reference, Chris@523: origin/master. *) Chris@523: Chris@523: fun git_command context libname args = Chris@523: FileBits.command context libname ("git" :: args) Chris@523: Chris@523: fun git_command_output context libname args = Chris@523: FileBits.command_output context libname ("git" :: args) Chris@523: Chris@523: fun exists context libname = Chris@523: OK (OS.FileSys.isDir (FileBits.subpath context libname ".git")) Chris@523: handle _ => OK false Chris@523: Chris@523: fun remote_for context (libname, source) = Chris@523: Provider.remote_url context GIT source libname Chris@523: Chris@523: fun branch_name branch = case branch of Chris@523: DEFAULT_BRANCH => "master" Chris@523: | BRANCH "" => "master" Chris@523: | BRANCH b => b Chris@523: Chris@523: fun remote_branch_name branch = "origin/" ^ branch_name branch Chris@523: Chris@523: fun checkout context (libname, source, branch) = Chris@523: let val url = remote_for context (libname, source) Chris@523: in Chris@523: case FileBits.mkpath (FileBits.extpath context) of Chris@523: OK () => git_command context "" Chris@523: ["clone", "-b", Chris@523: branch_name branch, Chris@523: url, libname] Chris@523: | ERROR e => ERROR e Chris@523: end Chris@523: Chris@523: (* NB git rev-parse HEAD shows revision id of current checkout; Chris@523: git rev-list -1 shows revision id of revision with that tag *) Chris@523: Chris@523: fun id_of context libname = Chris@523: git_command_output context libname ["rev-parse", "HEAD"] Chris@523: Chris@523: fun is_at context (libname, id_or_tag) = Chris@523: case id_of context libname of Chris@523: ERROR e => ERROR e Chris@523: | OK id => Chris@523: if String.isPrefix id_or_tag id orelse Chris@523: String.isPrefix id id_or_tag Chris@523: then OK true Chris@523: else Chris@523: case git_command_output context libname Chris@523: ["show-ref", Chris@523: "refs/tags/" ^ id_or_tag] of Chris@523: OK "" => OK false Chris@523: | ERROR _ => OK false Chris@523: | OK s => OK (id = hd (String.tokens (fn c => c = #" ") s)) Chris@523: Chris@523: fun branch_tip context (libname, branch) = Chris@523: git_command_output context libname Chris@523: ["rev-list", "-1", Chris@523: remote_branch_name branch] Chris@523: Chris@523: fun is_newest_locally context (libname, branch) = Chris@523: case branch_tip context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK rev => is_at context (libname, rev) Chris@523: Chris@523: fun is_on_branch context (libname, branch) = Chris@523: case branch_tip context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK rev => Chris@523: case is_at context (libname, rev) of Chris@523: ERROR e => ERROR e Chris@523: | OK true => OK true Chris@523: | OK false => Chris@523: case git_command context libname Chris@523: ["merge-base", "--is-ancestor", Chris@523: "HEAD", remote_branch_name branch] of Chris@523: ERROR e => OK false (* cmd returns non-zero for no *) Chris@523: | _ => OK true Chris@523: Chris@523: fun is_newest context (libname, branch) = Chris@523: case is_newest_locally context (libname, branch) of Chris@523: ERROR e => ERROR e Chris@523: | OK false => OK false Chris@523: | OK true => Chris@523: case git_command context libname ["fetch"] of Chris@523: ERROR e => ERROR e Chris@523: | _ => is_newest_locally context (libname, branch) Chris@523: Chris@523: fun is_modified_locally context libname = Chris@523: case git_command_output context libname ["status", "--porcelain"] of Chris@523: ERROR e => ERROR e Chris@523: | OK "" => OK false Chris@523: | OK _ => OK true Chris@523: Chris@523: (* This function updates to the latest revision on a branch rather Chris@523: than to a specific id or tag. We can't just checkout the given Chris@523: branch, as that will succeed even if the branch isn't up to Chris@523: date. We could checkout the branch and then fetch and merge, Chris@523: but it's perhaps cleaner not to maintain a local branch at all, Chris@523: but instead checkout the remote branch as a detached head. *) Chris@523: Chris@523: fun update context (libname, branch) = Chris@523: case git_command context libname ["fetch"] of Chris@523: ERROR e => ERROR e Chris@523: | _ => Chris@523: case git_command context libname ["checkout", "--detach", Chris@523: remote_branch_name branch] of Chris@523: ERROR e => ERROR e Chris@523: | _ => id_of context libname Chris@523: Chris@523: (* This function is dealing with a specific id or tag, so if we Chris@523: can successfully check it out (detached) then that's all we Chris@523: need to do, regardless of whether fetch succeeded or not. We do Chris@523: attempt the fetch first, though, purely in order to avoid ugly Chris@523: error messages in the common case where we're being asked to Chris@523: update to a new pin (from the lock file) that hasn't been Chris@523: fetched yet. *) Chris@523: Chris@523: fun update_to context (libname, "") = Chris@523: ERROR "Non-empty id (tag or revision id) required for update_to" Chris@523: | update_to context (libname, id) = Chris@523: let val fetch_result = git_command context libname ["fetch"] Chris@523: in Chris@523: case git_command context libname ["checkout", "--detach", id] of Chris@523: OK _ => id_of context libname Chris@523: | ERROR e => Chris@523: case fetch_result of Chris@523: ERROR e' => ERROR e' (* this was the ur-error *) Chris@523: | _ => ERROR e Chris@523: end Chris@523: Chris@523: end Chris@523: Chris@523: structure AnyLibControl :> LIB_CONTROL = struct Chris@523: Chris@523: structure H = LibControlFn(HgControl) Chris@523: structure G = LibControlFn(GitControl) Chris@523: Chris@523: fun review context (spec as { vcs, ... } : libspec) = Chris@523: (fn HG => H.review | GIT => G.review) vcs context spec Chris@523: Chris@523: fun status context (spec as { vcs, ... } : libspec) = Chris@523: (fn HG => H.status | GIT => G.status) vcs context spec Chris@523: Chris@523: fun update context (spec as { vcs, ... } : libspec) = Chris@523: (fn HG => H.update | GIT => G.update) vcs context spec Chris@529: Chris@529: fun id_of context (spec as { vcs, ... } : libspec) = Chris@529: (fn HG => H.id_of | GIT => G.id_of) vcs context spec Chris@529: end Chris@529: Chris@529: Chris@529: type exclusions = string list Chris@529: Chris@529: structure Archive :> sig Chris@529: Chris@529: val archive : string * exclusions -> project -> OS.Process.status Chris@529: Chris@529: end = struct Chris@529: Chris@529: (* The idea of "archive" is to replace hg/git archive, which won't Chris@529: include files, like the Vext-introduced external libraries, Chris@529: that are not under version control with the main repo. Chris@529: Chris@529: The process goes like this: Chris@529: Chris@529: - Make sure we have a target filename from the user, and take Chris@529: its basename as our archive directory name Chris@529: Chris@529: - Make an "archive root" subdir of the project repo, named Chris@529: typically .vext-archive Chris@529: Chris@529: - Identify the VCS used for the project repo. Note that any Chris@529: explicit references to VCS type in this structure are to Chris@529: the VCS used for the project (something Vext doesn't Chris@529: otherwise care about), not for an individual library Chris@529: Chris@529: - Synthesise a Vext project with the archive root as its Chris@529: root path, "." as its extdir, with one library whose Chris@529: name is the user-supplied basename and whose explicit Chris@529: source URL is the original project root; update that Chris@529: project -- thus cloning the original project to a subdir Chris@529: of the archive root Chris@529: Chris@529: - Synthesise a Vext project identical to the original one for Chris@529: this project, but with the newly-cloned copy as its root Chris@529: path; update that project -- thus checking out clean copies Chris@529: of the external library dirs Chris@529: Chris@529: - Call out to an archive program to archive up the new copy, Chris@529: running e.g. Chris@529: tar cvzf project-release.tar.gz \ Chris@529: --exclude=.hg --exclude=.git project-release Chris@529: in the archive root dir Chris@529: Chris@529: - (We also omit the vext-project.json file and any trace of Chris@529: Vext. It can't properly be run in a directory where the Chris@529: external project folders already exist but their repo history Chris@529: does not. End users shouldn't get to see Vext) Chris@529: Chris@529: - Clean up by deleting the new copy Chris@529: *) Chris@529: Chris@529: fun project_vcs_and_id dir = Chris@529: let val context = { Chris@529: rootpath = dir, Chris@529: extdir = ".", Chris@529: providers = [], Chris@529: accounts = [] Chris@529: } Chris@529: val vcs_maybe = Chris@529: case [HgControl.exists context ".", Chris@529: GitControl.exists context "."] of Chris@529: [OK true, OK false] => OK HG Chris@529: | [OK false, OK true] => OK GIT Chris@529: | _ => ERROR ("Unable to identify VCS for directory " ^ dir) Chris@529: in Chris@529: case vcs_maybe of Chris@529: ERROR e => ERROR e Chris@529: | OK vcs => Chris@529: case (fn HG => HgControl.id_of | GIT => GitControl.id_of) Chris@529: vcs context "." of Chris@529: ERROR e => ERROR ("Unable to obtain id of project repo: " Chris@529: ^ e) Chris@529: | OK id => OK (vcs, id) Chris@529: end Chris@529: Chris@529: fun make_archive_root (context : context) = Chris@529: let val path = OS.Path.joinDirFile { Chris@529: dir = #rootpath context, Chris@529: file = VextFilenames.archive_dir Chris@529: } Chris@529: in Chris@529: case FileBits.mkpath path of Chris@529: ERROR e => raise Fail ("Failed to create archive directory \"" Chris@529: ^ path ^ "\": " ^ e) Chris@529: | OK () => path Chris@529: end Chris@529: Chris@529: fun archive_path archive_dir target_name = Chris@529: OS.Path.joinDirFile { Chris@529: dir = archive_dir, Chris@529: file = target_name Chris@529: } Chris@529: Chris@529: fun check_nonexistent path = Chris@529: case SOME (OS.FileSys.fileSize path) handle OS.SysErr _ => NONE of Chris@529: NONE => () Chris@529: | _ => raise Fail ("Path " ^ path ^ " exists, not overwriting") Chris@529: Chris@529: fun file_url path = Chris@529: let val forward_path = Chris@529: String.translate (fn #"\\" => "/" | Chris@529: c => Char.toString c) path Chris@529: in Chris@529: (* Path is expected to be absolute already, but if it Chris@529: starts with a drive letter, we'll need an extra slash *) Chris@529: case explode forward_path of Chris@529: #"/"::rest => "file:///" ^ implode rest Chris@529: | _ => "file:///" ^ forward_path Chris@529: end Chris@529: Chris@529: fun make_archive_copy target_name (vcs, project_id) Chris@529: ({ context, ... } : project) = Chris@529: let val archive_root = make_archive_root context Chris@529: val synthetic_context = { Chris@529: rootpath = archive_root, Chris@529: extdir = ".", Chris@529: providers = [], Chris@529: accounts = [] Chris@529: } Chris@529: val synthetic_library = { Chris@529: libname = target_name, Chris@529: vcs = vcs, Chris@529: source = URL_SOURCE (file_url (#rootpath context)), Chris@529: branch = DEFAULT_BRANCH, (* overridden by pinned id below *) Chris@529: project_pin = PINNED project_id, Chris@529: lock_pin = PINNED project_id Chris@529: } Chris@529: val path = archive_path archive_root target_name Chris@529: val _ = print ("Cloning original project to " ^ path Chris@529: ^ " at revision " ^ project_id ^ "...\n"); Chris@529: val _ = check_nonexistent path Chris@529: in Chris@529: case AnyLibControl.update synthetic_context synthetic_library of Chris@529: ERROR e => ERROR ("Failed to clone original project to " Chris@529: ^ path ^ ": " ^ e) Chris@529: | OK _ => OK archive_root Chris@529: end Chris@529: Chris@529: fun update_archive archive_root target_name Chris@529: (project as { context, ... } : project) = Chris@529: let val synthetic_context = { Chris@529: rootpath = archive_path archive_root target_name, Chris@529: extdir = #extdir context, Chris@529: providers = #providers context, Chris@529: accounts = #accounts context Chris@529: } Chris@529: in Chris@529: foldl (fn (lib, acc) => Chris@529: case acc of Chris@529: ERROR e => ERROR e Chris@529: | OK _ => AnyLibControl.update synthetic_context lib) Chris@529: (OK "") Chris@529: (#libs project) Chris@529: end Chris@529: Chris@529: datatype packer = TAR Chris@529: | TAR_GZ Chris@529: | TAR_BZ2 Chris@529: | TAR_XZ Chris@529: (* could add other packers, e.g. zip, if we knew how to Chris@529: handle the file omissions etc properly in pack_archive *) Chris@529: Chris@529: fun packer_and_basename path = Chris@529: let val extensions = [ (".tar", TAR), Chris@529: (".tar.gz", TAR_GZ), Chris@529: (".tar.bz2", TAR_BZ2), Chris@529: (".tar.xz", TAR_XZ)] Chris@529: val filename = OS.Path.file path Chris@529: in Chris@529: foldl (fn ((ext, packer), acc) => Chris@529: if String.isSuffix ext filename Chris@529: then SOME (packer, Chris@529: String.substring (filename, 0, Chris@529: String.size filename - Chris@529: String.size ext)) Chris@529: else acc) Chris@529: NONE Chris@529: extensions Chris@529: end Chris@529: Chris@529: fun pack_archive archive_root target_name target_path packer exclusions = Chris@529: case FileBits.command { Chris@529: rootpath = archive_root, Chris@529: extdir = ".", Chris@529: providers = [], Chris@529: accounts = [] Chris@529: } "" ([ Chris@529: "tar", Chris@529: case packer of Chris@529: TAR => "cf" Chris@529: | TAR_GZ => "czf" Chris@529: | TAR_BZ2 => "cjf" Chris@529: | TAR_XZ => "cJf", Chris@529: target_path, Chris@529: "--exclude=.hg", Chris@529: "--exclude=.git", Chris@529: "--exclude=vext", Chris@529: "--exclude=vext.sml", Chris@529: "--exclude=vext.ps1", Chris@529: "--exclude=vext.bat", Chris@529: "--exclude=vext-project.json", Chris@529: "--exclude=vext-lock.json" Chris@529: ] @ (map (fn e => "--exclude=" ^ e) exclusions) @ Chris@529: [ target_name ]) Chris@529: of Chris@529: ERROR e => ERROR e Chris@529: | OK _ => FileBits.rmpath (archive_path archive_root target_name) Chris@529: Chris@529: fun archive (target_path, exclusions) (project : project) = Chris@529: let val _ = check_nonexistent target_path Chris@529: val (packer, name) = Chris@529: case packer_and_basename target_path of Chris@529: NONE => raise Fail ("Unsupported archive file extension in " Chris@529: ^ target_path) Chris@529: | SOME pn => pn Chris@529: val details = Chris@529: case project_vcs_and_id (#rootpath (#context project)) of Chris@529: ERROR e => raise Fail e Chris@529: | OK details => details Chris@529: val archive_root = Chris@529: case make_archive_copy name details project of Chris@529: ERROR e => raise Fail e Chris@529: | OK archive_root => archive_root Chris@529: val outcome = Chris@529: case update_archive archive_root name project of Chris@529: ERROR e => ERROR e Chris@529: | OK _ => Chris@529: case pack_archive archive_root name Chris@529: target_path packer exclusions of Chris@529: ERROR e => ERROR e Chris@529: | OK _ => OK () Chris@529: in Chris@529: case outcome of Chris@529: ERROR e => raise Fail e Chris@529: | OK () => OS.Process.success Chris@529: end Chris@529: Chris@523: end Chris@523: Chris@523: val libobjname = "libraries" Chris@523: Chris@523: fun load_libspec spec_json lock_json libname : libspec = Chris@523: let open JsonBits Chris@523: val libobj = lookup_mandatory spec_json [libobjname, libname] Chris@523: val vcs = lookup_mandatory_string libobj ["vcs"] Chris@523: val retrieve = lookup_optional_string libobj Chris@523: val service = retrieve ["service"] Chris@523: val owner = retrieve ["owner"] Chris@523: val repo = retrieve ["repository"] Chris@523: val url = retrieve ["url"] Chris@523: val branch = retrieve ["branch"] Chris@529: val project_pin = case retrieve ["pin"] of Chris@529: NONE => UNPINNED Chris@529: | SOME p => PINNED p Chris@523: val lock_pin = case lookup_optional lock_json [libobjname, libname] of Chris@529: NONE => UNPINNED Chris@529: | SOME ll => case lookup_optional_string ll ["pin"] of Chris@529: SOME p => PINNED p Chris@529: | NONE => UNPINNED Chris@523: in Chris@523: { Chris@523: libname = libname, Chris@523: vcs = case vcs of Chris@523: "hg" => HG Chris@523: | "git" => GIT Chris@523: | other => raise Fail ("Unknown version-control system \"" ^ Chris@523: other ^ "\""), Chris@523: source = case (url, service, owner, repo) of Chris@523: (SOME u, NONE, _, _) => URL_SOURCE u Chris@523: | (NONE, SOME ss, owner, repo) => Chris@523: SERVICE_SOURCE { service = ss, owner = owner, repo = repo } Chris@523: | _ => raise Fail ("Must have exactly one of service " ^ Chris@523: "or url string"), Chris@529: project_pin = project_pin, Chris@529: lock_pin = lock_pin, Chris@523: branch = case branch of Chris@523: SOME b => BRANCH b Chris@523: | NONE => DEFAULT_BRANCH Chris@523: } Chris@523: end Chris@523: Chris@523: fun load_userconfig () : userconfig = Chris@523: let val home = FileBits.homedir () Chris@523: val conf_json = Chris@523: JsonBits.load_json_from Chris@523: (OS.Path.joinDirFile { Chris@523: dir = home, Chris@523: file = VextFilenames.user_config_file }) Chris@523: handle IO.Io _ => Json.OBJECT [] Chris@523: in Chris@523: { Chris@523: accounts = case JsonBits.lookup_optional conf_json ["accounts"] of Chris@523: NONE => [] Chris@523: | SOME (Json.OBJECT aa) => Chris@523: map (fn (k, (Json.STRING v)) => Chris@523: { service = k, login = v } Chris@523: | _ => raise Fail Chris@523: "String expected for account name") Chris@523: aa Chris@523: | _ => raise Fail "Array expected for accounts", Chris@523: providers = Provider.load_providers conf_json Chris@523: } Chris@523: end Chris@523: Chris@523: datatype pintype = Chris@523: NO_LOCKFILE | Chris@523: USE_LOCKFILE Chris@523: Chris@523: fun load_project (userconfig : userconfig) rootpath pintype : project = Chris@523: let val spec_file = FileBits.project_spec_path rootpath Chris@523: val lock_file = FileBits.project_lock_path rootpath Chris@523: val _ = if OS.FileSys.access (spec_file, [OS.FileSys.A_READ]) Chris@523: handle OS.SysErr _ => false Chris@523: then () Chris@523: else raise Fail ("Failed to open project spec file " ^ Chris@523: (VextFilenames.project_file) ^ " in " ^ Chris@523: rootpath ^ Chris@523: ".\nPlease ensure the spec file is in the " ^ Chris@523: "project root and run this from there.") Chris@523: val spec_json = JsonBits.load_json_from spec_file Chris@523: val lock_json = if pintype = USE_LOCKFILE Chris@523: then JsonBits.load_json_from lock_file Chris@523: handle IO.Io _ => Json.OBJECT [] Chris@523: else Json.OBJECT [] Chris@523: val extdir = JsonBits.lookup_mandatory_string spec_json Chris@523: ["config", "extdir"] Chris@523: val spec_libs = JsonBits.lookup_optional spec_json [libobjname] Chris@523: val lock_libs = JsonBits.lookup_optional lock_json [libobjname] Chris@523: val providers = Provider.load_more_providers Chris@523: (#providers userconfig) spec_json Chris@523: val libnames = case spec_libs of Chris@523: NONE => [] Chris@523: | SOME (Json.OBJECT ll) => map (fn (k, v) => k) ll Chris@523: | _ => raise Fail "Object expected for libs" Chris@523: in Chris@523: { Chris@523: context = { Chris@523: rootpath = rootpath, Chris@523: extdir = extdir, Chris@523: providers = providers, Chris@523: accounts = #accounts userconfig Chris@523: }, Chris@523: libs = map (load_libspec spec_json lock_json) libnames Chris@523: } Chris@523: end Chris@523: Chris@523: fun save_lock_file rootpath locks = Chris@523: let val lock_file = FileBits.project_lock_path rootpath Chris@523: open Json Chris@523: val lock_json = Chris@523: OBJECT [ Chris@523: (libobjname, Chris@523: OBJECT (map (fn { libname, id_or_tag } => Chris@523: (libname, Chris@523: OBJECT [ ("pin", STRING id_or_tag) ])) Chris@523: locks)) Chris@523: ] Chris@523: in Chris@523: JsonBits.save_json_to lock_file lock_json Chris@523: end Chris@523: Chris@523: fun pad_to n str = Chris@523: if n <= String.size str then str Chris@523: else pad_to n (str ^ " ") Chris@523: Chris@523: fun hline_to 0 = "" Chris@523: | hline_to n = "-" ^ hline_to (n-1) Chris@523: Chris@523: val libname_width = 25 Chris@523: val libstate_width = 11 Chris@529: val localstate_width = 17 Chris@523: val notes_width = 5 Chris@523: val divider = " | " Chris@529: val clear_line = "\r" ^ pad_to 80 ""; Chris@523: Chris@523: fun print_status_header () = Chris@529: print (clear_line ^ "\n " ^ Chris@523: pad_to libname_width "Library" ^ divider ^ Chris@523: pad_to libstate_width "State" ^ divider ^ Chris@523: pad_to localstate_width "Local" ^ divider ^ Chris@523: "Notes" ^ "\n " ^ Chris@523: hline_to libname_width ^ "-+-" ^ Chris@523: hline_to libstate_width ^ "-+-" ^ Chris@523: hline_to localstate_width ^ "-+-" ^ Chris@523: hline_to notes_width ^ "\n") Chris@523: Chris@523: fun print_outcome_header () = Chris@529: print (clear_line ^ "\n " ^ Chris@523: pad_to libname_width "Library" ^ divider ^ Chris@523: pad_to libstate_width "Outcome" ^ divider ^ Chris@523: "Notes" ^ "\n " ^ Chris@523: hline_to libname_width ^ "-+-" ^ Chris@523: hline_to libstate_width ^ "-+-" ^ Chris@523: hline_to notes_width ^ "\n") Chris@523: Chris@523: fun print_status with_network (libname, status) = Chris@523: let val libstate_str = Chris@523: case status of Chris@523: OK (ABSENT, _) => "Absent" Chris@523: | OK (CORRECT, _) => if with_network then "Correct" else "Present" Chris@523: | OK (SUPERSEDED, _) => "Superseded" Chris@523: | OK (WRONG, _) => "Wrong" Chris@523: | ERROR _ => "Error" Chris@523: val localstate_str = Chris@523: case status of Chris@523: OK (_, MODIFIED) => "Modified" Chris@529: | OK (_, LOCK_MISMATCHED) => "Differs from Lock" Chris@529: | OK (_, CLEAN) => "Clean" Chris@529: | ERROR _ => "" Chris@523: val error_str = Chris@523: case status of Chris@523: ERROR e => e Chris@523: | _ => "" Chris@523: in Chris@523: print (" " ^ Chris@523: pad_to libname_width libname ^ divider ^ Chris@523: pad_to libstate_width libstate_str ^ divider ^ Chris@523: pad_to localstate_width localstate_str ^ divider ^ Chris@523: error_str ^ "\n") Chris@523: end Chris@523: Chris@523: fun print_update_outcome (libname, outcome) = Chris@523: let val outcome_str = Chris@523: case outcome of Chris@523: OK id => "Ok" Chris@523: | ERROR e => "Failed" Chris@523: val error_str = Chris@523: case outcome of Chris@523: ERROR e => e Chris@523: | _ => "" Chris@523: in Chris@523: print (" " ^ Chris@523: pad_to libname_width libname ^ divider ^ Chris@523: pad_to libstate_width outcome_str ^ divider ^ Chris@523: error_str ^ "\n") Chris@523: end Chris@523: Chris@523: fun act_and_print action print_header print_line (libs : libspec list) = Chris@523: let val lines = map (fn lib => (#libname lib, action lib)) libs Chris@523: val _ = print_header () Chris@523: in Chris@523: app print_line lines; Chris@523: lines Chris@523: end Chris@523: Chris@523: fun return_code_for outcomes = Chris@523: foldl (fn ((_, result), acc) => Chris@523: case result of Chris@523: ERROR _ => OS.Process.failure Chris@523: | _ => acc) Chris@523: OS.Process.success Chris@523: outcomes Chris@523: Chris@523: fun status_of_project ({ context, libs } : project) = Chris@523: return_code_for (act_and_print (AnyLibControl.status context) Chris@523: print_status_header (print_status false) Chris@523: libs) Chris@523: Chris@523: fun review_project ({ context, libs } : project) = Chris@523: return_code_for (act_and_print (AnyLibControl.review context) Chris@523: print_status_header (print_status true) Chris@523: libs) Chris@523: Chris@523: fun update_project ({ context, libs } : project) = Chris@523: let val outcomes = act_and_print Chris@523: (AnyLibControl.update context) Chris@523: print_outcome_header print_update_outcome libs Chris@523: val locks = Chris@523: List.concat Chris@523: (map (fn (libname, result) => Chris@523: case result of Chris@523: ERROR _ => [] Chris@523: | OK id => [{ libname = libname, id_or_tag = id }]) Chris@523: outcomes) Chris@523: val return_code = return_code_for outcomes Chris@523: in Chris@523: if OS.Process.isSuccess return_code Chris@523: then save_lock_file (#rootpath context) locks Chris@523: else (); Chris@523: return_code Chris@523: end Chris@523: Chris@529: fun lock_project ({ context, libs } : project) = Chris@529: let val outcomes = map (fn lib => Chris@529: (#libname lib, AnyLibControl.id_of context lib)) Chris@529: libs Chris@529: val locks = Chris@529: List.concat Chris@529: (map (fn (libname, result) => Chris@529: case result of Chris@529: ERROR _ => [] Chris@529: | OK id => [{ libname = libname, id_or_tag = id }]) Chris@529: outcomes) Chris@529: val return_code = return_code_for outcomes Chris@529: val _ = print clear_line Chris@529: in Chris@529: if OS.Process.isSuccess return_code Chris@529: then save_lock_file (#rootpath context) locks Chris@529: else (); Chris@529: return_code Chris@529: end Chris@529: Chris@523: fun load_local_project pintype = Chris@523: let val userconfig = load_userconfig () Chris@523: val rootpath = OS.FileSys.getDir () Chris@523: in Chris@523: load_project userconfig rootpath pintype Chris@523: end Chris@523: Chris@523: fun with_local_project pintype f = Chris@523: let val return_code = f (load_local_project pintype) Chris@529: handle e => (print ("Error: " ^ exnMessage e); Chris@529: OS.Process.failure) Chris@523: val _ = print "\n"; Chris@523: in Chris@523: return_code Chris@523: end Chris@523: Chris@529: fun review () = with_local_project USE_LOCKFILE review_project Chris@529: fun status () = with_local_project USE_LOCKFILE status_of_project Chris@523: fun update () = with_local_project NO_LOCKFILE update_project Chris@529: fun lock () = with_local_project NO_LOCKFILE lock_project Chris@523: fun install () = with_local_project USE_LOCKFILE update_project Chris@523: Chris@523: fun version () = Chris@523: (print ("v" ^ vext_version ^ "\n"); Chris@523: OS.Process.success) Chris@523: Chris@523: fun usage () = Chris@523: (print "\nVext "; Chris@523: version (); Chris@523: print ("\nA simple manager for third-party source code dependencies.\n\n" Chris@523: ^ "Usage:\n\n" Chris@523: ^ " vext \n\n" Chris@523: ^ "where is one of:\n\n" Chris@523: ^ " status print quick report on local status only, without using network\n" Chris@523: ^ " review check configured libraries against their providers, and report\n" Chris@523: ^ " install update configured libraries according to project specs and lock file\n" Chris@523: ^ " update update configured libraries and lock file according to project specs\n" Chris@529: ^ " lock update lock file to match local library status\n" Chris@529: ^ " archive pack up project and all libraries into an archive file\n" Chris@529: ^ " (invoke as 'vext archive target-file.tar.gz')\n" Chris@523: ^ " version print the Vext version number and exit\n\n"); Chris@523: OS.Process.failure) Chris@523: Chris@529: fun archive target args = Chris@529: case args of Chris@529: [] => Chris@529: with_local_project USE_LOCKFILE (Archive.archive (target, [])) Chris@529: | "--exclude"::xs => Chris@529: with_local_project USE_LOCKFILE (Archive.archive (target, xs)) Chris@529: | _ => usage () Chris@529: Chris@523: fun vext args = Chris@523: let val return_code = Chris@523: case args of Chris@523: ["review"] => review () Chris@523: | ["status"] => status () Chris@523: | ["install"] => install () Chris@523: | ["update"] => update () Chris@529: | ["lock"] => lock () Chris@523: | ["version"] => version () Chris@529: | "archive"::target::args => archive target args Chris@523: | _ => usage () Chris@523: in Chris@523: OS.Process.exit return_code; Chris@523: () Chris@523: end Chris@523: Chris@523: fun main () = Chris@523: vext (CommandLine.arguments ())