Chris@0: (* Chris@0: DO NOT EDIT THIS FILE. Chris@0: This file is automatically generated from the individual Chris@0: source files in the Repoint repository. Chris@0: *) Chris@0: Chris@0: (* Chris@0: Repoint Chris@0: Chris@0: A simple manager for third-party source code dependencies Chris@0: Chris@0: Copyright 2018 Chris Cannam, Particular Programs Ltd, Chris@0: and Queen Mary, University of London Chris@0: Chris@0: Permission is hereby granted, free of charge, to any person Chris@0: obtaining a copy of this software and associated documentation Chris@0: files (the "Software"), to deal in the Software without Chris@0: restriction, including without limitation the rights to use, copy, Chris@0: modify, merge, publish, distribute, sublicense, and/or sell copies Chris@0: of the Software, and to permit persons to whom the Software is Chris@0: furnished to do so, subject to the following conditions: Chris@0: Chris@0: The above copyright notice and this permission notice shall be Chris@0: included in all copies or substantial portions of the Software. Chris@0: Chris@0: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@0: EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@0: MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND Chris@0: NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR Chris@0: ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF Chris@0: CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@0: WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@0: Chris@0: Except as contained in this notice, the names of Chris Cannam, Chris@0: Particular Programs Ltd, and Queen Mary, University of London Chris@0: shall not be used in advertising or otherwise to promote the sale, Chris@0: use or other dealings in this Software without prior written Chris@0: authorization. Chris@0: *) Chris@0: Chris@0: val repoint_version = "1.2" Chris@0: Chris@0: Chris@0: datatype vcs = Chris@0: HG | Chris@0: GIT | Chris@0: SVN Chris@0: Chris@0: datatype source = Chris@0: URL_SOURCE of string | Chris@0: SERVICE_SOURCE of { Chris@0: service : string, Chris@0: owner : string option, Chris@0: repo : string option Chris@0: } Chris@0: Chris@0: type id_or_tag = string Chris@0: Chris@0: datatype pin = Chris@0: UNPINNED | Chris@0: PINNED of id_or_tag Chris@0: Chris@0: datatype libstate = Chris@0: ABSENT | Chris@0: CORRECT | Chris@0: SUPERSEDED | Chris@0: WRONG Chris@0: Chris@0: datatype localstate = Chris@0: MODIFIED | Chris@0: LOCK_MISMATCHED | Chris@0: CLEAN Chris@0: Chris@0: datatype branch = Chris@0: BRANCH of string | Chris@0: DEFAULT_BRANCH Chris@0: Chris@0: (* If we can recover from an error, for example by reporting failure Chris@0: for this one thing and going on to the next thing, then the error Chris@0: should usually be returned through a result type rather than an Chris@0: exception. *) Chris@0: Chris@0: datatype 'a result = Chris@0: OK of 'a | Chris@0: ERROR of string Chris@0: Chris@0: type libname = string Chris@0: Chris@0: type libspec = { Chris@0: libname : libname, Chris@0: vcs : vcs, Chris@0: source : source, Chris@0: branch : branch, Chris@0: project_pin : pin, Chris@0: lock_pin : pin Chris@0: } Chris@0: Chris@0: type lock = { Chris@0: libname : libname, Chris@0: id_or_tag : id_or_tag Chris@0: } Chris@0: Chris@0: type remote_spec = { Chris@0: anon : string option, Chris@0: auth : string option Chris@0: } Chris@0: Chris@0: type provider = { Chris@0: service : string, Chris@0: supports : vcs list, Chris@0: remote_spec : remote_spec Chris@0: } Chris@0: Chris@0: type account = { Chris@0: service : string, Chris@0: login : string Chris@0: } Chris@0: Chris@0: type context = { Chris@0: rootpath : string, Chris@0: extdir : string, Chris@0: providers : provider list, Chris@0: accounts : account list Chris@0: } Chris@0: Chris@0: type userconfig = { Chris@0: providers : provider list, Chris@0: accounts : account list Chris@0: } Chris@0: Chris@0: type project = { Chris@0: context : context, Chris@0: libs : libspec list Chris@0: } Chris@0: Chris@0: structure RepointFilenames = struct Chris@0: val project_file = "repoint-project.json" Chris@0: val project_lock_file = "repoint-lock.json" Chris@0: val project_completion_file = ".repoint.point" Chris@0: val user_config_file = ".repoint.json" Chris@0: val archive_dir = ".repoint-archive" Chris@0: end Chris@0: Chris@0: signature VCS_CONTROL = sig Chris@0: Chris@0: (** Check whether the given VCS is installed and working *) Chris@0: val is_working : context -> bool result Chris@0: Chris@0: (** Test whether the library is present locally at all *) Chris@0: val exists : context -> libname -> bool result Chris@0: Chris@0: (** Return the id (hash) of the current revision for the library *) Chris@0: val id_of : context -> libname -> id_or_tag result Chris@0: Chris@0: (** Test whether the library is at the given id *) Chris@0: val is_at : context -> libname * id_or_tag -> bool result Chris@0: Chris@0: (** Test whether the library is on the given branch, i.e. is at Chris@0: the branch tip or an ancestor of it *) Chris@0: val is_on_branch : context -> libname * branch -> bool result Chris@0: Chris@0: (** Test whether the library is at the newest revision for the Chris@0: given branch. False may indicate that the branch has advanced Chris@0: or that the library is not on the branch at all. This function Chris@0: may use the network to check for new revisions *) Chris@0: val is_newest : context -> libname * source * branch -> bool result Chris@0: Chris@0: (** Test whether the library is at the newest revision available Chris@0: locally for the given branch. False may indicate that the Chris@0: branch has advanced or that the library is not on the branch Chris@0: at all. This function must not use the network *) Chris@0: val is_newest_locally : context -> libname * branch -> bool result Chris@0: Chris@0: (** Test whether the library has been modified in the local Chris@0: working copy *) Chris@0: val is_modified_locally : context -> libname -> bool result Chris@0: Chris@0: (** Check out, i.e. clone a fresh copy of, the repo for the given Chris@0: library on the given branch *) Chris@0: val checkout : context -> libname * source * branch -> unit result Chris@0: Chris@0: (** Update the library to the given branch tip. Assumes that a Chris@0: local copy of the library already exists *) Chris@0: val update : context -> libname * source * branch -> unit result Chris@0: Chris@0: (** Update the library to the given specific id or tag *) Chris@0: val update_to : context -> libname * source * id_or_tag -> unit result Chris@0: Chris@0: (** Return a URL from which the library can be cloned, given that Chris@0: the local copy already exists. For a DVCS this can be the Chris@0: local copy, but for a centralised VCS it will have to be the Chris@0: remote repository URL. Used for archiving *) Chris@0: val copy_url_for : context -> libname -> string result Chris@0: end Chris@0: Chris@0: signature LIB_CONTROL = sig Chris@0: val review : context -> libspec -> (libstate * localstate) result Chris@0: val status : context -> libspec -> (libstate * localstate) result Chris@0: val update : context -> libspec -> unit result Chris@0: val id_of : context -> libspec -> id_or_tag result Chris@0: val is_working : context -> vcs -> bool result Chris@0: end Chris@0: Chris@0: structure FileBits :> sig Chris@0: val extpath : context -> string Chris@0: val libpath : context -> libname -> string Chris@0: val subpath : context -> libname -> string -> string Chris@0: val command_output : context -> libname -> string list -> string result Chris@0: val command : context -> libname -> string list -> unit result Chris@0: val file_url : string -> string Chris@0: val file_contents : string -> string Chris@0: val mydir : unit -> string Chris@0: val homedir : unit -> string Chris@0: val mkpath : string -> unit result Chris@0: val rmpath : string -> unit result Chris@0: val nonempty_dir_exists : string -> bool Chris@0: val project_spec_path : string -> string Chris@0: val project_lock_path : string -> string Chris@0: val project_completion_path : string -> string Chris@0: val verbose : unit -> bool Chris@0: end = struct Chris@0: Chris@0: fun verbose () = Chris@0: case OS.Process.getEnv "REPOINT_VERBOSE" of Chris@0: SOME "0" => false Chris@0: | SOME _ => true Chris@0: | NONE => false Chris@0: Chris@0: fun split_relative path desc = Chris@0: case OS.Path.fromString path of Chris@0: { isAbs = true, ... } => raise Fail (desc ^ " may not be absolute") Chris@0: | { arcs, ... } => arcs Chris@0: Chris@0: fun extpath ({ rootpath, extdir, ... } : context) = Chris@0: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@0: in OS.Path.toString { Chris@0: isAbs = isAbs, Chris@0: vol = vol, Chris@0: arcs = arcs @ Chris@0: split_relative extdir "extdir" Chris@0: } Chris@0: end Chris@0: Chris@0: fun subpath ({ rootpath, extdir, ... } : context) libname remainder = Chris@0: (* NB libname is allowed to be a path fragment, e.g. foo/bar *) Chris@0: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@0: in OS.Path.toString { Chris@0: isAbs = isAbs, Chris@0: vol = vol, Chris@0: arcs = arcs @ Chris@0: split_relative extdir "extdir" @ Chris@0: split_relative libname "library path" @ Chris@0: split_relative remainder "subpath" Chris@0: } Chris@0: end Chris@0: Chris@0: fun libpath context "" = Chris@0: extpath context Chris@0: | libpath context libname = Chris@0: subpath context libname "" Chris@0: Chris@0: fun project_file_path rootpath filename = Chris@0: let val { isAbs, vol, arcs } = OS.Path.fromString rootpath Chris@0: in OS.Path.toString { Chris@0: isAbs = isAbs, Chris@0: vol = vol, Chris@0: arcs = arcs @ [ filename ] Chris@0: } Chris@0: end Chris@0: Chris@0: fun project_spec_path rootpath = Chris@0: project_file_path rootpath (RepointFilenames.project_file) Chris@0: Chris@0: fun project_lock_path rootpath = Chris@0: project_file_path rootpath (RepointFilenames.project_lock_file) Chris@0: Chris@0: fun project_completion_path rootpath = Chris@0: project_file_path rootpath (RepointFilenames.project_completion_file) Chris@0: Chris@0: fun trim str = Chris@0: hd (String.fields (fn x => x = #"\n" orelse x = #"\r") str) Chris@0: Chris@0: fun make_canonical path = Chris@0: (* SML/NJ doesn't properly handle "/" when splitting paths - Chris@0: it should be a path separator even on Windows, but SML/NJ Chris@0: treats it as a normal filename character there. So we must Chris@0: convert these explicitly *) Chris@0: OS.Path.mkCanonical Chris@0: (if OS.Path.concat ("a", "b") = "a\\b" Chris@0: then String.translate (fn #"/" => "\\" | Chris@0: c => Char.toString c) Chris@0: path Chris@0: else path) Chris@0: Chris@0: fun file_url path = Chris@0: let val forward_path = Chris@0: String.translate (fn #"\\" => "/" | Chris@0: c => Char.toString c) Chris@0: (OS.Path.mkCanonical path) Chris@0: in Chris@0: (* Path is expected to be absolute already, but if it Chris@0: starts with a drive letter, we'll need an extra slash *) Chris@0: case explode forward_path of Chris@0: #"/"::rest => "file:///" ^ implode rest Chris@0: | _ => "file:///" ^ forward_path Chris@0: end Chris@0: Chris@0: fun file_contents filename = Chris@0: let val stream = TextIO.openIn filename Chris@0: fun read_all str acc = Chris@0: case TextIO.inputLine str of Chris@0: SOME line => read_all str (trim line :: acc) Chris@0: | NONE => rev acc Chris@0: val contents = read_all stream [] Chris@0: val _ = TextIO.closeIn stream Chris@0: in Chris@0: String.concatWith "\n" contents Chris@0: end Chris@0: Chris@0: fun expand_commandline cmdlist = Chris@0: (* We are quite strict about what we accept here, except Chris@0: for the first element in cmdlist which is assumed to be a Chris@0: known command location rather than arbitrary user input. *) Chris@0: let open Char Chris@0: fun quote arg = Chris@0: if List.all Chris@0: (fn c => isAlphaNum c orelse c = #"-" orelse c = #"_") Chris@0: (explode arg) Chris@0: then arg Chris@0: else "\"" ^ arg ^ "\"" Chris@0: fun check arg = Chris@0: let val valid = explode " /#:;?,._-{}@=+%" Chris@0: in Chris@0: app (fn c => Chris@0: if isAlphaNum c orelse Chris@0: List.exists (fn v => v = c) valid orelse Chris@0: c > chr 127 Chris@0: then () Chris@0: else raise Fail ("Invalid character '" ^ Chris@0: (Char.toString c) ^ Chris@0: "' in command list")) Chris@0: (explode arg); Chris@0: arg Chris@0: end Chris@0: in Chris@0: String.concatWith " " Chris@0: (map quote Chris@0: (hd cmdlist :: map check (tl cmdlist))) Chris@0: end Chris@0: Chris@0: val tick_cycle = ref 0 Chris@0: val tick_chars = Vector.fromList (map String.str (explode "|/-\\")) Chris@0: Chris@0: fun tick libname cmdlist = Chris@0: let val n = Vector.length tick_chars Chris@0: fun pad_to n str = Chris@0: if n <= String.size str then str Chris@0: else pad_to n (str ^ " ") Chris@0: val name = if libname <> "" then libname Chris@0: else if cmdlist = nil then "" Chris@0: else hd (rev cmdlist) Chris@0: in Chris@0: print (" " ^ Chris@0: Vector.sub(tick_chars, !tick_cycle) ^ " " ^ Chris@0: pad_to 70 name ^ Chris@0: "\r"); Chris@0: tick_cycle := (if !tick_cycle = n - 1 then 0 else 1 + !tick_cycle) Chris@0: end Chris@0: Chris@0: fun run_command context libname cmdlist redirect = Chris@0: let open OS Chris@0: val dir = libpath context libname Chris@0: val cmd = expand_commandline cmdlist Chris@0: val _ = if verbose () Chris@0: then print ("\n=== " ^ dir ^ "\n<<< " ^ cmd ^ "\n") Chris@0: else tick libname cmdlist Chris@0: val _ = FileSys.chDir dir Chris@0: val status = case redirect of Chris@0: NONE => Process.system cmd Chris@0: | SOME file => Process.system (cmd ^ ">" ^ file) Chris@0: in Chris@0: if Process.isSuccess status Chris@0: then OK () Chris@0: else ERROR ("Command failed: " ^ cmd ^ " (in dir " ^ dir ^ ")") Chris@0: end Chris@0: handle ex => ERROR ("Unable to run command: " ^ exnMessage ex) Chris@0: Chris@0: fun command context libname cmdlist = Chris@0: run_command context libname cmdlist NONE Chris@0: Chris@0: fun command_output context libname cmdlist = Chris@0: let open OS Chris@0: val tmpFile = FileSys.tmpName () Chris@0: val result = run_command context libname cmdlist (SOME tmpFile) Chris@0: val contents = file_contents tmpFile Chris@0: val _ = if verbose () Chris@0: then print (">>> \"" ^ contents ^ "\"\n") Chris@0: else () Chris@0: in Chris@0: FileSys.remove tmpFile handle _ => (); Chris@0: case result of Chris@0: OK () => OK contents Chris@0: | ERROR e => ERROR e Chris@0: end Chris@0: Chris@0: fun mydir () = Chris@0: let open OS Chris@0: val { dir, file } = Path.splitDirFile (CommandLine.name ()) Chris@0: in Chris@0: FileSys.realPath Chris@0: (if Path.isAbsolute dir Chris@0: then dir Chris@0: else Path.concat (FileSys.getDir (), dir)) Chris@0: end Chris@0: Chris@0: fun homedir () = Chris@0: (* Failure is not routine, so we use an exception here *) Chris@0: case (OS.Process.getEnv "HOME", Chris@0: OS.Process.getEnv "HOMEPATH") of Chris@0: (SOME home, _) => home Chris@0: | (NONE, SOME home) => home Chris@0: | (NONE, NONE) => Chris@0: raise Fail "Failed to look up home directory from environment" Chris@0: Chris@0: fun mkpath' path = Chris@0: if OS.FileSys.isDir path handle _ => false Chris@0: then OK () Chris@0: else case OS.Path.fromString path of Chris@0: { arcs = nil, ... } => OK () Chris@0: | { isAbs = false, ... } => ERROR "mkpath requires absolute path" Chris@0: | { isAbs, vol, arcs } => Chris@0: case mkpath' (OS.Path.toString { (* parent *) Chris@0: isAbs = isAbs, Chris@0: vol = vol, Chris@0: arcs = rev (tl (rev arcs)) }) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => ((OS.FileSys.mkDir path; OK ()) Chris@0: handle OS.SysErr (e, _) => Chris@0: ERROR ("Directory creation failed: " ^ e)) Chris@0: Chris@0: fun mkpath path = Chris@0: mkpath' (make_canonical path) Chris@0: Chris@0: fun dir_contents dir = Chris@0: let open OS Chris@0: fun files_from dirstream = Chris@0: case FileSys.readDir dirstream of Chris@0: NONE => [] Chris@0: | SOME file => Chris@0: (* readDir is supposed to filter these, Chris@0: but let's be extra cautious: *) Chris@0: if file = Path.parentArc orelse file = Path.currentArc Chris@0: then files_from dirstream Chris@0: else file :: files_from dirstream Chris@0: val stream = FileSys.openDir dir Chris@0: val files = map (fn f => Path.joinDirFile Chris@0: { dir = dir, file = f }) Chris@0: (files_from stream) Chris@0: val _ = FileSys.closeDir stream Chris@0: in Chris@0: files Chris@0: end Chris@0: Chris@0: fun rmpath' path = Chris@0: let open OS Chris@0: fun remove path = Chris@0: if FileSys.isLink path (* dangling links bother isDir *) Chris@0: then FileSys.remove path Chris@0: else if FileSys.isDir path Chris@0: then (app remove (dir_contents path); FileSys.rmDir path) Chris@0: else FileSys.remove path Chris@0: in Chris@0: (remove path; OK ()) Chris@0: handle SysErr (e, _) => ERROR ("Path removal failed: " ^ e) Chris@0: end Chris@0: Chris@0: fun rmpath path = Chris@0: rmpath' (make_canonical path) Chris@0: Chris@0: fun nonempty_dir_exists path = Chris@0: let open OS.FileSys Chris@0: in Chris@0: (not (isLink path) andalso Chris@0: isDir path andalso Chris@0: dir_contents path <> []) Chris@0: handle _ => false Chris@0: end Chris@0: Chris@0: end Chris@0: Chris@0: functor LibControlFn (V: VCS_CONTROL) :> LIB_CONTROL = struct Chris@0: Chris@0: (* Valid states for unpinned libraries: Chris@0: Chris@0: - CORRECT: We are on the right branch and are up-to-date with Chris@0: it as far as we can tell. (If not using the network, this Chris@0: should be reported to user as "Present" rather than "Correct" Chris@0: as the remote repo may have advanced without us knowing.) Chris@0: Chris@0: - SUPERSEDED: We are on the right branch but we can see that Chris@0: there is a newer revision either locally or on the remote (in Chris@0: Git terms, we are at an ancestor of the desired branch tip). Chris@0: Chris@0: - WRONG: We are on the wrong branch (in Git terms, we are not Chris@0: at the desired branch tip or any ancestor of it). Chris@0: Chris@0: - ABSENT: Repo doesn't exist here at all. Chris@0: Chris@0: Valid states for pinned libraries: Chris@0: Chris@0: - CORRECT: We are at the pinned revision. Chris@0: Chris@0: - WRONG: We are at any revision other than the pinned one. Chris@0: Chris@0: - ABSENT: Repo doesn't exist here at all. Chris@0: *) Chris@0: Chris@0: fun check with_network context Chris@0: ({ libname, source, branch, Chris@0: project_pin, lock_pin, ... } : libspec) = Chris@0: let fun check_unpinned () = Chris@0: let val newest = Chris@0: if with_network Chris@0: then V.is_newest context (libname, source, branch) Chris@0: else V.is_newest_locally context (libname, branch) Chris@0: in Chris@0: case newest of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK CORRECT Chris@0: | OK false => Chris@0: case V.is_on_branch context (libname, branch) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK SUPERSEDED Chris@0: | OK false => OK WRONG Chris@0: end Chris@0: fun check_pinned target = Chris@0: case V.is_at context (libname, target) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK CORRECT Chris@0: | OK false => OK WRONG Chris@0: fun check_remote () = Chris@0: case project_pin of Chris@0: UNPINNED => check_unpinned () Chris@0: | PINNED target => check_pinned target Chris@0: fun check_local () = Chris@0: case V.is_modified_locally context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK MODIFIED Chris@0: | OK false => Chris@0: case lock_pin of Chris@0: UNPINNED => OK CLEAN Chris@0: | PINNED target => Chris@0: case V.is_at context (libname, target) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK CLEAN Chris@0: | OK false => OK LOCK_MISMATCHED Chris@0: in Chris@0: case V.exists context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK false => OK (ABSENT, CLEAN) Chris@0: | OK true => Chris@0: case (check_remote (), check_local ()) of Chris@0: (ERROR e, _) => ERROR e Chris@0: | (_, ERROR e) => ERROR e Chris@0: | (OK r, OK l) => OK (r, l) Chris@0: end Chris@0: Chris@0: val review = check true Chris@0: val status = check false Chris@0: Chris@0: fun update context Chris@0: ({ libname, source, branch, Chris@0: project_pin, lock_pin, ... } : libspec) = Chris@0: let fun update_unpinned () = Chris@0: case V.is_newest context (libname, source, branch) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK () Chris@0: | OK false => V.update context (libname, source, branch) Chris@0: fun update_pinned target = Chris@0: case V.is_at context (libname, target) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK () Chris@0: | OK false => V.update_to context (libname, source, target) Chris@0: fun update' () = Chris@0: case lock_pin of Chris@0: PINNED target => update_pinned target Chris@0: | UNPINNED => Chris@0: case project_pin of Chris@0: PINNED target => update_pinned target Chris@0: | UNPINNED => update_unpinned () Chris@0: in Chris@0: case V.exists context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK true => update' () Chris@0: | OK false => Chris@0: case V.checkout context (libname, source, branch) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => update' () Chris@0: end Chris@0: Chris@0: fun id_of context ({ libname, ... } : libspec) = Chris@0: V.id_of context libname Chris@0: Chris@0: fun is_working context vcs = Chris@0: V.is_working context Chris@0: Chris@0: end Chris@0: Chris@0: (* Simple Standard ML JSON parser Chris@0: https://bitbucket.org/cannam/sml-simplejson Chris@0: Copyright 2017 Chris Cannam. BSD licence. Chris@0: Parts based on the JSON parser in the Ponyo library by Phil Eaton. Chris@0: *) Chris@0: Chris@0: signature JSON = sig Chris@0: Chris@0: datatype json = OBJECT of (string * json) list Chris@0: | ARRAY of json list Chris@0: | NUMBER of real Chris@0: | STRING of string Chris@0: | BOOL of bool Chris@0: | NULL Chris@0: Chris@0: datatype 'a result = OK of 'a Chris@0: | ERROR of string Chris@0: Chris@0: val parse : string -> json result Chris@0: val serialise : json -> string Chris@0: val serialiseIndented : json -> string Chris@0: Chris@0: end Chris@0: Chris@0: structure Json :> JSON = struct Chris@0: Chris@0: datatype json = OBJECT of (string * json) list Chris@0: | ARRAY of json list Chris@0: | NUMBER of real Chris@0: | STRING of string Chris@0: | BOOL of bool Chris@0: | NULL Chris@0: Chris@0: datatype 'a result = OK of 'a Chris@0: | ERROR of string Chris@0: Chris@0: structure T = struct Chris@0: datatype token = NUMBER of char list Chris@0: | STRING of string Chris@0: | BOOL of bool Chris@0: | NULL Chris@0: | CURLY_L Chris@0: | CURLY_R Chris@0: | SQUARE_L Chris@0: | SQUARE_R Chris@0: | COLON Chris@0: | COMMA Chris@0: Chris@0: fun toString t = Chris@0: case t of NUMBER digits => implode digits Chris@0: | STRING s => s Chris@0: | BOOL b => Bool.toString b Chris@0: | NULL => "null" Chris@0: | CURLY_L => "{" Chris@0: | CURLY_R => "}" Chris@0: | SQUARE_L => "[" Chris@0: | SQUARE_R => "]" Chris@0: | COLON => ":" Chris@0: | COMMA => "," Chris@0: end Chris@0: Chris@0: fun bmpToUtf8 cp = (* convert a codepoint in Unicode BMP to utf8 bytes *) Chris@0: let open Word Chris@0: infix 6 orb andb >> Chris@0: in Chris@0: map (Char.chr o toInt) Chris@0: (if cp < 0wx80 then Chris@0: [cp] Chris@0: else if cp < 0wx800 then Chris@0: [0wxc0 orb (cp >> 0w6), 0wx80 orb (cp andb 0wx3f)] Chris@0: else if cp < 0wx10000 then Chris@0: [0wxe0 orb (cp >> 0w12), Chris@0: 0wx80 orb ((cp >> 0w6) andb 0wx3f), Chris@0: 0wx80 orb (cp andb 0wx3f)] Chris@0: else raise Fail ("Invalid BMP point " ^ (Word.toString cp))) Chris@0: end Chris@0: Chris@0: fun error pos text = ERROR (text ^ " at character position " ^ Chris@0: Int.toString (pos - 1)) Chris@0: fun token_error pos = error pos ("Unexpected token") Chris@0: Chris@0: fun lexNull pos acc (#"u" :: #"l" :: #"l" :: xs) = Chris@0: lex (pos + 3) (T.NULL :: acc) xs Chris@0: | lexNull pos acc _ = token_error pos Chris@0: Chris@0: and lexTrue pos acc (#"r" :: #"u" :: #"e" :: xs) = Chris@0: lex (pos + 3) (T.BOOL true :: acc) xs Chris@0: | lexTrue pos acc _ = token_error pos Chris@0: Chris@0: and lexFalse pos acc (#"a" :: #"l" :: #"s" :: #"e" :: xs) = Chris@0: lex (pos + 4) (T.BOOL false :: acc) xs Chris@0: | lexFalse pos acc _ = token_error pos Chris@0: Chris@0: and lexChar tok pos acc xs = Chris@0: lex pos (tok :: acc) xs Chris@0: Chris@0: and lexString pos acc cc = Chris@0: let datatype escaped = ESCAPED | NORMAL Chris@0: fun lexString' pos text ESCAPED [] = Chris@0: error pos "End of input during escape sequence" Chris@0: | lexString' pos text NORMAL [] = Chris@0: error pos "End of input during string" Chris@0: | lexString' pos text ESCAPED (x :: xs) = Chris@0: let fun esc c = lexString' (pos + 1) (c :: text) NORMAL xs Chris@0: in case x of Chris@0: #"\"" => esc x Chris@0: | #"\\" => esc x Chris@0: | #"/" => esc x Chris@0: | #"b" => esc #"\b" Chris@0: | #"f" => esc #"\f" Chris@0: | #"n" => esc #"\n" Chris@0: | #"r" => esc #"\r" Chris@0: | #"t" => esc #"\t" Chris@0: | _ => error pos ("Invalid escape \\" ^ Chris@0: Char.toString x) Chris@0: end Chris@0: | lexString' pos text NORMAL (#"\\" :: #"u" ::a::b::c::d:: xs) = Chris@0: if List.all Char.isHexDigit [a,b,c,d] Chris@0: then case Word.fromString ("0wx" ^ (implode [a,b,c,d])) of Chris@0: SOME w => (let val utf = rev (bmpToUtf8 w) in Chris@0: lexString' (pos + 6) (utf @ text) Chris@0: NORMAL xs Chris@0: end Chris@0: handle Fail err => error pos err) Chris@0: | NONE => error pos "Invalid Unicode BMP escape sequence" Chris@0: else error pos "Invalid Unicode BMP escape sequence" Chris@0: | lexString' pos text NORMAL (x :: xs) = Chris@0: if Char.ord x < 0x20 Chris@0: then error pos "Invalid unescaped control character" Chris@0: else Chris@0: case x of Chris@0: #"\"" => OK (rev text, xs, pos + 1) Chris@0: | #"\\" => lexString' (pos + 1) text ESCAPED xs Chris@0: | _ => lexString' (pos + 1) (x :: text) NORMAL xs Chris@0: in Chris@0: case lexString' pos [] NORMAL cc of Chris@0: OK (text, rest, newpos) => Chris@0: lex newpos (T.STRING (implode text) :: acc) rest Chris@0: | ERROR e => ERROR e Chris@0: end Chris@0: Chris@0: and lexNumber firstChar pos acc cc = Chris@0: let val valid = explode ".+-e" Chris@0: fun lexNumber' pos digits [] = (rev digits, [], pos) Chris@0: | lexNumber' pos digits (x :: xs) = Chris@0: if x = #"E" then lexNumber' (pos + 1) (#"e" :: digits) xs Chris@0: else if Char.isDigit x orelse List.exists (fn c => x = c) valid Chris@0: then lexNumber' (pos + 1) (x :: digits) xs Chris@0: else (rev digits, x :: xs, pos) Chris@0: val (digits, rest, newpos) = Chris@0: lexNumber' (pos - 1) [] (firstChar :: cc) Chris@0: in Chris@0: case digits of Chris@0: [] => token_error pos Chris@0: | _ => lex newpos (T.NUMBER digits :: acc) rest Chris@0: end Chris@0: Chris@0: and lex pos acc [] = OK (rev acc) Chris@0: | lex pos acc (x::xs) = Chris@0: (case x of Chris@0: #" " => lex Chris@0: | #"\t" => lex Chris@0: | #"\n" => lex Chris@0: | #"\r" => lex Chris@0: | #"{" => lexChar T.CURLY_L Chris@0: | #"}" => lexChar T.CURLY_R Chris@0: | #"[" => lexChar T.SQUARE_L Chris@0: | #"]" => lexChar T.SQUARE_R Chris@0: | #":" => lexChar T.COLON Chris@0: | #"," => lexChar T.COMMA Chris@0: | #"\"" => lexString Chris@0: | #"t" => lexTrue Chris@0: | #"f" => lexFalse Chris@0: | #"n" => lexNull Chris@0: | x => lexNumber x) (pos + 1) acc xs Chris@0: Chris@0: fun show [] = "end of input" Chris@0: | show (tok :: _) = T.toString tok Chris@0: Chris@0: fun parseNumber digits = Chris@0: (* Note lexNumber already case-insensitised the E for us *) Chris@0: let open Char Chris@0: Chris@0: fun okExpDigits [] = false Chris@0: | okExpDigits (c :: []) = isDigit c Chris@0: | okExpDigits (c :: cs) = isDigit c andalso okExpDigits cs Chris@0: Chris@0: fun okExponent [] = false Chris@0: | okExponent (#"+" :: cs) = okExpDigits cs Chris@0: | okExponent (#"-" :: cs) = okExpDigits cs Chris@0: | okExponent cc = okExpDigits cc Chris@0: Chris@0: fun okFracTrailing [] = true Chris@0: | okFracTrailing (c :: cs) = Chris@0: (isDigit c andalso okFracTrailing cs) orelse Chris@0: (c = #"e" andalso okExponent cs) Chris@0: Chris@0: fun okFraction [] = false Chris@0: | okFraction (c :: cs) = Chris@0: isDigit c andalso okFracTrailing cs Chris@0: Chris@0: fun okPosTrailing [] = true Chris@0: | okPosTrailing (#"." :: cs) = okFraction cs Chris@0: | okPosTrailing (#"e" :: cs) = okExponent cs Chris@0: | okPosTrailing (c :: cs) = Chris@0: isDigit c andalso okPosTrailing cs Chris@0: Chris@0: fun okPositive [] = false Chris@0: | okPositive (#"0" :: []) = true Chris@0: | okPositive (#"0" :: #"." :: cs) = okFraction cs Chris@0: | okPositive (#"0" :: #"e" :: cs) = okExponent cs Chris@0: | okPositive (#"0" :: cs) = false Chris@0: | okPositive (c :: cs) = isDigit c andalso okPosTrailing cs Chris@0: Chris@0: fun okNumber (#"-" :: cs) = okPositive cs Chris@0: | okNumber cc = okPositive cc Chris@0: in Chris@0: if okNumber digits Chris@0: then case Real.fromString (implode digits) of Chris@0: NONE => ERROR "Number out of range" Chris@0: | SOME r => OK r Chris@0: else ERROR ("Invalid number \"" ^ (implode digits) ^ "\"") Chris@0: end Chris@0: Chris@0: fun parseObject (T.CURLY_R :: xs) = OK (OBJECT [], xs) Chris@0: | parseObject tokens = Chris@0: let fun parsePair (T.STRING key :: T.COLON :: xs) = Chris@0: (case parseTokens xs of Chris@0: ERROR e => ERROR e Chris@0: | OK (j, xs) => OK ((key, j), xs)) Chris@0: | parsePair other = Chris@0: ERROR ("Object key/value pair expected around \"" ^ Chris@0: show other ^ "\"") Chris@0: fun parseObject' acc [] = ERROR "End of input during object" Chris@0: | parseObject' acc tokens = Chris@0: case parsePair tokens of Chris@0: ERROR e => ERROR e Chris@0: | OK (pair, T.COMMA :: xs) => Chris@0: parseObject' (pair :: acc) xs Chris@0: | OK (pair, T.CURLY_R :: xs) => Chris@0: OK (OBJECT (rev (pair :: acc)), xs) Chris@0: | OK (_, _) => ERROR "Expected , or } after object element" Chris@0: in Chris@0: parseObject' [] tokens Chris@0: end Chris@0: Chris@0: and parseArray (T.SQUARE_R :: xs) = OK (ARRAY [], xs) Chris@0: | parseArray tokens = Chris@0: let fun parseArray' acc [] = ERROR "End of input during array" Chris@0: | parseArray' acc tokens = Chris@0: case parseTokens tokens of Chris@0: ERROR e => ERROR e Chris@0: | OK (j, T.COMMA :: xs) => parseArray' (j :: acc) xs Chris@0: | OK (j, T.SQUARE_R :: xs) => OK (ARRAY (rev (j :: acc)), xs) Chris@0: | OK (_, _) => ERROR "Expected , or ] after array element" Chris@0: in Chris@0: parseArray' [] tokens Chris@0: end Chris@0: Chris@0: and parseTokens [] = ERROR "Value expected" Chris@0: | parseTokens (tok :: xs) = Chris@0: (case tok of Chris@0: T.NUMBER d => (case parseNumber d of Chris@0: OK r => OK (NUMBER r, xs) Chris@0: | ERROR e => ERROR e) Chris@0: | T.STRING s => OK (STRING s, xs) Chris@0: | T.BOOL b => OK (BOOL b, xs) Chris@0: | T.NULL => OK (NULL, xs) Chris@0: | T.CURLY_L => parseObject xs Chris@0: | T.SQUARE_L => parseArray xs Chris@0: | _ => ERROR ("Unexpected token " ^ T.toString tok ^ Chris@0: " before " ^ show xs)) Chris@0: Chris@0: fun parse str = Chris@0: case lex 1 [] (explode str) of Chris@0: ERROR e => ERROR e Chris@0: | OK tokens => case parseTokens tokens of Chris@0: OK (value, []) => OK value Chris@0: | OK (_, _) => ERROR "Extra data after input" Chris@0: | ERROR e => ERROR e Chris@0: Chris@0: fun stringEscape s = Chris@0: let fun esc x = [x, #"\\"] Chris@0: fun escape' acc [] = rev acc Chris@0: | escape' acc (x :: xs) = Chris@0: escape' (case x of Chris@0: #"\"" => esc x @ acc Chris@0: | #"\\" => esc x @ acc Chris@0: | #"\b" => esc #"b" @ acc Chris@0: | #"\f" => esc #"f" @ acc Chris@0: | #"\n" => esc #"n" @ acc Chris@0: | #"\r" => esc #"r" @ acc Chris@0: | #"\t" => esc #"t" @ acc Chris@0: | _ => Chris@0: let val c = Char.ord x Chris@0: in Chris@0: if c < 0x20 Chris@0: then let val hex = Word.toString (Word.fromInt c) Chris@0: in (rev o explode) (if c < 0x10 Chris@0: then ("\\u000" ^ hex) Chris@0: else ("\\u00" ^ hex)) Chris@0: end @ acc Chris@0: else Chris@0: x :: acc Chris@0: end) Chris@0: xs Chris@0: in Chris@0: implode (escape' [] (explode s)) Chris@0: end Chris@0: Chris@0: fun serialise json = Chris@0: case json of Chris@0: OBJECT pp => "{" ^ String.concatWith Chris@0: "," (map (fn (key, value) => Chris@0: serialise (STRING key) ^ ":" ^ Chris@0: serialise value) pp) ^ Chris@0: "}" Chris@0: | ARRAY arr => "[" ^ String.concatWith "," (map serialise arr) ^ "]" Chris@0: | NUMBER n => implode (map (fn #"~" => #"-" | c => c) Chris@0: (explode (Real.toString n))) Chris@0: | STRING s => "\"" ^ stringEscape s ^ "\"" Chris@0: | BOOL b => Bool.toString b Chris@0: | NULL => "null" Chris@0: Chris@0: fun serialiseIndented json = Chris@0: let fun indent 0 = "" Chris@0: | indent i = " " ^ indent (i - 1) Chris@0: fun serialiseIndented' i json = Chris@0: let val ser = serialiseIndented' (i + 1) Chris@0: in Chris@0: case json of Chris@0: OBJECT [] => "{}" Chris@0: | ARRAY [] => "[]" Chris@0: | OBJECT pp => "{\n" ^ indent (i + 1) ^ Chris@0: String.concatWith Chris@0: (",\n" ^ indent (i + 1)) Chris@0: (map (fn (key, value) => Chris@0: ser (STRING key) ^ ": " ^ Chris@0: ser value) pp) ^ Chris@0: "\n" ^ indent i ^ "}" Chris@0: | ARRAY arr => "[\n" ^ indent (i + 1) ^ Chris@0: String.concatWith Chris@0: (",\n" ^ indent (i + 1)) Chris@0: (map ser arr) ^ Chris@0: "\n" ^ indent i ^ "]" Chris@0: | other => serialise other Chris@0: end Chris@0: in Chris@0: serialiseIndented' 0 json ^ "\n" Chris@0: end Chris@0: Chris@0: end Chris@0: Chris@0: Chris@0: structure JsonBits :> sig Chris@0: exception Config of string Chris@0: val load_json_from : string -> Json.json (* filename -> json *) Chris@0: val save_json_to : string -> Json.json -> unit Chris@0: val lookup_optional : Json.json -> string list -> Json.json option Chris@0: val lookup_optional_string : Json.json -> string list -> string option Chris@0: val lookup_mandatory : Json.json -> string list -> Json.json Chris@0: val lookup_mandatory_string : Json.json -> string list -> string Chris@0: end = struct Chris@0: Chris@0: exception Config of string Chris@0: Chris@0: fun load_json_from filename = Chris@0: case Json.parse (FileBits.file_contents filename) of Chris@0: Json.OK json => json Chris@0: | Json.ERROR e => raise Config ("Failed to parse file: " ^ e) Chris@0: Chris@0: fun save_json_to filename json = Chris@0: (* using binary I/O to avoid ever writing CR/LF line endings *) Chris@0: let val jstr = Json.serialiseIndented json Chris@0: val stream = BinIO.openOut filename Chris@0: in Chris@0: BinIO.output (stream, Byte.stringToBytes jstr); Chris@0: BinIO.closeOut stream Chris@0: end Chris@0: Chris@0: fun lookup_optional json kk = Chris@0: let fun lookup key = Chris@0: case json of Chris@0: Json.OBJECT kvs => Chris@0: (case List.filter (fn (k, v) => k = key) kvs of Chris@0: [] => NONE Chris@0: | [(_,v)] => SOME v Chris@0: | _ => raise Config ("Duplicate key: " ^ Chris@0: (String.concatWith " -> " kk))) Chris@0: | _ => raise Config "Object expected" Chris@0: in Chris@0: case kk of Chris@0: [] => NONE Chris@0: | key::[] => lookup key Chris@0: | key::kk => case lookup key of Chris@0: NONE => NONE Chris@0: | SOME j => lookup_optional j kk Chris@0: end Chris@0: Chris@0: fun lookup_optional_string json kk = Chris@0: case lookup_optional json kk of Chris@0: SOME (Json.STRING s) => SOME s Chris@0: | SOME _ => raise Config ("Value (if present) must be string: " ^ Chris@0: (String.concatWith " -> " kk)) Chris@0: | NONE => NONE Chris@0: Chris@0: fun lookup_mandatory json kk = Chris@0: case lookup_optional json kk of Chris@0: SOME v => v Chris@0: | NONE => raise Config ("Value is mandatory: " ^ Chris@0: (String.concatWith " -> " kk)) Chris@0: Chris@0: fun lookup_mandatory_string json kk = Chris@0: case lookup_optional json kk of Chris@0: SOME (Json.STRING s) => s Chris@0: | _ => raise Config ("Value must be string: " ^ Chris@0: (String.concatWith " -> " kk)) Chris@0: end Chris@0: Chris@0: structure Provider :> sig Chris@0: val load_providers : Json.json -> provider list Chris@0: val load_more_providers : provider list -> Json.json -> provider list Chris@0: val remote_url : context -> vcs -> source -> libname -> string Chris@0: end = struct Chris@0: Chris@0: val known_providers : provider list = Chris@0: [ { Chris@0: service = "bitbucket", Chris@0: supports = [HG, GIT], Chris@0: remote_spec = { Chris@0: anon = SOME "https://bitbucket.org/{owner}/{repository}", Chris@0: auth = SOME "ssh://{vcs}@bitbucket.org/{owner}/{repository}" Chris@0: } Chris@0: }, Chris@0: { Chris@0: service = "github", Chris@0: supports = [GIT], Chris@0: remote_spec = { Chris@0: anon = SOME "https://github.com/{owner}/{repository}", Chris@0: auth = SOME "ssh://{vcs}@github.com/{owner}/{repository}" Chris@0: } Chris@0: }, Chris@0: { service = "sourcehut", Chris@0: supports = [HG, GIT], Chris@0: remote_spec = { Chris@0: anon = SOME "https://{vcs}.sr.ht/%7E{owner}/{repository}", Chris@0: auth = SOME "ssh://{vcs}@{vcs}.sr.ht/%7E{owner}/{repository}" Chris@0: } Chris@0: } Chris@0: ] Chris@0: Chris@0: fun vcs_name vcs = Chris@0: case vcs of HG => "hg" Chris@0: | GIT => "git" Chris@0: | SVN => "svn" Chris@0: Chris@0: fun vcs_from_name name = Chris@0: case name of "hg" => HG Chris@0: | "git" => GIT Chris@0: | "svn" => SVN Chris@0: | other => raise Fail ("Unknown vcs name \"" ^ name ^ "\"") Chris@0: Chris@0: fun load_more_providers previously_loaded json = Chris@0: let open JsonBits Chris@0: fun load pjson pname : provider = Chris@0: { Chris@0: service = pname, Chris@0: supports = Chris@0: case lookup_mandatory pjson ["vcs"] of Chris@0: Json.ARRAY vv => Chris@0: map (fn (Json.STRING v) => vcs_from_name v Chris@0: | _ => raise Fail "Strings expected in vcs array") Chris@0: vv Chris@0: | _ => raise Fail "Array expected for vcs", Chris@0: remote_spec = { Chris@0: anon = lookup_optional_string pjson ["anonymous"], Chris@0: auth = lookup_optional_string pjson ["authenticated"] Chris@0: } Chris@0: } Chris@0: val loaded = Chris@0: case lookup_optional json ["services"] of Chris@0: NONE => [] Chris@0: | SOME (Json.OBJECT pl) => map (fn (k, v) => load v k) pl Chris@0: | _ => raise Fail "Object expected for services in config" Chris@0: val newly_loaded = Chris@0: List.filter (fn p => not (List.exists (fn pp => #service p = Chris@0: #service pp) Chris@0: previously_loaded)) Chris@0: loaded Chris@0: in Chris@0: previously_loaded @ newly_loaded Chris@0: end Chris@0: Chris@0: fun load_providers json = Chris@0: load_more_providers known_providers json Chris@0: Chris@0: fun expand_spec spec { vcs, service, owner, repo } login = Chris@0: (* ugly *) Chris@0: let fun replace str = Chris@0: case str of Chris@0: "vcs" => vcs_name vcs Chris@0: | "service" => service Chris@0: | "owner" => Chris@0: (case owner of Chris@0: SOME ostr => ostr Chris@0: | NONE => raise Fail ("Owner not specified for service " ^ Chris@0: service)) Chris@0: | "repository" => repo Chris@0: | "account" => Chris@0: (case login of Chris@0: SOME acc => acc Chris@0: | NONE => raise Fail ("Account not given for service " ^ Chris@0: service)) Chris@0: | other => raise Fail ("Unknown variable \"" ^ other ^ Chris@0: "\" in spec for service " ^ service) Chris@0: fun expand' acc sstr = Chris@0: case Substring.splitl (fn c => c <> #"{") sstr of Chris@0: (pfx, sfx) => Chris@0: if Substring.isEmpty sfx Chris@0: then rev (pfx :: acc) Chris@0: else Chris@0: case Substring.splitl (fn c => c <> #"}") sfx of Chris@0: (tok, remainder) => Chris@0: if Substring.isEmpty remainder Chris@0: then rev (tok :: pfx :: acc) Chris@0: else let val replacement = Chris@0: replace Chris@0: (* tok begins with "{": *) Chris@0: (Substring.string Chris@0: (Substring.triml 1 tok)) Chris@0: in Chris@0: expand' (Substring.full replacement :: Chris@0: pfx :: acc) Chris@0: (* remainder begins with "}": *) Chris@0: (Substring.triml 1 remainder) Chris@0: end Chris@0: in Chris@0: Substring.concat (expand' [] (Substring.full spec)) Chris@0: end Chris@0: Chris@0: fun provider_url req login providers = Chris@0: case providers of Chris@0: [] => raise Fail ("Unknown service \"" ^ (#service req) ^ Chris@0: "\" for vcs \"" ^ (vcs_name (#vcs req)) ^ "\"") Chris@0: | ({ service, supports, remote_spec : remote_spec } :: rest) => Chris@0: if service <> (#service req) orelse Chris@0: not (List.exists (fn v => v = (#vcs req)) supports) Chris@0: then provider_url req login rest Chris@0: else Chris@0: case (login, #auth remote_spec, #anon remote_spec) of Chris@0: (SOME _, SOME auth, _) => expand_spec auth req login Chris@0: | (SOME _, _, SOME anon) => expand_spec anon req NONE Chris@0: | (NONE, _, SOME anon) => expand_spec anon req NONE Chris@0: | _ => raise Fail ("No suitable anonymous or authenticated " ^ Chris@0: "URL spec provided for service \"" ^ Chris@0: service ^ "\"") Chris@0: Chris@0: fun login_for ({ accounts, ... } : context) service = Chris@0: case List.find (fn a => service = #service a) accounts of Chris@0: SOME { login, ... } => SOME login Chris@0: | NONE => NONE Chris@0: Chris@0: fun reponame_for path = Chris@0: case String.tokens (fn c => c = #"/") path of Chris@0: [] => raise Fail "Non-empty library path required" Chris@0: | toks => hd (rev toks) Chris@0: Chris@0: fun remote_url (context : context) vcs source libname = Chris@0: case source of Chris@0: URL_SOURCE u => u Chris@0: | SERVICE_SOURCE { service, owner, repo } => Chris@0: provider_url { vcs = vcs, Chris@0: service = service, Chris@0: owner = owner, Chris@0: repo = case repo of Chris@0: SOME r => r Chris@0: | NONE => reponame_for libname } Chris@0: (login_for context service) Chris@0: (#providers context) Chris@0: end Chris@0: Chris@0: structure HgControl :> VCS_CONTROL = struct Chris@0: Chris@0: (* Pulls always use an explicit URL, never just the default Chris@0: remote, in order to ensure we update properly if the location Chris@0: given in the project file changes. *) Chris@0: Chris@0: type vcsstate = { id: string, modified: bool, Chris@0: branch: string, tags: string list } Chris@0: Chris@0: val hg_program = "hg" Chris@0: Chris@0: val hg_args = [ "--config", "ui.interactive=true", Chris@0: "--config", "ui.merge=:merge" ] Chris@0: Chris@0: fun hg_command context libname args = Chris@0: FileBits.command context libname (hg_program :: hg_args @ args) Chris@0: Chris@0: fun hg_command_output context libname args = Chris@0: FileBits.command_output context libname (hg_program :: hg_args @ args) Chris@0: Chris@0: fun is_working context = Chris@0: case hg_command_output context "" ["--version"] of Chris@0: OK "" => OK false Chris@0: | OK _ => OK true Chris@0: | ERROR e => ERROR e Chris@0: Chris@0: fun exists context libname = Chris@0: OK (OS.FileSys.isDir (FileBits.subpath context libname ".hg")) Chris@0: handle _ => OK false Chris@0: Chris@0: fun remote_for context (libname, source) = Chris@0: Provider.remote_url context HG source libname Chris@0: Chris@0: fun current_state context libname : vcsstate result = Chris@0: let fun is_branch text = text <> "" andalso #"(" = hd (explode text) Chris@0: and extract_branch b = Chris@0: if is_branch b (* need to remove enclosing parens *) Chris@0: then (implode o rev o tl o rev o tl o explode) b Chris@0: else "default" Chris@0: and is_modified id = id <> "" andalso #"+" = hd (rev (explode id)) Chris@0: and extract_id id = Chris@0: if is_modified id (* need to remove trailing "+" *) Chris@0: then (implode o rev o tl o rev o explode) id Chris@0: else id Chris@0: and split_tags tags = String.tokens (fn c => c = #"/") tags Chris@0: and state_for (id, branch, tags) = Chris@0: OK { id = extract_id id, Chris@0: modified = is_modified id, Chris@0: branch = extract_branch branch, Chris@0: tags = split_tags tags } Chris@0: in Chris@0: case hg_command_output context libname ["id"] of Chris@0: ERROR e => ERROR e Chris@0: | OK out => Chris@0: case String.tokens (fn x => x = #" ") out of Chris@0: [id, branch, tags] => state_for (id, branch, tags) Chris@0: | [id, other] => if is_branch other Chris@0: then state_for (id, other, "") Chris@0: else state_for (id, "", other) Chris@0: | [id] => state_for (id, "", "") Chris@0: | _ => ERROR ("Unexpected output from hg id: " ^ out) Chris@0: end Chris@0: Chris@0: fun branch_name branch = case branch of Chris@0: DEFAULT_BRANCH => "default" Chris@0: | BRANCH "" => "default" Chris@0: | BRANCH b => b Chris@0: Chris@0: fun id_of context libname = Chris@0: case current_state context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK { id, ... } => OK id Chris@0: Chris@0: fun is_at context (libname, id_or_tag) = Chris@0: case current_state context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK { id, tags, ... } => Chris@0: OK (String.isPrefix id_or_tag id orelse Chris@0: String.isPrefix id id_or_tag orelse Chris@0: List.exists (fn t => t = id_or_tag) tags) Chris@0: Chris@0: fun is_on_branch context (libname, b) = Chris@0: case current_state context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK { branch, ... } => OK (branch = branch_name b) Chris@0: Chris@0: fun is_newest_locally context (libname, branch) = Chris@0: case hg_command_output context libname Chris@0: ["log", "-l1", Chris@0: "-b", branch_name branch, Chris@0: "--template", "{node}"] of Chris@0: ERROR e => OK false (* desired branch does not exist *) Chris@0: | OK newest_in_repo => is_at context (libname, newest_in_repo) Chris@0: Chris@0: fun pull context (libname, source) = Chris@0: let val url = remote_for context (libname, source) Chris@0: in Chris@0: hg_command context libname Chris@0: (if FileBits.verbose () Chris@0: then ["pull", url] Chris@0: else ["pull", "-q", url]) Chris@0: end Chris@0: Chris@0: fun is_newest context (libname, source, branch) = Chris@0: case is_newest_locally context (libname, branch) of Chris@0: ERROR e => ERROR e Chris@0: | OK false => OK false Chris@0: | OK true => Chris@0: case pull context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | _ => is_newest_locally context (libname, branch) Chris@0: Chris@0: fun is_modified_locally context libname = Chris@0: case current_state context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK { modified, ... } => OK modified Chris@0: Chris@0: fun checkout context (libname, source, branch) = Chris@0: let val url = remote_for context (libname, source) Chris@0: in Chris@0: (* make the lib dir rather than just the ext dir, since Chris@0: the lib dir might be nested and hg will happily check Chris@0: out into an existing empty dir anyway *) Chris@0: case FileBits.mkpath (FileBits.libpath context libname) of Chris@0: ERROR e => ERROR e Chris@0: | _ => hg_command context "" Chris@0: ["clone", "-u", branch_name branch, Chris@0: url, libname] Chris@0: end Chris@0: Chris@0: fun update context (libname, source, branch) = Chris@0: let val pull_result = pull context (libname, source) Chris@0: in Chris@0: case hg_command context libname ["update", branch_name branch] of Chris@0: ERROR e => ERROR e Chris@0: | _ => Chris@0: case pull_result of Chris@0: ERROR e => ERROR e Chris@0: | _ => OK () Chris@0: end Chris@0: Chris@0: fun update_to context (libname, _, "") = Chris@0: ERROR "Non-empty id (tag or revision id) required for update_to" Chris@0: | update_to context (libname, source, id) = Chris@0: let val pull_result = pull context (libname, source) Chris@0: in Chris@0: case hg_command context libname ["update", "-r", id] of Chris@0: OK _ => OK () Chris@0: | ERROR e => Chris@0: case pull_result of Chris@0: ERROR e' => ERROR e' (* this was the ur-error *) Chris@0: | _ => ERROR e Chris@0: end Chris@0: Chris@0: fun copy_url_for context libname = Chris@0: OK (FileBits.file_url (FileBits.libpath context libname)) Chris@0: Chris@0: end Chris@0: Chris@0: structure GitControl :> VCS_CONTROL = struct Chris@0: Chris@0: (* With Git repos we always operate in detached HEAD state. Even Chris@0: the master branch is checked out using a remote reference Chris@0: (repoint/master). The remote we use is always named repoint, and we Chris@0: update it to the expected URL each time we fetch, in order to Chris@0: ensure we update properly if the location given in the project Chris@0: file changes. The origin remote is unused. *) Chris@0: Chris@0: val git_program = "git" Chris@0: Chris@0: fun git_command context libname args = Chris@0: FileBits.command context libname (git_program :: args) Chris@0: Chris@0: fun git_command_output context libname args = Chris@0: FileBits.command_output context libname (git_program :: args) Chris@0: Chris@0: fun is_working context = Chris@0: case git_command_output context "" ["--version"] of Chris@0: OK "" => OK false Chris@0: | OK _ => OK true Chris@0: | ERROR e => ERROR e Chris@0: Chris@0: fun exists context libname = Chris@0: OK (OS.FileSys.isDir (FileBits.subpath context libname ".git")) Chris@0: handle _ => OK false Chris@0: Chris@0: fun remote_for context (libname, source) = Chris@0: Provider.remote_url context GIT source libname Chris@0: Chris@0: fun branch_name branch = case branch of Chris@0: DEFAULT_BRANCH => "master" Chris@0: | BRANCH "" => "master" Chris@0: | BRANCH b => b Chris@0: Chris@0: val our_remote = "repoint" Chris@0: Chris@0: fun remote_branch_name branch = our_remote ^ "/" ^ branch_name branch Chris@0: Chris@0: fun checkout context (libname, source, branch) = Chris@0: let val url = remote_for context (libname, source) Chris@0: in Chris@0: (* make the lib dir rather than just the ext dir, since Chris@0: the lib dir might be nested and git will happily check Chris@0: out into an existing empty dir anyway *) Chris@0: case FileBits.mkpath (FileBits.libpath context libname) of Chris@0: OK () => git_command context "" Chris@0: ["clone", "--origin", our_remote, Chris@0: "--branch", branch_name branch, Chris@0: url, libname] Chris@0: | ERROR e => ERROR e Chris@0: end Chris@0: Chris@0: fun add_our_remote context (libname, source) = Chris@0: (* When we do the checkout ourselves (above), we add the Chris@0: remote at the same time. But if the repo was cloned by Chris@0: someone else, we'll need to do it after the fact. Git Chris@0: doesn't seem to have a means to add a remote or change its Chris@0: url if it already exists; seems we have to do this: *) Chris@0: let val url = remote_for context (libname, source) Chris@0: in Chris@0: case git_command context libname Chris@0: ["remote", "set-url", our_remote, url] of Chris@0: OK () => OK () Chris@0: | ERROR e => git_command context libname Chris@0: ["remote", "add", "-f", our_remote, url] Chris@0: end Chris@0: Chris@0: (* NB git rev-parse HEAD shows revision id of current checkout; Chris@0: git rev-list -1 shows revision id of revision with that tag *) Chris@0: Chris@0: fun id_of context libname = Chris@0: git_command_output context libname ["rev-parse", "HEAD"] Chris@0: Chris@0: fun is_at context (libname, id_or_tag) = Chris@0: case id_of context libname of Chris@0: ERROR e => OK false (* HEAD nonexistent, expected in empty repo *) Chris@0: | OK id => Chris@0: if String.isPrefix id_or_tag id orelse Chris@0: String.isPrefix id id_or_tag Chris@0: then OK true Chris@0: else is_at_tag context (libname, id, id_or_tag) Chris@0: Chris@0: and is_at_tag context (libname, id, tag) = Chris@0: (* For annotated tags (with message) show-ref returns the tag Chris@0: object ref rather than that of the revision being tagged; Chris@0: we need the subsequent rev-list to chase that up. In fact Chris@0: the rev-list on its own is enough to get us the id direct Chris@0: from the tag name, but it fails with an error if the tag Chris@0: doesn't exist, whereas we want to handle that quietly in Chris@0: case the tag simply hasn't been pulled yet *) Chris@0: case git_command_output context libname Chris@0: ["show-ref", "refs/tags/" ^ tag, "--"] of Chris@0: OK "" => OK false (* Not a tag *) Chris@0: | ERROR _ => OK false Chris@0: | OK s => Chris@0: let val tag_ref = hd (String.tokens (fn c => c = #" ") s) Chris@0: in Chris@0: case git_command_output context libname Chris@0: ["rev-list", "-1", tag_ref] of Chris@0: OK tagged => OK (id = tagged) Chris@0: | ERROR _ => OK false Chris@0: end Chris@0: Chris@0: fun branch_tip context (libname, branch) = Chris@0: (* We don't have access to the source info or the network Chris@0: here, as this is used by status (e.g. via is_on_branch) as Chris@0: well as review. It's possible the remote branch won't exist, Chris@0: e.g. if the repo was checked out by something other than Chris@0: Repoint, and if that's the case, we can't add it here; we'll Chris@0: just have to fail, since checking against local branches Chris@0: instead could produce the wrong result. *) Chris@0: git_command_output context libname Chris@0: ["rev-list", "-1", Chris@0: remote_branch_name branch, "--"] Chris@0: Chris@0: fun is_newest_locally context (libname, branch) = Chris@0: case branch_tip context (libname, branch) of Chris@0: ERROR e => OK false Chris@0: | OK rev => is_at context (libname, rev) Chris@0: Chris@0: fun is_on_branch context (libname, branch) = Chris@0: case branch_tip context (libname, branch) of Chris@0: ERROR e => OK false Chris@0: | OK rev => Chris@0: case is_at context (libname, rev) of Chris@0: ERROR e => ERROR e Chris@0: | OK true => OK true Chris@0: | OK false => Chris@0: case git_command context libname Chris@0: ["merge-base", "--is-ancestor", Chris@0: "HEAD", remote_branch_name branch] of Chris@0: ERROR e => OK false (* cmd returns non-zero for no *) Chris@0: | _ => OK true Chris@0: Chris@0: fun fetch context (libname, source) = Chris@0: case add_our_remote context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | _ => git_command context libname ["fetch", our_remote] Chris@0: Chris@0: fun is_newest context (libname, source, branch) = Chris@0: case add_our_remote context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => Chris@0: case is_newest_locally context (libname, branch) of Chris@0: ERROR e => ERROR e Chris@0: | OK false => OK false Chris@0: | OK true => Chris@0: case fetch context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | _ => is_newest_locally context (libname, branch) Chris@0: Chris@0: fun is_modified_locally context libname = Chris@0: case git_command_output context libname ["status", "--porcelain"] of Chris@0: ERROR e => ERROR e Chris@0: | OK "" => OK false Chris@0: | OK _ => OK true Chris@0: Chris@0: (* This function updates to the latest revision on a branch rather Chris@0: than to a specific id or tag. We can't just checkout the given Chris@0: branch, as that will succeed even if the branch isn't up to Chris@0: date. We could checkout the branch and then fetch and merge, Chris@0: but it's perhaps cleaner not to maintain a local branch at all, Chris@0: but instead checkout the remote branch as a detached head. *) Chris@0: Chris@0: fun update context (libname, source, branch) = Chris@0: case fetch context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | _ => Chris@0: case git_command context libname ["checkout", "--detach", Chris@0: remote_branch_name branch] of Chris@0: ERROR e => ERROR e Chris@0: | _ => OK () Chris@0: Chris@0: (* This function is dealing with a specific id or tag, so if we Chris@0: can successfully check it out (detached) then that's all we Chris@0: need to do, regardless of whether fetch succeeded or not. We do Chris@0: attempt the fetch first, though, purely in order to avoid ugly Chris@0: error messages in the common case where we're being asked to Chris@0: update to a new pin (from the lock file) that hasn't been Chris@0: fetched yet. *) Chris@0: Chris@0: fun update_to context (libname, _, "") = Chris@0: ERROR "Non-empty id (tag or revision id) required for update_to" Chris@0: | update_to context (libname, source, id) = Chris@0: let val fetch_result = fetch context (libname, source) Chris@0: in Chris@0: case git_command context libname ["checkout", "--detach", id] of Chris@0: OK _ => OK () Chris@0: | ERROR e => Chris@0: case fetch_result of Chris@0: ERROR e' => ERROR e' (* this was the ur-error *) Chris@0: | _ => ERROR e Chris@0: end Chris@0: Chris@0: fun copy_url_for context libname = Chris@0: OK (FileBits.file_url (FileBits.libpath context libname)) Chris@0: Chris@0: end Chris@0: Chris@0: (* SubXml - A parser for a subset of XML Chris@0: https://bitbucket.org/cannam/sml-subxml Chris@0: Copyright 2018 Chris Cannam. BSD licence. Chris@0: *) Chris@0: Chris@0: signature SUBXML = sig Chris@0: Chris@0: datatype node = ELEMENT of { name : string, children : node list } Chris@0: | ATTRIBUTE of { name : string, value : string } Chris@0: | TEXT of string Chris@0: | CDATA of string Chris@0: | COMMENT of string Chris@0: Chris@0: datatype document = DOCUMENT of { name : string, children : node list } Chris@0: Chris@0: datatype 'a result = OK of 'a Chris@0: | ERROR of string Chris@0: Chris@0: val parse : string -> document result Chris@0: val serialise : document -> string Chris@0: Chris@0: end Chris@0: Chris@0: structure SubXml :> SUBXML = struct Chris@0: Chris@0: datatype node = ELEMENT of { name : string, children : node list } Chris@0: | ATTRIBUTE of { name : string, value : string } Chris@0: | TEXT of string Chris@0: | CDATA of string Chris@0: | COMMENT of string Chris@0: Chris@0: datatype document = DOCUMENT of { name : string, children : node list } Chris@0: Chris@0: datatype 'a result = OK of 'a Chris@0: | ERROR of string Chris@0: Chris@0: structure T = struct Chris@0: datatype token = ANGLE_L Chris@0: | ANGLE_R Chris@0: | ANGLE_SLASH_L Chris@0: | SLASH_ANGLE_R Chris@0: | EQUAL Chris@0: | NAME of string Chris@0: | TEXT of string Chris@0: | CDATA of string Chris@0: | COMMENT of string Chris@0: Chris@0: fun name t = Chris@0: case t of ANGLE_L => "<" Chris@0: | ANGLE_R => ">" Chris@0: | ANGLE_SLASH_L => " "/>" Chris@0: | EQUAL => "=" Chris@0: | NAME s => "name \"" ^ s ^ "\"" Chris@0: | TEXT s => "text" Chris@0: | CDATA _ => "CDATA section" Chris@0: | COMMENT _ => "comment" Chris@0: end Chris@0: Chris@0: structure Lex :> sig Chris@0: val lex : string -> T.token list result Chris@0: end = struct Chris@0: Chris@0: fun error pos text = Chris@0: ERROR (text ^ " at character position " ^ Int.toString (pos-1)) Chris@0: fun tokenError pos token = Chris@0: error pos ("Unexpected token '" ^ Char.toString token ^ "'") Chris@0: Chris@0: val nameEnd = explode " \t\n\r\"'!=?" Chris@0: Chris@0: fun quoted quote pos acc cc = Chris@0: let fun quoted' pos text [] = Chris@0: error pos "Document ends during quoted string" Chris@0: | quoted' pos text (x::xs) = Chris@0: if x = quote Chris@0: then OK (rev text, xs, pos+1) Chris@0: else quoted' (pos+1) (x::text) xs Chris@0: in Chris@0: case quoted' pos [] cc of Chris@0: ERROR e => ERROR e Chris@0: | OK (text, rest, newpos) => Chris@0: inside newpos (T.TEXT (implode text) :: acc) rest Chris@0: end Chris@0: Chris@0: and name first pos acc cc = Chris@0: let fun name' pos text [] = Chris@0: error pos "Document ends during name" Chris@0: | name' pos text (x::xs) = Chris@0: if List.find (fn c => c = x) nameEnd <> NONE Chris@0: then OK (rev text, (x::xs), pos) Chris@0: else name' (pos+1) (x::text) xs Chris@0: in Chris@0: case name' (pos-1) [] (first::cc) of Chris@0: ERROR e => ERROR e Chris@0: | OK ([], [], pos) => error pos "Document ends before name" Chris@0: | OK ([], (x::xs), pos) => tokenError pos x Chris@0: | OK (text, rest, pos) => Chris@0: inside pos (T.NAME (implode text) :: acc) rest Chris@0: end Chris@0: Chris@0: and comment pos acc cc = Chris@0: let fun comment' pos text cc = Chris@0: case cc of Chris@0: #"-" :: #"-" :: #">" :: xs => OK (rev text, xs, pos+3) Chris@0: | x :: xs => comment' (pos+1) (x::text) xs Chris@0: | [] => error pos "Document ends during comment" Chris@0: in Chris@0: case comment' pos [] cc of Chris@0: ERROR e => ERROR e Chris@0: | OK (text, rest, pos) => Chris@0: outside pos (T.COMMENT (implode text) :: acc) rest Chris@0: end Chris@0: Chris@0: and instruction pos acc cc = Chris@0: case cc of Chris@0: #"?" :: #">" :: xs => outside (pos+2) acc xs Chris@0: | #">" :: _ => tokenError pos #">" Chris@0: | x :: xs => instruction (pos+1) acc xs Chris@0: | [] => error pos "Document ends during processing instruction" Chris@0: Chris@0: and cdata pos acc cc = Chris@0: let fun cdata' pos text cc = Chris@0: case cc of Chris@0: #"]" :: #"]" :: #">" :: xs => OK (rev text, xs, pos+3) Chris@0: | x :: xs => cdata' (pos+1) (x::text) xs Chris@0: | [] => error pos "Document ends during CDATA section" Chris@0: in Chris@0: case cdata' pos [] cc of Chris@0: ERROR e => ERROR e Chris@0: | OK (text, rest, pos) => Chris@0: outside pos (T.CDATA (implode text) :: acc) rest Chris@0: end Chris@0: Chris@0: and doctype pos acc cc = Chris@0: case cc of Chris@0: #">" :: xs => outside (pos+1) acc xs Chris@0: | x :: xs => doctype (pos+1) acc xs Chris@0: | [] => error pos "Document ends during DOCTYPE" Chris@0: Chris@0: and declaration pos acc cc = Chris@0: case cc of Chris@0: #"-" :: #"-" :: xs => Chris@0: comment (pos+2) acc xs Chris@0: | #"[" :: #"C" :: #"D" :: #"A" :: #"T" :: #"A" :: #"[" :: xs => Chris@0: cdata (pos+7) acc xs Chris@0: | #"D" :: #"O" :: #"C" :: #"T" :: #"Y" :: #"P" :: #"E" :: xs => Chris@0: doctype (pos+7) acc xs Chris@0: | [] => error pos "Document ends during declaration" Chris@0: | _ => error pos "Unsupported declaration type" Chris@0: Chris@0: and left pos acc cc = Chris@0: case cc of Chris@0: #"/" :: xs => inside (pos+1) (T.ANGLE_SLASH_L :: acc) xs Chris@0: | #"!" :: xs => declaration (pos+1) acc xs Chris@0: | #"?" :: xs => instruction (pos+1) acc xs Chris@0: | xs => inside pos (T.ANGLE_L :: acc) xs Chris@0: Chris@0: and slash pos acc cc = Chris@0: case cc of Chris@0: #">" :: xs => outside (pos+1) (T.SLASH_ANGLE_R :: acc) xs Chris@0: | x :: _ => tokenError pos x Chris@0: | [] => error pos "Document ends before element closed" Chris@0: Chris@0: and close pos acc xs = outside pos (T.ANGLE_R :: acc) xs Chris@0: Chris@0: and equal pos acc xs = inside pos (T.EQUAL :: acc) xs Chris@0: Chris@0: and outside pos acc [] = OK acc Chris@0: | outside pos acc cc = Chris@0: let fun textOf text = T.TEXT (implode (rev text)) Chris@0: fun outside' pos [] acc [] = OK acc Chris@0: | outside' pos text acc [] = OK (textOf text :: acc) Chris@0: | outside' pos text acc (x::xs) = Chris@0: case x of Chris@0: #"<" => if text = [] Chris@0: then left (pos+1) acc xs Chris@0: else left (pos+1) (textOf text :: acc) xs Chris@0: | x => outside' (pos+1) (x::text) acc xs Chris@0: in Chris@0: outside' pos [] acc cc Chris@0: end Chris@0: Chris@0: and inside pos acc [] = error pos "Document ends within tag" Chris@0: | inside pos acc (#"<"::_) = tokenError pos #"<" Chris@0: | inside pos acc (x::xs) = Chris@0: (case x of Chris@0: #" " => inside | #"\t" => inside Chris@0: | #"\n" => inside | #"\r" => inside Chris@0: | #"\"" => quoted x | #"'" => quoted x Chris@0: | #"/" => slash | #">" => close | #"=" => equal Chris@0: | x => name x) (pos+1) acc xs Chris@0: Chris@0: fun lex str = Chris@0: case outside 1 [] (explode str) of Chris@0: ERROR e => ERROR e Chris@0: | OK tokens => OK (rev tokens) Chris@0: end Chris@0: Chris@0: structure Parse :> sig Chris@0: val parse : string -> document result Chris@0: end = struct Chris@0: Chris@0: fun show [] = "end of input" Chris@0: | show (tok :: _) = T.name tok Chris@0: Chris@0: fun error toks text = ERROR (text ^ " before " ^ show toks) Chris@0: Chris@0: fun attribute elt name toks = Chris@0: case toks of Chris@0: T.EQUAL :: T.TEXT value :: xs => Chris@0: namedElement { Chris@0: name = #name elt, Chris@0: children = ATTRIBUTE { name = name, value = value } :: Chris@0: #children elt Chris@0: } xs Chris@0: | T.EQUAL :: xs => error xs "Expected attribute value" Chris@0: | toks => error toks "Expected attribute assignment" Chris@0: Chris@0: and content elt toks = Chris@0: case toks of Chris@0: T.ANGLE_SLASH_L :: T.NAME n :: T.ANGLE_R :: xs => Chris@0: if n = #name elt Chris@0: then OK (elt, xs) Chris@0: else ERROR ("Closing tag " ^ Chris@0: "does not match opening <" ^ #name elt ^ ">") Chris@0: | T.TEXT text :: xs => Chris@0: content { Chris@0: name = #name elt, Chris@0: children = TEXT text :: #children elt Chris@0: } xs Chris@0: | T.CDATA text :: xs => Chris@0: content { Chris@0: name = #name elt, Chris@0: children = CDATA text :: #children elt Chris@0: } xs Chris@0: | T.COMMENT text :: xs => Chris@0: content { Chris@0: name = #name elt, Chris@0: children = COMMENT text :: #children elt Chris@0: } xs Chris@0: | T.ANGLE_L :: xs => Chris@0: (case element xs of Chris@0: ERROR e => ERROR e Chris@0: | OK (child, xs) => Chris@0: content { Chris@0: name = #name elt, Chris@0: children = ELEMENT child :: #children elt Chris@0: } xs) Chris@0: | tok :: xs => Chris@0: error xs ("Unexpected token " ^ T.name tok) Chris@0: | [] => Chris@0: ERROR ("Document ends within element \"" ^ #name elt ^ "\"") Chris@0: Chris@0: and namedElement elt toks = Chris@0: case toks of Chris@0: T.SLASH_ANGLE_R :: xs => OK (elt, xs) Chris@0: | T.NAME name :: xs => attribute elt name xs Chris@0: | T.ANGLE_R :: xs => content elt xs Chris@0: | x :: xs => error xs ("Unexpected token " ^ T.name x) Chris@0: | [] => ERROR "Document ends within opening tag" Chris@0: Chris@0: and element toks = Chris@0: case toks of Chris@0: T.NAME name :: xs => Chris@0: (case namedElement { name = name, children = [] } xs of Chris@0: ERROR e => ERROR e Chris@0: | OK ({ name, children }, xs) => Chris@0: OK ({ name = name, children = rev children }, xs)) Chris@0: | toks => error toks "Expected element name" Chris@0: Chris@0: and document [] = ERROR "Empty document" Chris@0: | document (tok :: xs) = Chris@0: case tok of Chris@0: T.TEXT _ => document xs Chris@0: | T.COMMENT _ => document xs Chris@0: | T.ANGLE_L => Chris@0: (case element xs of Chris@0: ERROR e => ERROR e Chris@0: | OK (elt, []) => OK (DOCUMENT elt) Chris@0: | OK (elt, (T.TEXT _ :: xs)) => OK (DOCUMENT elt) Chris@0: | OK (elt, xs) => error xs "Extra data after document") Chris@0: | _ => error xs ("Unexpected token " ^ T.name tok) Chris@0: Chris@0: fun parse str = Chris@0: case Lex.lex str of Chris@0: ERROR e => ERROR e Chris@0: | OK tokens => document tokens Chris@0: end Chris@0: Chris@0: structure Serialise :> sig Chris@0: val serialise : document -> string Chris@0: end = struct Chris@0: Chris@0: fun attributes nodes = Chris@0: String.concatWith Chris@0: " " Chris@0: (map node (List.filter Chris@0: (fn ATTRIBUTE _ => true | _ => false) Chris@0: nodes)) Chris@0: Chris@0: and nonAttributes nodes = Chris@0: String.concat Chris@0: (map node (List.filter Chris@0: (fn ATTRIBUTE _ => false | _ => true) Chris@0: nodes)) Chris@0: Chris@0: and node n = Chris@0: case n of Chris@0: TEXT string => Chris@0: string Chris@0: | CDATA string => Chris@0: "" Chris@0: | COMMENT string => Chris@0: "" Chris@0: | ATTRIBUTE { name, value } => Chris@0: name ^ "=" ^ "\"" ^ value ^ "\"" (*!!!*) Chris@0: | ELEMENT { name, children } => Chris@0: "<" ^ name ^ Chris@0: (case (attributes children) of Chris@0: "" => "" Chris@0: | s => " " ^ s) ^ Chris@0: (case (nonAttributes children) of Chris@0: "" => "/>" Chris@0: | s => ">" ^ s ^ "") Chris@0: Chris@0: fun serialise (DOCUMENT { name, children }) = Chris@0: "\n" ^ Chris@0: node (ELEMENT { name = name, children = children }) Chris@0: end Chris@0: Chris@0: val parse = Parse.parse Chris@0: val serialise = Serialise.serialise Chris@0: Chris@0: end Chris@0: Chris@0: Chris@0: structure SvnControl :> VCS_CONTROL = struct Chris@0: Chris@0: val svn_program = "svn" Chris@0: Chris@0: fun svn_command context libname args = Chris@0: FileBits.command context libname (svn_program :: args) Chris@0: Chris@0: fun svn_command_output context libname args = Chris@0: FileBits.command_output context libname (svn_program :: args) Chris@0: Chris@0: fun svn_command_lines context libname args = Chris@0: case svn_command_output context libname args of Chris@0: ERROR e => ERROR e Chris@0: | OK s => OK (String.tokens (fn c => c = #"\n" orelse c = #"\r") s) Chris@0: Chris@0: fun split_line_pair line = Chris@0: let fun strip_leading_ws str = case explode str of Chris@0: #" "::rest => implode rest Chris@0: | _ => str Chris@0: in Chris@0: case String.tokens (fn c => c = #":") line of Chris@0: [] => ("", "") Chris@0: | first::rest => Chris@0: (first, strip_leading_ws (String.concatWith ":" rest)) Chris@0: end Chris@0: Chris@0: fun is_working context = Chris@0: case svn_command_output context "" ["--version"] of Chris@0: OK "" => OK false Chris@0: | OK _ => OK true Chris@0: | ERROR e => ERROR e Chris@0: Chris@0: structure X = SubXml Chris@0: Chris@0: fun svn_info context libname route = Chris@0: (* SVN 1.9 has info --show-item which is just what we need, Chris@0: but at this point we still have 1.8 on the CI boxes so we Chris@0: might as well aim to support it. For that we really have to Chris@0: use the XML output format, since the default info output is Chris@0: localised. This is the only thing our mini-XML parser is Chris@0: used for though, so it would be good to trim it at some Chris@0: point *) Chris@0: let fun find elt [] = OK elt Chris@0: | find { children, ... } (first :: rest) = Chris@0: case List.find (fn (X.ELEMENT { name, ... }) => name = first Chris@0: | _ => false) Chris@0: children of Chris@0: NONE => ERROR ("No element \"" ^ first ^ "\" in SVN XML") Chris@0: | SOME (X.ELEMENT e) => find e rest Chris@0: | SOME _ => ERROR "Internal error" Chris@0: in Chris@0: case svn_command_output context libname ["info", "--xml"] of Chris@0: ERROR e => ERROR e Chris@0: | OK xml => Chris@0: case X.parse xml of Chris@0: X.ERROR e => ERROR e Chris@0: | X.OK (X.DOCUMENT doc) => find doc route Chris@0: end Chris@0: Chris@0: fun exists context libname = Chris@0: OK (OS.FileSys.isDir (FileBits.subpath context libname ".svn")) Chris@0: handle _ => OK false Chris@0: Chris@0: fun remote_for context (libname, source) = Chris@0: Provider.remote_url context SVN source libname Chris@0: Chris@0: (* Remote the checkout came from, not necessarily the one we want *) Chris@0: fun actual_remote_for context libname = Chris@0: case svn_info context libname ["entry", "url"] of Chris@0: ERROR e => ERROR e Chris@0: | OK { children, ... } => Chris@0: case List.find (fn (X.TEXT _) => true | _ => false) children of Chris@0: NONE => ERROR "No content for URL in SVN info XML" Chris@0: | SOME (X.TEXT url) => OK url Chris@0: | SOME _ => ERROR "Internal error" Chris@0: Chris@0: fun id_of context libname = Chris@0: case svn_info context libname ["entry"] of Chris@0: ERROR e => ERROR e Chris@0: | OK { children, ... } => Chris@0: case List.find Chris@0: (fn (X.ATTRIBUTE { name = "revision", ... }) => true Chris@0: | _ => false) Chris@0: children of Chris@0: NONE => ERROR "No revision for entry in SVN info XML" Chris@0: | SOME (X.ATTRIBUTE { value, ... }) => OK value Chris@0: | SOME _ => ERROR "Internal error" Chris@0: Chris@0: fun is_at context (libname, id_or_tag) = Chris@0: case id_of context libname of Chris@0: ERROR e => ERROR e Chris@0: | OK id => OK (id = id_or_tag) Chris@0: Chris@0: fun is_on_branch context (libname, b) = Chris@0: OK (b = DEFAULT_BRANCH) Chris@0: Chris@0: fun check_remote context (libname, source) = Chris@0: case (remote_for context (libname, source), Chris@0: actual_remote_for context libname) of Chris@0: (_, ERROR e) => ERROR e Chris@0: | (url, OK actual) => Chris@0: if actual = url Chris@0: then OK () Chris@0: else svn_command context libname ["relocate", url] Chris@0: Chris@0: fun is_newest context (libname, source, branch) = Chris@0: case check_remote context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => Chris@0: case svn_command_lines context libname Chris@0: ["status", "--show-updates"] of Chris@0: ERROR e => ERROR e Chris@0: | OK lines => Chris@0: case rev lines of Chris@0: [] => ERROR "No result returned for server status" Chris@0: | last_line::_ => Chris@0: case rev (String.tokens (fn c => c = #" ") last_line) of Chris@0: [] => ERROR "No revision field found in server status" Chris@0: | server_id::_ => is_at context (libname, server_id) Chris@0: Chris@0: fun is_newest_locally context (libname, branch) = Chris@0: OK true (* no local history *) Chris@0: Chris@0: fun is_modified_locally context libname = Chris@0: case svn_command_output context libname ["status"] of Chris@0: ERROR e => ERROR e Chris@0: | OK "" => OK false Chris@0: | OK _ => OK true Chris@0: Chris@0: fun checkout context (libname, source, branch) = Chris@0: let val url = remote_for context (libname, source) Chris@0: val path = FileBits.libpath context libname Chris@0: in Chris@0: if FileBits.nonempty_dir_exists path Chris@0: then (* Surprisingly, SVN itself has no problem with Chris@0: this. But for consistency with other VCSes we Chris@0: don't allow it *) Chris@0: ERROR ("Refusing checkout to nonempty dir \"" ^ path ^ "\"") Chris@0: else Chris@0: (* make the lib dir rather than just the ext dir, since Chris@0: the lib dir might be nested and svn will happily check Chris@0: out into an existing empty dir anyway *) Chris@0: case FileBits.mkpath (FileBits.libpath context libname) of Chris@0: ERROR e => ERROR e Chris@0: | _ => svn_command context "" ["checkout", url, libname] Chris@0: end Chris@0: Chris@0: fun update context (libname, source, branch) = Chris@0: case check_remote context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => Chris@0: case svn_command context libname Chris@0: ["update", "--accept", "postpone"] of Chris@0: ERROR e => ERROR e Chris@0: | _ => OK () Chris@0: Chris@0: fun update_to context (libname, _, "") = Chris@0: ERROR "Non-empty id (tag or revision id) required for update_to" Chris@0: | update_to context (libname, source, id) = Chris@0: case check_remote context (libname, source) of Chris@0: ERROR e => ERROR e Chris@0: | OK () => Chris@0: case svn_command context libname Chris@0: ["update", "-r", id, "--accept", "postpone"] of Chris@0: ERROR e => ERROR e Chris@0: | OK _ => OK () Chris@0: Chris@0: fun copy_url_for context libname = Chris@0: actual_remote_for context libname Chris@0: Chris@0: end Chris@0: Chris@0: structure AnyLibControl :> LIB_CONTROL = struct Chris@0: Chris@0: structure H = LibControlFn(HgControl) Chris@0: structure G = LibControlFn(GitControl) Chris@0: structure S = LibControlFn(SvnControl) Chris@0: Chris@0: fun review context (spec as { vcs, ... } : libspec) = Chris@0: (fn HG => H.review | GIT => G.review | SVN => S.review) vcs context spec Chris@0: Chris@0: fun status context (spec as { vcs, ... } : libspec) = Chris@0: (fn HG => H.status | GIT => G.status | SVN => S.status) vcs context spec Chris@0: Chris@0: fun update context (spec as { vcs, ... } : libspec) = Chris@0: (fn HG => H.update | GIT => G.update | SVN => S.update) vcs context spec Chris@0: Chris@0: fun id_of context (spec as { vcs, ... } : libspec) = Chris@0: (fn HG => H.id_of | GIT => G.id_of | SVN => S.id_of) vcs context spec Chris@0: Chris@0: fun is_working context vcs = Chris@0: (fn HG => H.is_working | GIT => G.is_working | SVN => S.is_working) Chris@0: vcs context vcs Chris@0: Chris@0: end Chris@0: Chris@0: Chris@0: type exclusions = string list Chris@0: Chris@0: structure Archive :> sig Chris@0: Chris@0: val archive : string * exclusions -> project -> OS.Process.status Chris@0: Chris@0: end = struct Chris@0: Chris@0: (* The idea of "archive" is to replace hg/git archive, which won't Chris@0: include files, like the Repoint-introduced external libraries, Chris@0: that are not under version control with the main repo. Chris@0: Chris@0: The process goes like this: Chris@0: Chris@0: - Make sure we have a target filename from the user, and take Chris@0: its basename as our archive directory name Chris@0: Chris@0: - Make an "archive root" subdir of the project repo, named Chris@0: typically .repoint-archive Chris@0: Chris@0: - Identify the VCS used for the project repo. Note that any Chris@0: explicit references to VCS type in this structure are to Chris@0: the VCS used for the project (something Repoint doesn't Chris@0: otherwise care about), not for an individual library Chris@0: Chris@0: - Synthesise a Repoint project with the archive root as its Chris@0: root path, "." as its extdir, with one library whose Chris@0: name is the user-supplied basename and whose explicit Chris@0: source URL is the original project root; update that Chris@0: project -- thus cloning the original project to a subdir Chris@0: of the archive root Chris@0: Chris@0: - Synthesise a Repoint project identical to the original one for Chris@0: this project, but with the newly-cloned copy as its root Chris@0: path; update that project -- thus checking out clean copies Chris@0: of the external library dirs Chris@0: Chris@0: - Call out to an archive program to archive up the new copy, Chris@0: running e.g. Chris@0: tar cvzf project-release.tar.gz \ Chris@0: --exclude=.hg --exclude=.git project-release Chris@0: in the archive root dir Chris@0: Chris@0: - (We also omit the repoint-project.json file and any trace of Chris@0: Repoint. It can't properly be run in a directory where the Chris@0: external project folders already exist but their repo history Chris@0: does not. End users shouldn't get to see Repoint) Chris@0: Chris@0: - Clean up by deleting the new copy Chris@0: *) Chris@0: Chris@0: fun project_vcs_id_and_url dir = Chris@0: let val context = { Chris@0: rootpath = dir, Chris@0: extdir = ".", Chris@0: providers = [], Chris@0: accounts = [] Chris@0: } Chris@0: val vcs_maybe = Chris@0: case [HgControl.exists context ".", Chris@0: GitControl.exists context ".", Chris@0: SvnControl.exists context "."] of Chris@0: [OK true, OK false, OK false] => OK HG Chris@0: | [OK false, OK true, OK false] => OK GIT Chris@0: | [OK false, OK false, OK true] => OK SVN Chris@0: | _ => ERROR ("Unable to identify VCS for directory " ^ dir) Chris@0: in Chris@0: case vcs_maybe of Chris@0: ERROR e => ERROR e Chris@0: | OK vcs => Chris@0: case (fn HG => HgControl.id_of Chris@0: | GIT => GitControl.id_of Chris@0: | SVN => SvnControl.id_of) Chris@0: vcs context "." of Chris@0: ERROR e => ERROR ("Unable to find id of project repo: " ^ e) Chris@0: | OK id => Chris@0: case (fn HG => HgControl.copy_url_for Chris@0: | GIT => GitControl.copy_url_for Chris@0: | SVN => SvnControl.copy_url_for) Chris@0: vcs context "." of Chris@0: ERROR e => ERROR ("Unable to find URL of project repo: " Chris@0: ^ e) Chris@0: | OK url => OK (vcs, id, url) Chris@0: end Chris@0: Chris@0: fun make_archive_root (context : context) = Chris@0: let val path = OS.Path.joinDirFile { Chris@0: dir = #rootpath context, Chris@0: file = RepointFilenames.archive_dir Chris@0: } Chris@0: in Chris@0: case FileBits.mkpath path of Chris@0: ERROR e => raise Fail ("Failed to create archive directory \"" Chris@0: ^ path ^ "\": " ^ e) Chris@0: | OK () => path Chris@0: end Chris@0: Chris@0: fun archive_path archive_dir target_name = Chris@0: OS.Path.joinDirFile { Chris@0: dir = archive_dir, Chris@0: file = target_name Chris@0: } Chris@0: Chris@0: fun check_nonexistent path = Chris@0: case SOME (OS.FileSys.fileSize path) handle OS.SysErr _ => NONE of Chris@0: NONE => () Chris@0: | _ => raise Fail ("Path " ^ path ^ " exists, not overwriting") Chris@0: Chris@0: fun make_archive_copy target_name (vcs, project_id, source_url) Chris@0: ({ context, ... } : project) = Chris@0: let val archive_root = make_archive_root context Chris@0: val synthetic_context = { Chris@0: rootpath = archive_root, Chris@0: extdir = ".", Chris@0: providers = [], Chris@0: accounts = [] Chris@0: } Chris@0: val synthetic_library = { Chris@0: libname = target_name, Chris@0: vcs = vcs, Chris@0: source = URL_SOURCE source_url, Chris@0: branch = DEFAULT_BRANCH, (* overridden by pinned id below *) Chris@0: project_pin = PINNED project_id, Chris@0: lock_pin = PINNED project_id Chris@0: } Chris@0: val path = archive_path archive_root target_name Chris@0: val _ = print ("Cloning original project to " ^ path Chris@0: ^ " at revision " ^ project_id ^ "...\n"); Chris@0: val _ = check_nonexistent path Chris@0: in Chris@0: case AnyLibControl.update synthetic_context synthetic_library of Chris@0: ERROR e => ERROR ("Failed to clone original project to " Chris@0: ^ path ^ ": " ^ e) Chris@0: | OK _ => OK archive_root Chris@0: end Chris@0: Chris@0: fun update_archive archive_root target_name Chris@0: (project as { context, ... } : project) = Chris@0: let val synthetic_context = { Chris@0: rootpath = archive_path archive_root target_name, Chris@0: extdir = #extdir context, Chris@0: providers = #providers context, Chris@0: accounts = #accounts context Chris@0: } Chris@0: in Chris@0: foldl (fn (lib, acc) => Chris@0: case acc of Chris@0: ERROR e => ERROR e Chris@0: | OK () => AnyLibControl.update synthetic_context lib) Chris@0: (OK ()) Chris@0: (#libs project) Chris@0: end Chris@0: Chris@0: datatype packer = TAR Chris@0: | TAR_GZ Chris@0: | TAR_BZ2 Chris@0: | TAR_XZ Chris@0: (* could add other packers, e.g. zip, if we knew how to Chris@0: handle the file omissions etc properly in pack_archive *) Chris@0: Chris@0: fun packer_and_basename path = Chris@0: let val extensions = [ (".tar", TAR), Chris@0: (".tar.gz", TAR_GZ), Chris@0: (".tar.bz2", TAR_BZ2), Chris@0: (".tar.xz", TAR_XZ)] Chris@0: val filename = OS.Path.file path Chris@0: in Chris@0: foldl (fn ((ext, packer), acc) => Chris@0: if String.isSuffix ext filename Chris@0: then SOME (packer, Chris@0: String.substring (filename, 0, Chris@0: String.size filename - Chris@0: String.size ext)) Chris@0: else acc) Chris@0: NONE Chris@0: extensions Chris@0: end Chris@0: Chris@0: fun pack_archive archive_root target_name target_path packer exclusions = Chris@0: case FileBits.command { Chris@0: rootpath = archive_root, Chris@0: extdir = ".", Chris@0: providers = [], Chris@0: accounts = [] Chris@0: } "" ([ Chris@0: "tar", Chris@0: case packer of Chris@0: TAR => "cf" Chris@0: | TAR_GZ => "czf" Chris@0: | TAR_BZ2 => "cjf" Chris@0: | TAR_XZ => "cJf", Chris@0: target_path, Chris@0: "--exclude=.hg", Chris@0: "--exclude=.git", Chris@0: "--exclude=.svn", Chris@0: "--exclude=repoint", Chris@0: "--exclude=repoint.sml", Chris@0: "--exclude=repoint.ps1", Chris@0: "--exclude=repoint.bat", Chris@0: "--exclude=repoint-project.json", Chris@0: "--exclude=repoint-lock.json" Chris@0: ] @ (map (fn e => "--exclude=" ^ e) exclusions) @ Chris@0: [ target_name ]) Chris@0: of Chris@0: ERROR e => ERROR e Chris@0: | OK _ => FileBits.rmpath (archive_path archive_root target_name) Chris@0: Chris@0: fun archive (target_path, exclusions) (project : project) = Chris@0: let val _ = check_nonexistent target_path Chris@0: val (packer, name) = Chris@0: case packer_and_basename target_path of Chris@0: NONE => raise Fail ("Unsupported archive file extension in " Chris@0: ^ target_path) Chris@0: | SOME pn => pn Chris@0: val details = Chris@0: case project_vcs_id_and_url (#rootpath (#context project)) of Chris@0: ERROR e => raise Fail e Chris@0: | OK details => details Chris@0: val archive_root = Chris@0: case make_archive_copy name details project of Chris@0: ERROR e => raise Fail e Chris@0: | OK archive_root => archive_root Chris@0: val outcome = Chris@0: case update_archive archive_root name project of Chris@0: ERROR e => ERROR e Chris@0: | OK _ => Chris@0: case pack_archive archive_root name Chris@0: target_path packer exclusions of Chris@0: ERROR e => ERROR e Chris@0: | OK _ => OK () Chris@0: in Chris@0: case outcome of Chris@0: ERROR e => raise Fail e Chris@0: | OK () => OS.Process.success Chris@0: end Chris@0: Chris@0: end Chris@0: Chris@0: val libobjname = "libraries" Chris@0: Chris@0: fun load_libspec spec_json lock_json libname : libspec = Chris@0: let open JsonBits Chris@0: val libobj = lookup_mandatory spec_json [libobjname, libname] Chris@0: val vcs = lookup_mandatory_string libobj ["vcs"] Chris@0: val retrieve = lookup_optional_string libobj Chris@0: val service = retrieve ["service"] Chris@0: val owner = retrieve ["owner"] Chris@0: val repo = retrieve ["repository"] Chris@0: val url = retrieve ["url"] Chris@0: val branch = retrieve ["branch"] Chris@0: val project_pin = case retrieve ["pin"] of Chris@0: NONE => UNPINNED Chris@0: | SOME p => PINNED p Chris@0: val lock_pin = case lookup_optional lock_json [libobjname, libname] of Chris@0: NONE => UNPINNED Chris@0: | SOME ll => case lookup_optional_string ll ["pin"] of Chris@0: SOME p => PINNED p Chris@0: | NONE => UNPINNED Chris@0: in Chris@0: { Chris@0: libname = libname, Chris@0: vcs = case vcs of Chris@0: "hg" => HG Chris@0: | "git" => GIT Chris@0: | "svn" => SVN Chris@0: | other => raise Fail ("Unknown version-control system \"" ^ Chris@0: other ^ "\""), Chris@0: source = case (url, service, owner, repo) of Chris@0: (SOME u, NONE, _, _) => URL_SOURCE u Chris@0: | (NONE, SOME ss, owner, repo) => Chris@0: SERVICE_SOURCE { service = ss, owner = owner, repo = repo } Chris@0: | _ => raise Fail ("Must have exactly one of service " ^ Chris@0: "or url string"), Chris@0: project_pin = project_pin, Chris@0: lock_pin = lock_pin, Chris@0: branch = case branch of Chris@0: NONE => DEFAULT_BRANCH Chris@0: | SOME b => Chris@0: case vcs of Chris@0: "svn" => raise Fail ("Branches not supported for " ^ Chris@0: "svn repositories; change " ^ Chris@0: "URL instead") Chris@0: | _ => BRANCH b Chris@0: } Chris@0: end Chris@0: Chris@0: fun load_userconfig () : userconfig = Chris@0: let val home = FileBits.homedir () Chris@0: val conf_json = Chris@0: JsonBits.load_json_from Chris@0: (OS.Path.joinDirFile { Chris@0: dir = home, Chris@0: file = RepointFilenames.user_config_file }) Chris@0: handle IO.Io _ => Json.OBJECT [] Chris@0: in Chris@0: { Chris@0: accounts = case JsonBits.lookup_optional conf_json ["accounts"] of Chris@0: NONE => [] Chris@0: | SOME (Json.OBJECT aa) => Chris@0: map (fn (k, (Json.STRING v)) => Chris@0: { service = k, login = v } Chris@0: | _ => raise Fail Chris@0: "String expected for account name") Chris@0: aa Chris@0: | _ => raise Fail "Array expected for accounts", Chris@0: providers = Provider.load_providers conf_json Chris@0: } Chris@0: end Chris@0: Chris@0: datatype pintype = Chris@0: NO_LOCKFILE | Chris@0: USE_LOCKFILE Chris@0: Chris@0: fun load_project (userconfig : userconfig) rootpath pintype : project = Chris@0: let val spec_file = FileBits.project_spec_path rootpath Chris@0: val lock_file = FileBits.project_lock_path rootpath Chris@0: val _ = if OS.FileSys.access (spec_file, [OS.FileSys.A_READ]) Chris@0: handle OS.SysErr _ => false Chris@0: then () Chris@0: else raise Fail ("Failed to open project spec file " ^ Chris@0: (RepointFilenames.project_file) ^ " in " ^ Chris@0: rootpath ^ Chris@0: ".\nPlease ensure the spec file is in the " ^ Chris@0: "project root and run this from there.") Chris@0: val spec_json = JsonBits.load_json_from spec_file Chris@0: val lock_json = if pintype = USE_LOCKFILE Chris@0: then JsonBits.load_json_from lock_file Chris@0: handle IO.Io _ => Json.OBJECT [] Chris@0: else Json.OBJECT [] Chris@0: val extdir = JsonBits.lookup_mandatory_string spec_json Chris@0: ["config", "extdir"] Chris@0: val spec_libs = JsonBits.lookup_optional spec_json [libobjname] Chris@0: val lock_libs = JsonBits.lookup_optional lock_json [libobjname] Chris@0: val providers = Provider.load_more_providers Chris@0: (#providers userconfig) spec_json Chris@0: val libnames = case spec_libs of Chris@0: NONE => [] Chris@0: | SOME (Json.OBJECT ll) => map (fn (k, v) => k) ll Chris@0: | _ => raise Fail "Object expected for libs" Chris@0: in Chris@0: { Chris@0: context = { Chris@0: rootpath = rootpath, Chris@0: extdir = extdir, Chris@0: providers = providers, Chris@0: accounts = #accounts userconfig Chris@0: }, Chris@0: libs = map (load_libspec spec_json lock_json) libnames Chris@0: } Chris@0: end Chris@0: Chris@0: fun save_lock_file rootpath locks = Chris@0: let val lock_file = FileBits.project_lock_path rootpath Chris@0: open Json Chris@0: val lock_json = Chris@0: OBJECT [ Chris@0: (libobjname, Chris@0: OBJECT (map (fn { libname, id_or_tag } => Chris@0: (libname, Chris@0: OBJECT [ ("pin", STRING id_or_tag) ])) Chris@0: locks)) Chris@0: ] Chris@0: in Chris@0: JsonBits.save_json_to lock_file lock_json Chris@0: end Chris@0: Chris@0: fun checkpoint_completion_file rootpath = Chris@0: let val completion_file = FileBits.project_completion_path rootpath Chris@0: val stream = TextIO.openOut completion_file Chris@0: in Chris@0: TextIO.closeOut stream Chris@0: end Chris@0: Chris@0: fun pad_to n str = Chris@0: if n <= String.size str then str Chris@0: else pad_to n (str ^ " ") Chris@0: Chris@0: fun hline_to 0 = "" Chris@0: | hline_to n = "-" ^ hline_to (n-1) Chris@0: Chris@0: val libname_width = 28 Chris@0: val libstate_width = 11 Chris@0: val localstate_width = 17 Chris@0: val notes_width = 5 Chris@0: val divider = " | " Chris@0: val clear_line = "\r" ^ pad_to 80 ""; Chris@0: Chris@0: fun print_status_header () = Chris@0: print (clear_line ^ "\n " ^ Chris@0: pad_to libname_width "Library" ^ divider ^ Chris@0: pad_to libstate_width "State" ^ divider ^ Chris@0: pad_to localstate_width "Local" ^ divider ^ Chris@0: "Notes" ^ "\n " ^ Chris@0: hline_to libname_width ^ "-+-" ^ Chris@0: hline_to libstate_width ^ "-+-" ^ Chris@0: hline_to localstate_width ^ "-+-" ^ Chris@0: hline_to notes_width ^ "\n") Chris@0: Chris@0: fun print_outcome_header () = Chris@0: print (clear_line ^ "\n " ^ Chris@0: pad_to libname_width "Library" ^ divider ^ Chris@0: pad_to libstate_width "Outcome" ^ divider ^ Chris@0: "Notes" ^ "\n " ^ Chris@0: hline_to libname_width ^ "-+-" ^ Chris@0: hline_to libstate_width ^ "-+-" ^ Chris@0: hline_to notes_width ^ "\n") Chris@0: Chris@0: fun print_status with_network (lib : libspec, status) = Chris@0: let val libstate_str = Chris@0: case status of Chris@0: OK (ABSENT, _) => "Absent" Chris@0: | OK (CORRECT, _) => if with_network then "Correct" else "Present" Chris@0: | OK (SUPERSEDED, _) => "Superseded" Chris@0: | OK (WRONG, _) => "Wrong" Chris@0: | ERROR _ => "Error" Chris@0: val localstate_str = Chris@0: case status of Chris@0: OK (_, MODIFIED) => "Modified" Chris@0: | OK (_, LOCK_MISMATCHED) => "Differs from Lock" Chris@0: | OK (_, CLEAN) => "Clean" Chris@0: | ERROR _ => "" Chris@0: val error_str = Chris@0: case status of Chris@0: ERROR e => e Chris@0: | _ => "" Chris@0: in Chris@0: print (" " ^ Chris@0: pad_to libname_width (#libname lib) ^ divider ^ Chris@0: pad_to libstate_width libstate_str ^ divider ^ Chris@0: pad_to localstate_width localstate_str ^ divider ^ Chris@0: error_str ^ "\n") Chris@0: end Chris@0: Chris@0: fun print_update_outcome (lib : libspec, outcome) = Chris@0: let val outcome_str = Chris@0: case outcome of Chris@0: OK id => "Ok" Chris@0: | ERROR e => "Failed" Chris@0: val error_str = Chris@0: case outcome of Chris@0: ERROR e => e Chris@0: | _ => "" Chris@0: in Chris@0: print (" " ^ Chris@0: pad_to libname_width (#libname lib) ^ divider ^ Chris@0: pad_to libstate_width outcome_str ^ divider ^ Chris@0: error_str ^ "\n") Chris@0: end Chris@0: Chris@0: fun vcs_name HG = ("Mercurial", "hg") Chris@0: | vcs_name GIT = ("Git", "git") Chris@0: | vcs_name SVN = ("Subversion", "svn") Chris@0: Chris@0: fun print_problem_summary context lines = Chris@0: let val failed_vcs = Chris@0: foldl (fn (({ vcs, ... } : libspec, ERROR _), acc) => vcs::acc Chris@0: | (_, acc) => acc) [] lines Chris@0: fun report_nonworking vcs error = Chris@0: print ((if error = "" then "" else error ^ "\n\n") ^ Chris@0: "Error: The project uses the " ^ (#1 (vcs_name vcs)) ^ Chris@0: " version control system, but its\n" ^ Chris@0: "executable program (" ^ (#2 (vcs_name vcs)) ^ Chris@0: ") does not appear to be installed in the program path\n\n") Chris@0: fun check_working [] checked = () Chris@0: | check_working (vcs::rest) checked = Chris@0: if List.exists (fn v => vcs = v) checked Chris@0: then check_working rest checked Chris@0: else Chris@0: case AnyLibControl.is_working context vcs of Chris@0: OK true => check_working rest checked Chris@0: | OK false => (report_nonworking vcs ""; Chris@0: check_working rest (vcs::checked)) Chris@0: | ERROR e => (report_nonworking vcs e; Chris@0: check_working rest (vcs::checked)) Chris@0: in Chris@0: print "\nError: Some operations failed\n\n"; Chris@0: check_working failed_vcs [] Chris@0: end Chris@0: Chris@0: fun act_and_print action print_header print_line context (libs : libspec list) = Chris@0: let val lines = map (fn lib => (lib, action lib)) libs Chris@0: val imperfect = List.exists (fn (_, ERROR _) => true | _ => false) lines Chris@0: val _ = print_header () Chris@0: in Chris@0: app print_line lines; Chris@0: if imperfect then print_problem_summary context lines else (); Chris@0: lines Chris@0: end Chris@0: Chris@0: fun return_code_for outcomes = Chris@0: foldl (fn ((_, result), acc) => Chris@0: case result of Chris@0: ERROR _ => OS.Process.failure Chris@0: | _ => acc) Chris@0: OS.Process.success Chris@0: outcomes Chris@0: Chris@0: fun status_of_project ({ context, libs } : project) = Chris@0: return_code_for (act_and_print (AnyLibControl.status context) Chris@0: print_status_header (print_status false) Chris@0: context libs) Chris@0: Chris@0: fun review_project ({ context, libs } : project) = Chris@0: return_code_for (act_and_print (AnyLibControl.review context) Chris@0: print_status_header (print_status true) Chris@0: context libs) Chris@0: Chris@0: fun lock_project ({ context, libs } : project) = Chris@0: let val _ = if FileBits.verbose () Chris@0: then print ("Scanning IDs for lock file...\n") Chris@0: else () Chris@0: val outcomes = map (fn lib => (lib, AnyLibControl.id_of context lib)) Chris@0: libs Chris@0: val locks = Chris@0: List.concat Chris@0: (map (fn (lib : libspec, result) => Chris@0: case result of Chris@0: ERROR _ => [] Chris@0: | OK id => [{ libname = #libname lib, Chris@0: id_or_tag = id }]) Chris@0: outcomes) Chris@0: val return_code = return_code_for outcomes Chris@0: val _ = print clear_line Chris@0: in Chris@0: if OS.Process.isSuccess return_code Chris@0: then save_lock_file (#rootpath context) locks Chris@0: else (); Chris@0: return_code Chris@0: end Chris@0: Chris@0: fun update_project (project as { context, libs }) = Chris@0: let val outcomes = act_and_print Chris@0: (AnyLibControl.update context) Chris@0: print_outcome_header print_update_outcome Chris@0: context libs Chris@0: val _ = if List.exists (fn (_, OK _) => true | _ => false) outcomes Chris@0: then lock_project project Chris@0: else OS.Process.success Chris@0: val return_code = return_code_for outcomes Chris@0: in Chris@0: if OS.Process.isSuccess return_code Chris@0: then checkpoint_completion_file (#rootpath context) Chris@0: else (); Chris@0: return_code Chris@0: end Chris@0: Chris@0: fun load_local_project pintype = Chris@0: let val userconfig = load_userconfig () Chris@0: val rootpath = OS.FileSys.getDir () Chris@0: in Chris@0: load_project userconfig rootpath pintype Chris@0: end Chris@0: Chris@0: fun with_local_project pintype f = Chris@0: let open OS.Process Chris@0: val return_code = Chris@0: f (load_local_project pintype) Chris@0: handle Fail msg => Chris@0: failure before print ("Error: " ^ msg) Chris@0: | JsonBits.Config msg => Chris@0: failure before print ("Error in configuration: " ^ msg) Chris@0: | e => Chris@0: failure before print ("Error: " ^ exnMessage e) Chris@0: val _ = print "\n"; Chris@0: in Chris@0: return_code Chris@0: end Chris@0: Chris@0: fun review () = with_local_project USE_LOCKFILE review_project Chris@0: fun status () = with_local_project USE_LOCKFILE status_of_project Chris@0: fun update () = with_local_project NO_LOCKFILE update_project Chris@0: fun lock () = with_local_project NO_LOCKFILE lock_project Chris@0: fun install () = with_local_project USE_LOCKFILE update_project Chris@0: Chris@0: fun version () = Chris@0: (print ("v" ^ repoint_version ^ "\n"); Chris@0: OS.Process.success) Chris@0: Chris@0: fun usage () = Chris@0: (print "\nRepoint "; Chris@0: version (); Chris@0: print ("\n A simple manager for third-party source code dependencies.\n" Chris@0: ^ " http://all-day-breakfast.com/repoint/\n\n" Chris@0: ^ "Usage:\n\n" Chris@0: ^ " repoint []\n\n" Chris@0: ^ "where is one of:\n\n" Chris@0: ^ " status print quick report on local status only, without using network\n" Chris@0: ^ " review check configured libraries against their providers, and report\n" Chris@0: ^ " install update configured libraries according to project specs and lock file\n" Chris@0: ^ " update update configured libraries and lock file according to project specs\n" Chris@0: ^ " lock rewrite lock file to match local library status\n" Chris@0: ^ " archive pack up project and all libraries into an archive file:\n" Chris@0: ^ " invoke as 'repoint archive targetfile.tar.gz --exclude unwanted.txt'\n" Chris@0: ^ " version print the Repoint version number and exit\n\n" Chris@0: ^ "and may include:\n\n" Chris@0: ^ " --directory \n" Chris@0: ^ " change to directory before doing anything; in particular,\n" Chris@0: ^ " expect to find project spec file in that directory\n\n"); Chris@0: OS.Process.failure) Chris@0: Chris@0: fun archive target args = Chris@0: case args of Chris@0: [] => Chris@0: with_local_project USE_LOCKFILE (Archive.archive (target, [])) Chris@0: | "--exclude"::xs => Chris@0: with_local_project USE_LOCKFILE (Archive.archive (target, xs)) Chris@0: | _ => usage () Chris@0: Chris@0: fun handleSystemArgs args = Chris@0: let fun handleSystemArgs' leftover args = Chris@0: case args of Chris@0: "--directory"::dir::rest => Chris@0: (OS.FileSys.chDir dir; Chris@0: handleSystemArgs' leftover rest) Chris@0: | arg::rest => Chris@0: handleSystemArgs' (leftover @ [arg]) rest Chris@0: | [] => leftover Chris@0: in Chris@0: OK (handleSystemArgs' [] args) Chris@0: handle e => ERROR (exnMessage e) Chris@0: end Chris@0: Chris@0: fun repoint args = Chris@0: case handleSystemArgs args of Chris@0: ERROR e => (print ("Error: " ^ e ^ "\n"); Chris@0: OS.Process.exit OS.Process.failure) Chris@0: | OK args => Chris@0: let val return_code = Chris@0: case args of Chris@0: ["review"] => review () Chris@0: | ["status"] => status () Chris@0: | ["install"] => install () Chris@0: | ["update"] => update () Chris@0: | ["lock"] => lock () Chris@0: | ["version"] => version () Chris@0: | "archive"::target::args => archive target args Chris@0: | arg::_ => (print ("Error: unknown argument \"" ^ arg ^ "\"\n"); Chris@0: usage ()) Chris@0: | _ => usage () Chris@0: in Chris@0: OS.Process.exit return_code Chris@0: end Chris@0: Chris@0: fun main () = Chris@0: repoint (CommandLine.arguments ())