Debian Codegraph @

extra/haxelib_src/src/haxelib/client/Main.hx

raw
1 /*
2 * Copyright (C)2005-2016 Haxe Foundation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22 package haxelib.client;
23
24 import haxelib.client.Util.*;
25 import haxe.crypto.Md5;
26 import haxe.*;
27 import haxe.ds.*;
28 import haxe.io.BytesOutput;
29 import haxe.io.Path;
30 import haxe.zip.*;
31 import sys.io.File;
32 import sys.FileSystem;
33 import sys.io.*;
34 import haxe.ds.Option;
35 import haxelib.client.Cli.ask;
36 import haxelib.client.FsUtils.*;
37 import haxelib.client.Vcs;
38
39 using StringTools;
40 using Lambda;
41 using haxelib.Data;
42
43 private enum CommandCategory {
44 Basic;
45 Information;
46 Development;
47 Miscellaneous;
48 Deprecated(msg:String);
49 }
50
51 class SiteProxy extends haxe.remoting.Proxy<haxelib.SiteApi> {
52 }
53
54 class ProgressOut extends haxe.io.Output {
55
56 var o : haxe.io.Output;
57 var cur : Int;
58 var curReadable : Float;
59 var startSize : Int;
60 var max : Null<Int>;
61 var maxReadable : Null<Float>;
62 var start : Float;
63
64 public function new(o, currentSize) {
65 this.o = o;
66 startSize = currentSize;
67 cur = currentSize;
68 start = Timer.stamp();
69 }
70
71 function report(n) {
72 cur += n;
73
74 var tag : String = ((max != null ? max : cur) / 1000000) > 1 ? "MB" : "KB";
75
76 curReadable = tag == "MB" ? cur / 1000000 : cur / 1000;
77 curReadable = Math.round( curReadable * 100 ) / 100; // 12.34 precision.
78
79 if( max == null )
80 Sys.print('${curReadable} ${tag}\r');
81 else {
82 maxReadable = tag == "MB" ? max / 1000000 : max / 1000;
83 maxReadable = Math.round( maxReadable * 100 ) / 100; // 12.34 precision.
84
85 Sys.print('${curReadable}${tag} / ${maxReadable}${tag} (${Std.int((cur*100.0)/max)}%)\r');
86 }
87 }
88
89 public override function writeByte(c) {
90 o.writeByte(c);
91 report(1);
92 }
93
94 public override function writeBytes(s,p,l) {
95 var r = o.writeBytes(s,p,l);
96 report(r);
97 return r;
98 }
99
100 public override function close() {
101 super.close();
102 o.close();
103
104 var time = Timer.stamp() - start;
105 var downloadedBytes = cur - startSize;
106 var speed = (downloadedBytes / time) / 1000;
107 time = Std.int(time * 10) / 10;
108 speed = Std.int(speed * 10) / 10;
109
110 var tag : String = (downloadedBytes / 1000000) > 1 ? "MB" : "KB";
111 var readableBytes : Float = (tag == "MB") ? downloadedBytes / 1000000 : downloadedBytes / 1000;
112 readableBytes = Math.round( readableBytes * 100 ) / 100; // 12.34 precision.
113
114 Sys.println('Download complete: ${readableBytes}${tag} in ${time}s (${speed}KB/s)');
115 }
116
117 public override function prepare(m) {
118 max = m + startSize;
119 }
120
121 }
122
123 class ProgressIn extends haxe.io.Input {
124
125 var i : haxe.io.Input;
126 var pos : Int;
127 var tot : Int;
128
129 public function new( i, tot ) {
130 this.i = i;
131 this.pos = 0;
132 this.tot = tot;
133 }
134
135 public override function readByte() {
136 var c = i.readByte();
137 report(1);
138 return c;
139 }
140
141 public override function readBytes(buf,pos,len) {
142 var k = i.readBytes(buf,pos,len);
143 report(k);
144 return k;
145 }
146
147 function report( nbytes : Int ) {
148 pos += nbytes;
149 Sys.print( Std.int((pos * 100.0) / tot) + "%\r" );
150 }
151
152 }
153
154 class Main {
155 static inline var HAXELIB_LIBNAME = "haxelib";
156
157 static var VERSION:SemVer = SemVer.ofString(getHaxelibVersion());
158 static var VERSION_LONG:String = getHaxelibVersionLong();
159 static var REPNAME = "lib";
160 static var REPODIR = ".haxelib";
161 static var SERVER = {
162 protocol : "https",
163 host : "lib.haxe.org",
164 port : 443,
165 dir : "",
166 url : "index.n",
167 apiVersion : "3.0",
168 noSsl : false
169 };
170 static var IS_WINDOWS = (Sys.systemName() == "Windows");
171
172 var argcur : Int;
173 var args : Array<String>;
174 var commands : List<{ name : String, doc : String, f : Void -> Void, net : Bool, cat : CommandCategory }>;
175 var siteUrl : String;
176 var site : SiteProxy;
177 var isHaxelibRun : Bool;
178 var alreadyUpdatedVcsDependencies:Map<String,String> = new Map<String,String>();
179
180 function new() {
181 args = Sys.args();
182 isHaxelibRun = (Sys.getEnv("HAXELIB_RUN_NAME") == HAXELIB_LIBNAME);
183
184 if (isHaxelibRun)
185 Sys.setCwd(args.pop());
186
187 commands = new List();
188 addCommand("install", install, "install a given library, or all libraries from a hxml file", Basic);
189 addCommand("update", update, "update a single library (if given) or all installed libraries", Basic);
190 addCommand("remove", remove, "remove a given library/version", Basic, false);
191 addCommand("list", list, "list all installed libraries", Basic, false);
192 addCommand("set", set, "set the current version for a library", Basic, false);
193
194 addCommand("search", search, "list libraries matching a word", Information);
195 addCommand("info", info, "list information on a given library", Information);
196 addCommand("user", user, "list information on a given user", Information);
197 addCommand("config", config, "print the repository path", Information, false);
198 addCommand("path", path, "give paths to libraries' sources and necessary build definitions", Information, false);
199 addCommand("libpath", libpath, "returns the root path of a library", Information, false);
200 addCommand("version", version, "print the currently used haxelib version", Information, false);
201 addCommand("help", usage, "display this list of options", Information, false);
202
203 addCommand("submit", submit, "submit or update a library package", Development);
204 addCommand("register", register, "register a new user", Development);
205 addCommand("dev", dev, "set the development directory for a given library", Development, false);
206 //TODO: generate command about VCS by Vcs.getAll()
207 addCommand("git", vcs.bind(VcsID.Git), "use Git repository as library", Development);
208 addCommand("hg", vcs.bind(VcsID.Hg), "use Mercurial (hg) repository as library", Development);
209
210 addCommand("setup", setup, "set the haxelib repository path", Miscellaneous, false);
211 addCommand("newrepo", newRepo, "create a new local repository", Miscellaneous, false);
212 addCommand("deleterepo", deleteRepo, "delete the local repository", Miscellaneous, false);
213 addCommand("convertxml", convertXml, "convert haxelib.xml file to haxelib.json", Miscellaneous);
214 addCommand("run", run, "run the specified library with parameters", Miscellaneous, false);
215 addCommand("proxy", proxy, "setup the Http proxy", Miscellaneous);
216
217 // deprecated commands
218 addCommand("local", local, "install the specified package locally", Deprecated("Use `haxelib install <file>` instead"), false);
219 addCommand("selfupdate", updateSelf, "update haxelib itself", Deprecated('Use `haxelib --global update $HAXELIB_LIBNAME` instead'));
220
221 initSite();
222 }
223
224 function retry<R>(func:Void -> R, numTries:Int = 3) {
225 var hasRetried = false;
226
227 while (numTries-- > 0) {
228 try {
229 var result = func();
230
231 if (hasRetried) print("retry sucessful");
232
233 return result;
234 } catch (e:Dynamic) {
235 if ( e == "Blocked") {
236 print("Failed. Triggering retry due to HTTP timeout");
237 hasRetried = true;
238 }
239 else {
240 throw 'Failed with error: $e';
241 }
242 }
243 }
244 throw 'Failed due to HTTP timeout after multiple retries';
245 }
246
247 function checkUpdate() {
248 var latest = try retry(site.getLatestVersion.bind(HAXELIB_LIBNAME)) catch (_:Dynamic) null;
249 if (latest != null && latest > VERSION)
250 print('\nA new version ($latest) of haxelib is available.\nDo `haxelib --global update $HAXELIB_LIBNAME` to get the latest version.\n');
251 }
252
253 function initSite() {
254 siteUrl = SERVER.protocol + "://" + SERVER.host + ":" + SERVER.port + "/" + SERVER.dir;
255 var remotingUrl = siteUrl + "api/" + SERVER.apiVersion + "/" + SERVER.url;
256 site = new SiteProxy(haxe.remoting.HttpConnection.urlConnect(remotingUrl).resolve("api"));
257 }
258
259 function param( name, ?passwd ) {
260 if( args.length > argcur )
261 return args[argcur++];
262 Sys.print(name+" : ");
263 if( passwd ) {
264 var s = new StringBuf();
265 do switch Sys.getChar(false) {
266 case 10, 13: break;
267 case 0: // ignore (windows bug)
268 case c: s.addChar(c);
269 }
270 while (true);
271 print("");
272 return s.toString();
273 }
274 return Sys.stdin().readLine();
275 }
276
277 function paramOpt() {
278 if( args.length > argcur )
279 return args[argcur++];
280 return null;
281 }
282
283 function addCommand( name, f, doc, cat, ?net = true ) {
284 commands.add({ name : name, doc : doc, f : f, net : net, cat : cat });
285 }
286
287 function version() {
288 var params = paramOpt();
289 if ( params == null )
290 print(VERSION_LONG);
291 else {
292 Sys.stderr().writeString('no parameters expected, got: ${params}\n');
293 Sys.exit(1);
294 }
295 }
296
297 function usage() {
298 var cats = [];
299 var maxLength = Lambda.fold(Reflect.fields(ABOUT_SETTINGS), function(opt, max) {
300 var fullOption = '--' + ~/([A-Z])/g.replace(opt, "-$1").toLowerCase();
301 var len = fullOption.length;
302 return len > max ? len : max;
303 }, 0);
304
305 for( c in commands ) {
306 if (c.name.length > maxLength) maxLength = c.name.length;
307 if (c.cat.match(Deprecated(_))) continue;
308 var i = c.cat.getIndex();
309 if (cats[i] == null) cats[i] = [c];
310 else cats[i].push(c);
311 }
312
313 print('Haxe Library Manager $VERSION - (c)2006-2019 Haxe Foundation');
314 print(" Usage: haxelib [command] [options]");
315
316 for (cat in cats) {
317 print(" " + cat[0].cat.getName());
318 for (c in cat) {
319 print(" " + StringTools.rpad(c.name, " ", maxLength) + ": " +c.doc);
320 }
321 }
322
323 print(" Available switches");
324 for (f in Reflect.fields(ABOUT_SETTINGS)) {
325 var option = ~/([A-Z])/g.replace(f, "-$1").toLowerCase().rpad(' ', maxLength-2);
326 print(' --' + option + ": " + Reflect.field(ABOUT_SETTINGS, f));
327 }
328 }
329 static var ABOUT_SETTINGS = {
330 global : "force global repo if a local one exists",
331 debug : "run in debug mode, imply not --quiet",
332 quiet : "print less messages, imply not --debug",
333 flat : "do not use --recursive cloning for git",
334 always : "answer all questions with yes",
335 never : "answer all questions with no",
336 system : "run bundled haxelib version instead of latest update",
337 skipDependencies : "do not install dependencies",
338 }
339
340 var settings: {
341 debug : Bool,
342 quiet : Bool,
343 flat : Bool,
344 always : Bool,
345 never : Bool,
346 global : Bool,
347 system : Bool,
348 skipDependencies : Bool,
349 };
350 function process() {
351 argcur = 0;
352 var rest = [];
353 settings = {
354 debug: false,
355 quiet: false,
356 always: false,
357 never: false,
358 flat: false,
359 global: false,
360 system: false,
361 skipDependencies: false,
362 };
363
364 function parseSwitch(s:String) {
365 return
366 if (s.startsWith('--'))
367 Some(s.substr(2));
368 else if (s.startsWith('-'))
369 Some(s.substr(1));
370 else
371 None;
372 }
373
374 var remoteIsSet = false;
375 function setupRemote(path:String) {
376 var r = ~/^(?:(https?):\/\/)?([^:\/]+)(?::([0-9]+))?\/?(.*)$/;
377 if( !r.match(path) )
378 throw "Invalid repository format '"+path+"'";
379 SERVER.protocol = switch (r.matched(1)) {
380 case null:
381 SERVER.noSsl ? "http" : "https";
382 case protocol:
383 protocol;
384 }
385 SERVER.host = r.matched(2);
386 SERVER.port = switch (r.matched(3)) {
387 case null:
388 switch (SERVER.protocol) {
389 case "https": 443;
390 case "http": 80;
391 case protocol: throw 'unknown default port for $protocol';
392 }
393 case portStr:
394 Std.parseInt(portStr);
395 }
396 SERVER.dir = r.matched(4);
397 if (SERVER.dir.length > 0 && !SERVER.dir.endsWith("/")) SERVER.dir += "/";
398 initSite();
399 remoteIsSet = true;
400 }
401
402 while ( argcur < args.length) {
403 var a = args[argcur++];
404 switch( a ) {
405 case '-cwd':
406 var dir = args[argcur++];
407 if (dir == null) {
408 print("Missing directory argument for -cwd");
409 Sys.exit(1);
410 }
411 try {
412 Sys.setCwd(dir);
413 } catch (e:String) {
414 if (e == "std@set_cwd") {
415 print("Directory " + dir + " unavailable");
416 Sys.exit(1);
417 }
418 rethrow(e);
419 }
420 case "-notimeout":
421 haxe.remoting.HttpConnection.TIMEOUT = 0;
422 case "-R":
423 setupRemote(args[argcur++]);
424 case "--debug":
425 settings.debug = true;
426 settings.quiet = false;
427 case "--quiet":
428 settings.debug = false;
429 settings.quiet = true;
430 case "--skip-dependencies":
431 settings.skipDependencies = true;
432 case parseSwitch(_) => Some(s) if (Reflect.hasField(settings, s)):
433 //if (!Reflect.hasField(settings, s)) {
434 //print('unknown switch $a');
435 //Sys.exit(1);
436 //}
437 Reflect.setField(settings, s, true);
438 case 'run':
439 rest = rest.concat(args.slice(argcur - 1));
440 break;
441 default:
442 rest.push(a);
443 }
444 }
445 if(!remoteIsSet) {
446 switch(Sys.getEnv("HAXELIB_REMOTE")) {
447 case null:
448 case path: setupRemote(path);
449 }
450 }
451
452 if (!isHaxelibRun && !settings.system) {
453 var rep = try getGlobalRepository() catch (_:Dynamic) null;
454 if (rep != null && FileSystem.exists(rep + HAXELIB_LIBNAME)) {
455 argcur = 0; // send all arguments
456 try {
457 doRun(rep, HAXELIB_LIBNAME, null);
458 return;
459 } catch(e:Dynamic) {
460 Sys.println('Warning: failed to run updated haxelib: $e');
461 Sys.println('Warning: resorting to system haxelib...');
462 }
463 }
464 }
465
466 Cli.defaultAnswer =
467 switch [settings.always, settings.never] {
468 case [true, true]:
469 print('--always and --never are mutually exclusive');
470 Sys.exit(1);
471 null;
472 case [true, _]: true;
473 case [_, true]: false;
474 default: null;
475 }
476
477 argcur = 0;
478 args = rest;
479
480 var cmd = args[argcur++];
481 if( cmd == null ) {
482 usage();
483 Sys.exit(1);
484 }
485 if (cmd == "upgrade") cmd = "update"; // TODO: maybe we should have some alias system
486 for( c in commands )
487 if( c.name == cmd ) {
488 switch (c.cat) {
489 case Deprecated(message):
490 Sys.println('Warning: Command `$cmd` is deprecated and will be removed in future. $message.');
491 default:
492 }
493 try {
494 if( c.net ) {
495 loadProxy();
496 checkUpdate();
497 }
498 c.f();
499 } catch( e : Dynamic ) {
500 if( e == "std@host_resolve" ) {
501 print("Host "+SERVER.host+" was not found");
502 print("Please ensure that your internet connection is on");
503 print("If you don't have an internet connection or if you are behing a proxy");
504 print("please download manually the file from https://lib.haxe.org/files/3.0/");
505 print("and run 'haxelib local <file>' to install the Library.");
506 print("You can also setup the proxy with 'haxelib proxy'.");
507 print(haxe.CallStack.toString(haxe.CallStack.exceptionStack()));
508 Sys.exit(1);
509 }
510 if( e == "Blocked" ) {
511 print("Http connection timeout. Try running haxelib -notimeout <command> to disable timeout");
512 Sys.exit(1);
513 }
514 if( e == "std@get_cwd" ) {
515 print("Error: Current working directory is unavailable");
516 Sys.exit(1);
517 }
518 if( settings.debug )
519 rethrow(e);
520 print("Error: " + Std.string(e));
521 Sys.exit(1);
522 }
523 return;
524 }
525 print("Unknown command "+cmd);
526 usage();
527 Sys.exit(1);
528 }
529
530 inline function createHttpRequest(url:String):Http {
531 var req = new Http(url);
532 req.addHeader("User-Agent", 'haxelib $VERSION_LONG');
533 if (haxe.remoting.HttpConnection.TIMEOUT == 0)
534 req.cnxTimeout = 0;
535 return req;
536 }
537
538 // ---- COMMANDS --------------------
539
540 function search() {
541 var word = param("Search word");
542 var l = retry(site.search.bind(word));
543 for( s in l )
544 print(s.name);
545 print(l.length+" libraries found");
546 }
547
548 function info() {
549 var prj = param("Library name");
550 var inf = retry(site.infos.bind(prj));
551 print("Name: "+inf.name);
552 print("Tags: "+inf.tags.join(", "));
553 print("Desc: "+inf.desc);
554 print("Website: "+inf.website);
555 print("License: "+inf.license);
556 print("Owner: "+inf.owner);
557 print("Version: "+inf.getLatest());
558 print("Releases: ");
559 if( inf.versions.length == 0 )
560 print(" (no version released yet)");
561 for( v in inf.versions )
562 print(" "+v.date+" "+v.name+" : "+v.comments);
563 }
564
565 function user() {
566 var uname = param("User name");
567 var inf = retry(site.user.bind(uname));
568 print("Id: "+inf.name);
569 print("Name: "+inf.fullname);
570 print("Mail: "+inf.email);
571 print("Libraries: ");
572 if( inf.projects.length == 0 )
573 print(" (no libraries)");
574 for( p in inf.projects )
575 print(" "+p);
576 }
577
578 function register() {
579 doRegister(param("User"));
580 print("Registration successful");
581 }
582
583 function doRegister(name) {
584 var email = param("Email");
585 var fullname = param("Fullname");
586 var pass = param("Password",true);
587 var pass2 = param("Confirm",true);
588 if( pass != pass2 )
589 throw "Password does not match";
590 pass = Md5.encode(pass);
591 retry(site.register.bind(name,pass,email,fullname));
592 return pass;
593 }
594
595 function zipDirectory(root:String):List<Entry> {
596 var ret = new List<Entry>();
597 function seek(dir:String) {
598 for (name in FileSystem.readDirectory(dir)) if (!name.startsWith('.')) {
599 var full = '$dir/$name';
600 if (FileSystem.isDirectory(full)) seek(full);
601 else {
602 var blob = File.getBytes(full);
603 var entry:Entry = {
604 fileName: full.substr(root.length+1),
605 fileSize : blob.length,
606 fileTime : FileSystem.stat(full).mtime,
607 compressed : false,
608 dataSize : blob.length,
609 data : blob,
610 crc32: haxe.crypto.Crc32.make(blob),
611 };
612 Tools.compress(entry, 9);
613 ret.push(entry);
614 }
615 }
616 }
617 seek(root);
618 return ret;
619 }
620
621 function submit() {
622 var file = param("Package");
623
624 var data, zip;
625 if (FileSystem.isDirectory(file)) {
626 zip = zipDirectory(file);
627 var out = new BytesOutput();
628 new Writer(out).write(zip);
629 data = out.getBytes();
630 } else {
631 data = File.getBytes(file);
632 zip = Reader.readZip(new haxe.io.BytesInput(data));
633 }
634
635 var infos = Data.readInfos(zip,true);
636 Data.checkClassPath(zip, infos);
637 Data.checkDocumentation(zip, infos);
638
639 var user:String = infos.contributors[0];
640
641 if (infos.contributors.length > 1)
642 do {
643 print("Which of these users are you: " + infos.contributors);
644 user = param("User");
645 } while ( infos.contributors.indexOf(user) == -1 );
646
647 var password;
648 if( retry(site.isNewUser.bind(user)) ) {
649 print("This is your first submission as '"+user+"'");
650 print("Please enter the following information for registration");
651 password = doRegister(user);
652 } else {
653 password = readPassword(user);
654 }
655 retry(site.checkDeveloper.bind(infos.name,user));
656
657 // check dependencies validity
658 for( d in infos.dependencies ) {
659 var infos = retry(site.infos.bind(d.name));
660 if( d.version == "" )
661 continue;
662 var found = false;
663 for( v in infos.versions )
664 if( v.name == d.version ) {
665 found = true;
666 break;
667 }
668 if( !found )
669 throw "Library " + d.name + " does not have version " + d.version;
670 }
671
672 // check if this version already exists
673
674 var sinfos = try retry(site.infos.bind(infos.name)) catch( _ : Dynamic ) null;
675 if( sinfos != null )
676 for( v in sinfos.versions )
677 if( v.name == infos.version && !ask("You're about to overwrite existing version '"+v.name+"', please confirm") )
678 throw "Aborted";
679
680 // query a submit id that will identify the file
681 var id = retry(site.getSubmitId.bind());
682
683 // directly send the file data over Http
684 var h = createHttpRequest(SERVER.protocol+"://"+SERVER.host+":"+SERVER.port+"/"+SERVER.url);
685 h.onError = function(e) throw e;
686 h.onData = print;
687
688 var inp = if ( settings.quiet == false )
689 new ProgressIn(new haxe.io.BytesInput(data),data.length);
690 else
691 new haxe.io.BytesInput(data);
692
693 h.fileTransfer("file", id, inp, data.length);
694 print("Sending data.... ");
695 h.request(true);
696
697 // processing might take some time, make sure we wait
698 print("Processing file.... ");
699 if (haxe.remoting.HttpConnection.TIMEOUT != 0) // don't ignore -notimeout
700 haxe.remoting.HttpConnection.TIMEOUT = 1000;
701 // ask the server to register the sent file
702 var msg = retry(site.processSubmit.bind(id,user,password));
703 print(msg);
704 }
705
706 function readPassword(user:String, prompt = "Password"):String {
707 var password = Md5.encode(param(prompt,true));
708 var attempts = 5;
709 while (!retry(site.checkPassword.bind(user, password))) {
710 print('Invalid password for $user');
711 if (--attempts == 0)
712 throw 'Failed to input correct password';
713 password = Md5.encode(param('$prompt ($attempts more attempt${attempts == 1 ? "" : "s"})', true));
714 }
715 return password;
716 }
717
718 function install() {
719 var rep = getRepository();
720
721 var prj = param("Library name or hxml file:");
722
723 // No library given, install libraries listed in *.hxml in given directory
724 if( prj == "all") {
725 installFromAllHxml(rep);
726 return;
727 }
728
729 if( sys.FileSystem.exists(prj) && !sys.FileSystem.isDirectory(prj) ) {
730 // *.hxml provided, install all libraries/versions in this hxml file
731 if( prj.endsWith(".hxml") ) {
732 installFromHxml(rep, prj);
733 return;
734 }
735 // *.zip provided, install zip as haxe library
736 if (prj.endsWith(".zip")) {
737 doInstallFile(rep, prj, true, true);
738 return;
739 }
740
741 if ( prj.endsWith("haxelib.json") )
742 {
743 installFromHaxelibJson( rep, prj);
744 return;
745 }
746 }
747
748 // Name provided that wasn't a local hxml or zip, so try to install it from server
749 var inf = retry(site.infos.bind(prj));
750 var reqversion = paramOpt();
751 var version = getVersion(inf, reqversion);
752 doInstall(rep,inf.name,version,version == inf.getLatest());
753 }
754
755 function getVersion( inf:ProjectInfos, ?reqversion:String ) {
756 if( inf.versions.length == 0 )
757 throw "The library "+inf.name+" has not yet released a version";
758 var version = if( reqversion != null ) reqversion else inf.getLatest();
759 var found = false;
760 for( v in inf.versions )
761 if( v.name == version ) {
762 found = true;
763 break;
764 }
765 if( !found )
766 throw "No such version "+version+" for library "+inf.name;
767
768 return version;
769 }
770
771 function installFromHxml( rep:String, path:String ) {
772 var targets = [
773 '-java ' => 'hxjava',
774 '-cpp ' => 'hxcpp',
775 '-cs ' => 'hxcs',
776 ];
777 var libsToInstall = new Map<String, {name:String,version:String,type:String,url:String,branch:String,subDir:String}>();
778
779 function processHxml(path) {
780 var hxml = normalizeHxml(sys.io.File.getContent(path));
781 var lines = hxml.split("\n");
782 for (l in lines) {
783 l = l.trim();
784
785 for (target in targets.keys())
786 if (l.startsWith(target)) {
787 var lib = targets[target];
788 if (!libsToInstall.exists(lib))
789 libsToInstall[lib] = { name: lib, version: null, type:"haxelib", url: null, branch: null, subDir: null }
790 }
791
792 var libraryFlagEReg = ~/^(-lib|-L|--library)\b/;
793 if (libraryFlagEReg.match(l))
794 {
795 var key = libraryFlagEReg.matchedRight().trim();
796 var parts = ~/:/.split(key);
797 var libName = parts[0];
798 var libVersion:String = null;
799 var branch:String = null;
800 var url:String = null;
801 var subDir:String = null;
802 var type:String;
803
804 if ( parts.length > 1 )
805 {
806 if ( parts[1].startsWith("git:") )
807 {
808
809 type = "git";
810 var urlParts = parts[1].substr(4).split("#");
811 url = urlParts[0];
812 branch = urlParts.length > 1 ? urlParts[1] : null;
813 }
814 else
815 {
816 type = "haxelib";
817 libVersion = parts[1];
818 }
819 }
820 else
821 {
822 type = "haxelib";
823 }
824
825 switch libsToInstall[key] {
826 case null, { version: null } :
827 libsToInstall.set(key, { name:libName, version:libVersion, type: type, url: url, subDir: subDir, branch: branch } );
828 default:
829 }
830 }
831
832 if (l.endsWith(".hxml"))
833 processHxml(l);
834 }
835 }
836 processHxml(path);
837
838 if (Lambda.empty(libsToInstall))
839 return;
840
841 // Check the version numbers are all good
842 // TODO: can we collapse this into a single API call? It's getting too slow otherwise.
843 print("Loading info about the required libraries");
844 for (l in libsToInstall)
845 {
846 if ( l.type == "git" )
847 {
848 // Do not check git repository infos
849 continue;
850 }
851 var inf = retry(site.infos.bind(l.name));
852 l.version = getVersion(inf, l.version);
853 }
854
855 // Print a list with all the info
856 print("Haxelib is going to install these libraries:");
857 for (l in libsToInstall) {
858 var vString = (l.version == null) ? "" : " - " + l.version;
859 print(" " + l.name + vString);
860 }
861
862 // Install if they confirm
863 if (ask("Continue?")) {
864 for (l in libsToInstall) {
865 if ( l.type == "haxelib" )
866 doInstall(rep, l.name, l.version, true);
867 else if ( l.type == "git" )
868 useVcs(VcsID.Git, function(vcs) doVcsInstall(rep, vcs, l.name, l.url, l.branch, l.subDir, l.version));
869 else if ( l.type == "hg" )
870 useVcs(VcsID.Hg, function(vcs) doVcsInstall(rep, vcs, l.name, l.url, l.branch, l.subDir, l.version));
871 }
872 }
873 }
874
875 function installFromHaxelibJson( rep:String, path:String )
876 {
877 doInstallDependencies(rep, Data.readData(File.getContent(path), false).dependencies);
878 }
879
880 function installFromAllHxml(rep:String) {
881 var cwd = Sys.getCwd();
882 var hxmlFiles = sys.FileSystem.readDirectory(cwd).filter(function (f) return f.endsWith(".hxml"));
883 if (hxmlFiles.length > 0) {
884 for (file in hxmlFiles) {
885 print('Installing all libraries from $file:');
886 installFromHxml(rep, cwd + file);
887 }
888 } else {
889 print("No hxml files found in the current directory.");
890 }
891 }
892
893 // strip comments, trim whitespace from each line and remove empty lines
894 function normalizeHxml(hxmlContents: String) {
895 return ~/\r?\n/g.split(hxmlContents).map(StringTools.trim).filter(function(line) {
896 return line != "" && !line.startsWith("#");
897 }).join('\n');
898 }
899
900 // maxRedirect set to 20, which is most browsers' default value according to https://stackoverflow.com/a/36041063/267998
901 function download(fileUrl:String, outPath:String, maxRedirect = 20):Void {
902 var out = try File.append(outPath,true) catch (e:Dynamic) throw 'Failed to write to $outPath: $e';
903 out.seek(0, SeekEnd);
904
905 var h = createHttpRequest(fileUrl);
906
907 var currentSize = out.tell();
908 if (currentSize > 0)
909 h.addHeader("range", "bytes="+currentSize + "-");
910
911 var progress = if (settings != null && settings.quiet == false )
912 new ProgressOut(out, currentSize);
913 else
914 out;
915
916 var httpStatus = -1;
917 var redirectedLocation = null;
918 h.onStatus = function(status) {
919 httpStatus = status;
920 switch (httpStatus) {
921 case 301, 302, 307, 308:
922 switch (h.responseHeaders.get("Location")) {
923 case null:
924 throw 'Request to $fileUrl responded with $httpStatus, ${h.responseHeaders}';
925 case location:
926 redirectedLocation = location;
927 }
928 default:
929 // TODO?
930 }
931 };
932 h.onError = function(e) {
933 progress.close();
934
935 switch(httpStatus) {
936 case 416:
937 // 416 Requested Range Not Satisfiable, which means that we probably have a fully downloaded file already
938 // if we reached onError, because of 416 status code, it's probably okay and we should try unzipping the file
939 default:
940 FileSystem.deleteFile(outPath);
941 throw e;
942 }
943 };
944 h.customRequest(false, progress);
945
946 if (redirectedLocation != null) {
947 FileSystem.deleteFile(outPath);
948
949 if (maxRedirect > 0) {
950 download(redirectedLocation, outPath, maxRedirect - 1);
951 } else {
952 throw "Too many redirects.";
953 }
954 }
955 }
956
957 function doInstall( rep, project, version, setcurrent ) {
958 // check if exists already
959 if( FileSystem.exists(Path.join([rep, Data.safe(project), Data.safe(version)])) ) {
960 print("You already have "+project+" version "+version+" installed");
961 setCurrent(rep,project,version,true);
962 return;
963 }
964
965 // download to temporary file
966 var filename = Data.fileName(project,version);
967 var filepath = Path.join([rep, filename]);
968
969 print("Downloading "+filename+"...");
970
971 var maxRetry = 3;
972 var fileUrl = Path.join([siteUrl, Data.REPOSITORY, filename]);
973 for (i in 0...maxRetry) {
974 try {
975 download(fileUrl, filepath);
976 break;
977 } catch (e:Dynamic) {
978 print('Failed to download ${fileUrl}. (${i+1}/${maxRetry})\n${e}');
979 Sys.sleep(1);
980 }
981 }
982
983 doInstallFile(rep, filepath, setcurrent);
984 try {
985 retry(site.postInstall.bind(project, version));
986 } catch (e:Dynamic) {}
987 }
988
989 function doInstallFile(rep,filepath,setcurrent,nodelete = false) {
990 // read zip content
991 var f = File.read(filepath,true);
992 var zip = try {
993 Reader.readZip(f);
994 } catch (e:Dynamic) {
995 f.close();
996 // file is corrupted, remove it
997 if (!nodelete)
998 FileSystem.deleteFile(filepath);
999 rethrow(e);
1000 }
1001 f.close();
1002 var infos = Data.readInfos(zip,false);
1003 print('Installing ${infos.name}...');
1004 // create directories
1005 var pdir = rep + Data.safe(infos.name);
1006 safeDir(pdir);
1007 pdir += "/";
1008 var target = pdir + Data.safe(infos.version);
1009 safeDir(target);
1010 target += "/";
1011
1012 // locate haxelib.json base path
1013 var basepath = Data.locateBasePath(zip);
1014
1015 // unzip content
1016 var entries = [for (entry in zip) if (entry.fileName.startsWith(basepath)) entry];
1017 var total = entries.length;
1018 for (i in 0...total) {
1019 var zipfile = entries[i];
1020 var n = zipfile.fileName;
1021 // remove basepath
1022 n = n.substr(basepath.length,n.length-basepath.length);
1023 if( n.charAt(0) == "/" || n.charAt(0) == "\\" || n.split("..").length > 1 )
1024 throw "Invalid filename : "+n;
1025
1026 if (settings.debug) {
1027 var percent = Std.int((i / total) * 100);
1028 Sys.print('${i + 1}/$total ($percent%)\r');
1029 }
1030
1031 var dirs = ~/[\/\\]/g.split(n);
1032 var path = "";
1033 var file = dirs.pop();
1034 for( d in dirs ) {
1035 path += d;
1036 safeDir(target+path);
1037 path += "/";
1038 }
1039 if( file == "" ) {
1040 if( path != "" && settings.debug ) print(" Created "+path);
1041 continue; // was just a directory
1042 }
1043 path += file;
1044 if (settings.debug)
1045 print(" Install "+path);
1046 var data = Reader.unzip(zipfile);
1047 File.saveBytes(target+path,data);
1048 }
1049
1050 // set current version
1051 if( setcurrent || !FileSystem.exists(pdir+".current") ) {
1052 File.saveContent(pdir + ".current", infos.version);
1053 print(" Current version is now "+infos.version);
1054 }
1055
1056 // end
1057 if( !nodelete )
1058 FileSystem.deleteFile(filepath);
1059 print("Done");
1060
1061 // process dependencies
1062 doInstallDependencies(rep, infos.dependencies);
1063
1064 return infos;
1065 }
1066
1067 function doInstallDependencies( rep:String, dependencies:Array<Dependency> ) {
1068 if( settings.skipDependencies ) return;
1069
1070 for( d in dependencies ) {
1071 if( d.version == "" ) {
1072 var pdir = rep + Data.safe(d.name);
1073 var dev = try getDev(pdir) catch (_:Dynamic) null;
1074
1075 if (dev != null) { // no version specified and dev set, no need to install dependency
1076 continue;
1077 }
1078 }
1079
1080 if( d.version == "" && d.type == DependencyType.Haxelib )
1081 d.version = retry(site.getLatestVersion.bind(d.name));
1082 print("Installing dependency "+d.name+" "+d.version);
1083
1084 switch d.type {
1085 case Haxelib:
1086 var info = retry(site.infos.bind(d.name));
1087 doInstall(rep, info.name, d.version, false);
1088 case Git:
1089 useVcs(VcsID.Git, function(vcs) doVcsInstall(rep, vcs, d.name, d.url, d.branch, d.subDir, d.version));
1090 case Mercurial:
1091 useVcs(VcsID.Hg, function(vcs) doVcsInstall(rep, vcs, d.name, d.url, d.branch, d.subDir, d.version));
1092 }
1093 }
1094 }
1095
1096 static public function getHomePath():String{
1097 var home:String = null;
1098 if (IS_WINDOWS) {
1099 home = Sys.getEnv("USERPROFILE");
1100 if (home == null) {
1101 var drive = Sys.getEnv("HOMEDRIVE");
1102 var path = Sys.getEnv("HOMEPATH");
1103 if (drive != null && path != null)
1104 home = drive + path;
1105 }
1106 if (home == null)
1107 throw "Could not determine home path. Please ensure that USERPROFILE or HOMEDRIVE+HOMEPATH environment variables are set.";
1108 } else {
1109 home = Sys.getEnv("HOME");
1110 if (home == null)
1111 throw "Could not determine home path. Please ensure that HOME environment variable is set.";
1112 }
1113 return home;
1114 }
1115
1116 static public function getConfigFile():String {
1117 return Path.addTrailingSlash( getHomePath() ) + ".haxelib";
1118 }
1119
1120 function getGlobalRepositoryPath(create = false):String {
1121 // first check the env var
1122 var rep = Sys.getEnv("HAXELIB_PATH");
1123 if (rep != null)
1124 return rep.trim();
1125
1126 // try to read from user config
1127 rep = try File.getContent(getConfigFile()).trim() catch (_:Dynamic) null;
1128 if (rep != null)
1129 return rep;
1130
1131 if (!IS_WINDOWS) {
1132 // on unixes, try to read system-wide config
1133 rep = try File.getContent("/etc/.haxelib").trim() catch (_:Dynamic) null;
1134 if (rep == null)
1135 throw "This is the first time you are running haxelib. Please run `haxelib setup` first";
1136 } else {
1137 // on windows, try to use haxe installation path
1138 rep = getWindowsDefaultGlobalRepositoryPath();
1139 if (create)
1140 try safeDir(rep) catch(e:Dynamic) throw 'Error accessing Haxelib repository: $e';
1141 }
1142
1143 return rep;
1144 }
1145
1146 // The Windows haxe installer will setup %HAXEPATH%. We will default haxelib repo to %HAXEPATH%/lib.
1147 // When there is no %HAXEPATH%, we will use a "haxelib" directory next to the config file, ".haxelib".
1148 function getWindowsDefaultGlobalRepositoryPath():String {
1149 var haxepath = Sys.getEnv("HAXEPATH");
1150 if (haxepath != null)
1151 return Path.addTrailingSlash(haxepath.trim()) + REPNAME;
1152 else
1153 return Path.join([Path.directory(getConfigFile()), "haxelib"]);
1154 }
1155
1156 function getSuggestedGlobalRepositoryPath():String {
1157 if (IS_WINDOWS)
1158 return getWindowsDefaultGlobalRepositoryPath();
1159
1160 return if (FileSystem.exists("/usr/share/haxe")) // for Debian
1161 '/usr/share/haxe/$REPNAME'
1162 else if (Sys.systemName() == "Mac") // for newer OSX, where /usr/lib is not writable
1163 '/usr/local/lib/haxe/$REPNAME'
1164 else
1165 '/usr/lib/haxe/$REPNAME'; // for other unixes
1166 }
1167
1168 function getRepository():String {
1169 if (!settings.global)
1170 return switch getLocalRepository() {
1171 case null: getGlobalRepository();
1172 case repo: Path.addTrailingSlash(FileSystem.fullPath(repo));
1173 }
1174 else
1175 return getGlobalRepository();
1176 }
1177
1178 function getLocalRepository():Null<String> {
1179 var dir = Path.removeTrailingSlashes(Sys.getCwd());
1180 while (dir != null) {
1181 var repo = Path.addTrailingSlash(dir) + REPODIR;
1182 if(FileSystem.exists(repo) && FileSystem.isDirectory(repo)) {
1183 return repo;
1184 } else {
1185 dir = new Path(dir).dir;
1186 }
1187 }
1188 return null;
1189 }
1190
1191 function getGlobalRepository():String {
1192 var rep = getGlobalRepositoryPath(true);
1193 if (!FileSystem.exists(rep))
1194 throw "haxelib Repository " + rep + " does not exist. Please run `haxelib setup` again.";
1195 else if (!FileSystem.isDirectory(rep))
1196 throw "haxelib Repository " + rep + " exists, but is a file, not a directory. Please remove it and run `haxelib setup` again.";
1197 return Path.addTrailingSlash(rep);
1198 }
1199
1200 function setup() {
1201 var rep = try getGlobalRepositoryPath() catch (_:Dynamic) null;
1202
1203 var configFile = getConfigFile();
1204
1205 if (args.length <= argcur) {
1206 if (rep == null)
1207 rep = getSuggestedGlobalRepositoryPath();
1208 print("Please enter haxelib repository path with write access");
1209 print("Hit enter for default (" + rep + ")");
1210 }
1211
1212 var line = param("Path");
1213 if (line != "") {
1214 var splitLine = line.split("/");
1215 if(splitLine[0] == "~") {
1216 var home = getHomePath();
1217
1218 for(i in 1...splitLine.length) {
1219 home += "/" + splitLine[i];
1220 }
1221 line = home;
1222 }
1223
1224 rep = line;
1225 }
1226
1227
1228 rep = try absolutePath(rep) catch (e:Dynamic) rep;
1229
1230 if (isSamePath(rep, configFile))
1231 throw "Can't use "+rep+" because it is reserved for config file";
1232
1233 safeDir(rep);
1234 File.saveContent(configFile, rep);
1235
1236 print("haxelib repository is now " + rep);
1237 }
1238
1239 function config() {
1240 print(getRepository());
1241 }
1242
1243 function getCurrent( proj, dir ) {
1244 return try { getDev(dir); return "dev"; } catch( e : Dynamic ) try File.getContent(dir + "/.current").trim() catch( e : Dynamic ) throw "Library "+proj+" is not installed : run 'haxelib install "+proj+"'";
1245 }
1246
1247 function getDev( dir ) {
1248 var path = File.getContent(dir + "/.dev").trim();
1249 path = ~/%([A-Za-z0-9_]+)%/g.map(path,function(r) {
1250 var env = Sys.getEnv(r.matched(1));
1251 return env == null ? "" : env;
1252 });
1253 var filters = try Sys.getEnv("HAXELIB_DEV_FILTER").split(";") catch( e : Dynamic ) null;
1254 if( filters != null && !filters.exists(function(flt) return StringTools.startsWith(path.toLowerCase().split("\\").join("/"),flt.toLowerCase().split("\\").join("/"))) )
1255 throw "This .dev is filtered";
1256 return path;
1257 }
1258
1259 function list() {
1260 var rep = getRepository();
1261 var folders = FileSystem.readDirectory(rep);
1262 var filter = paramOpt();
1263 if ( filter != null )
1264 folders = folders.filter( function (f) return f.toLowerCase().indexOf(filter.toLowerCase()) > -1 );
1265 var all = [];
1266 for( p in folders ) {
1267 if( p.charAt(0) == "." )
1268 continue;
1269
1270 var current = try getCurrent("", rep + p) catch(e:Dynamic) continue;
1271 var dev = try getDev(rep + p) catch( e : Dynamic ) null;
1272
1273 var semvers = [];
1274 var others = [];
1275 for( v in FileSystem.readDirectory(rep+p) ) {
1276 if( v.charAt(0) == "." )
1277 continue;
1278 v = Data.unsafe(v);
1279 var semver = try SemVer.ofString(v) catch (_:Dynamic) null;
1280 if (semver != null)
1281 semvers.push(semver);
1282 else
1283 others.push(v);
1284 }
1285
1286 if (semvers.length > 0)
1287 semvers.sort(SemVer.compare);
1288
1289 var versions = [];
1290 for (v in semvers)
1291 versions.push((v : String));
1292 for (v in others)
1293 versions.push(v);
1294
1295 if (dev == null) {
1296 for (i in 0...versions.length) {
1297 var v = versions[i];
1298 if (v == current)
1299 versions[i] = '[$v]';
1300 }
1301 } else {
1302 versions.push("[dev:"+dev+"]");
1303 }
1304
1305 all.push(Data.unsafe(p) + ": "+versions.join(" "));
1306 }
1307 all.sort(function(s1, s2) return Reflect.compare(s1.toLowerCase(), s2.toLowerCase()));
1308 for (p in all) {
1309 print(p);
1310 }
1311 }
1312
1313 function update() {
1314 var rep = getRepository();
1315
1316 var prj = paramOpt();
1317 if (prj != null) {
1318 prj = projectNameToDir(rep, prj); // get project name in proper case
1319 if (!updateByName(rep, prj))
1320 print(prj + " is up to date");
1321 return;
1322 }
1323
1324 var state = { rep : rep, prompt : true, updated : false };
1325 for( p in FileSystem.readDirectory(state.rep) ) {
1326 if( p.charAt(0) == "." || !FileSystem.isDirectory(state.rep+"/"+p) )
1327 continue;
1328 var p = Data.unsafe(p);
1329 print("Checking " + p);
1330 try {
1331 doUpdate(p, state);
1332 } catch (e:VcsError) {
1333 if (!e.match(VcsUnavailable(_)))
1334 rethrow(e);
1335 }
1336 }
1337 if( state.updated )
1338 print("Done");
1339 else
1340 print("All libraries are up-to-date");
1341 }
1342
1343 function projectNameToDir( rep:String, project:String ) {
1344 var p = project.toLowerCase();
1345 var l = FileSystem.readDirectory(rep).filter(function (dir) return dir.toLowerCase() == p);
1346
1347 switch (l) {
1348 case []: return project;
1349 case [dir]: return Data.unsafe(dir);
1350 case _: throw "Several name case for library " + project;
1351 }
1352 }
1353
1354 function updateByName(rep:String, prj:String) {
1355 var state = { rep : rep, prompt : false, updated : false };
1356 doUpdate(prj,state);
1357 return state.updated;
1358 }
1359
1360 function doUpdate( p : String, state : { updated : Bool, rep : String, prompt : Bool } ) {
1361 var pdir = state.rep + Data.safe(p);
1362
1363 var vcs = Vcs.getVcsForDevLib(pdir, settings);
1364 if(vcs != null) {
1365 if(!vcs.available)
1366 throw VcsError.VcsUnavailable(vcs);
1367
1368 var oldCwd = Sys.getCwd();
1369 Sys.setCwd(pdir + "/" + vcs.directory);
1370 var success = vcs.update(p);
1371
1372 state.updated = success;
1373 if(success)
1374 print(p + " was updated");
1375 Sys.setCwd(oldCwd);
1376 } else {
1377 var latest = try retry(site.getLatestVersion.bind(p)) catch( e : Dynamic ) { Sys.println(e); return; };
1378
1379 if( !FileSystem.exists(pdir+"/"+Data.safe(latest)) ) {
1380 if( state.prompt ) {
1381 if (!ask("Update "+p+" to "+latest))
1382 return;
1383 }
1384 var info = retry(site.infos.bind(p));
1385 doInstall(state.rep, info.name, latest,true);
1386 state.updated = true;
1387 } else
1388 setCurrent(state.rep, p, latest, true);
1389 }
1390 }
1391
1392 function remove() {
1393 var rep = getRepository();
1394 var prj = param("Library");
1395 var version = paramOpt();
1396 var pdir = rep + Data.safe(prj);
1397 if( version == null ) {
1398 if( !FileSystem.exists(pdir) )
1399 throw "Library "+prj+" is not installed";
1400
1401 if (prj == HAXELIB_LIBNAME && isHaxelibRun) {
1402 print('Error: Removing "$HAXELIB_LIBNAME" requires the --system flag');
1403 Sys.exit(1);
1404 }
1405
1406 deleteRec(pdir);
1407 print("Library "+prj+" removed");
1408 return;
1409 }
1410
1411 var vdir = pdir + "/" + Data.safe(version);
1412 if( !FileSystem.exists(vdir) )
1413 throw "Library "+prj+" does not have version "+version+" installed";
1414
1415 var cur = File.getContent(pdir + "/.current").trim(); // set version regardless of dev
1416 if( cur == version )
1417 throw "Can't remove current version of library "+prj;
1418 var dev = try getDev(pdir) catch (_:Dynamic) null; // dev is checked here
1419 if( dev == vdir )
1420 throw "Can't remove dev version of library "+prj;
1421 deleteRec(vdir);
1422 print("Library "+prj+" version "+version+" removed");
1423 }
1424
1425 function set() {
1426 setCurrent(getRepository(), param("Library"), param("Version"), false);
1427 }
1428
1429 function setCurrent( rep : String, prj : String, version : String, doAsk : Bool ) {
1430 var pdir = rep + Data.safe(prj);
1431 var vdir = pdir + "/" + Data.safe(version);
1432 if( !FileSystem.exists(vdir) ){
1433 print("Library "+prj+" version "+version+" is not installed");
1434 if(ask("Would you like to install it?")) {
1435 var info = retry(site.infos.bind(prj));
1436 doInstall(rep, info.name, version, true);
1437 }
1438 return;
1439 }
1440 if( File.getContent(pdir + "/.current").trim() == version )
1441 return;
1442 if( doAsk && !ask("Set "+prj+" to version "+version) )
1443 return;
1444 File.saveContent(pdir+"/.current",version);
1445 print("Library "+prj+" current version is now "+version);
1446 }
1447
1448 function checkRec( rep : String, prj : String, version : String, l : List<{ project : String, version : String, dir : String, info : Infos }>, ?returnDependencies : Bool = true ) {
1449 var pdir = rep + Data.safe(prj);
1450 var explicitVersion = version != null;
1451 var version = if( version != null ) version else getCurrent(prj, pdir);
1452
1453 var dev = try getDev(pdir) catch (_:Dynamic) null;
1454 var vdir = pdir + "/" + Data.safe(version);
1455
1456 if( dev != null && (!explicitVersion || !FileSystem.exists(vdir)) )
1457 vdir = dev;
1458
1459 if( !FileSystem.exists(vdir) )
1460 throw "Library "+prj+" version "+version+" is not installed";
1461
1462 for( p in l )
1463 if( p.project == prj ) {
1464 if( p.version == version )
1465 return;
1466 throw "Library "+prj+" has two versions included : "+version+" and "+p.version;
1467 }
1468 var json = try File.getContent(vdir+"/"+Data.JSON) catch( e : Dynamic ) null;
1469 var inf = Data.readData(json, json != null ? CheckSyntax : NoCheck);
1470 l.add({ project : prj, version : version, dir : Path.addTrailingSlash(vdir), info: inf });
1471 if( returnDependencies ) {
1472 for( d in inf.dependencies )
1473 if( !Lambda.exists(l, function(e) return e.project == d.name) )
1474 checkRec(rep,d.name,if( d.version == "" ) null else d.version,l);
1475 }
1476 }
1477
1478 function path() {
1479 var rep = getRepository();
1480 var list = new List();
1481 while( argcur < args.length ) {
1482 var a = args[argcur++].split(":");
1483 try {
1484 checkRec(rep, a[0], a[1], list);
1485 } catch(e:Dynamic) {
1486 throw 'Cannot process $a: $e';
1487 }
1488 }
1489 for( d in list ) {
1490 var ndir = d.dir + "ndll";
1491 if (FileSystem.exists(ndir))
1492 Sys.println('-L $ndir/');
1493
1494 try {
1495 Sys.println(normalizeHxml(File.getContent(d.dir + "extraParams.hxml")));
1496 } catch(_:Dynamic) {}
1497
1498 var dir = d.dir;
1499 if (d.info.classPath != "") {
1500 var cp = d.info.classPath;
1501 dir = Path.addTrailingSlash( d.dir + cp );
1502 }
1503 Sys.println(dir);
1504
1505 Sys.println("-D " + d.project + "="+d.info.version);
1506
1507 if (d.info.documentation != null) {
1508 var doc = d.info.documentation;
1509
1510 // we'll have to change this to "4.3.0" after the release
1511 if (haxeVersion() >= SemVer.ofString("4.3.0-rc.1")) {
1512 // custom defines if defined
1513 if (doc.defines != null && doc.defines != "") {
1514 var path = Path.join([d.dir, doc.defines]);
1515 Sys.println('--macro registerDefinesDescriptionFile(\'$path\', \'${d.info.name}\')');
1516 }
1517
1518 // custom metadatas if defined
1519 if (doc.metadata != null && doc.metadata != "") {
1520 var path = Path.join([d.dir, doc.metadata]);
1521 Sys.println('--macro registerMetadataDescriptionFile(\'$path\', \'${d.info.name}\')');
1522 }
1523 }
1524 }
1525 }
1526 }
1527
1528 function libpath( ) {
1529 var rep = getRepository();
1530 while( argcur < args.length ) {
1531 var a = args[argcur++].split(":");
1532 var results = new List();
1533 checkRec(rep, a[0], a[1], results, false);
1534 if( !results.isEmpty() ) Sys.println(results.first().dir);
1535 }
1536 }
1537
1538 function dev() {
1539 var rep = getRepository();
1540 var project = param("Library");
1541 var dir = paramOpt();
1542 var proj = rep + Data.safe(project);
1543 if( !FileSystem.exists(proj) ) {
1544 FileSystem.createDirectory(proj);
1545 }
1546 var devfile = proj+"/.dev";
1547 if( dir == null ) {
1548 if( FileSystem.exists(devfile) )
1549 FileSystem.deleteFile(devfile);
1550 print("Development directory disabled");
1551 }
1552 else {
1553 while ( dir.endsWith("/") || dir.endsWith("\\") ) {
1554 dir = dir.substr(0,-1);
1555 }
1556 if (!FileSystem.exists(dir)) {
1557 print('Directory $dir does not exist');
1558 } else {
1559 dir = FileSystem.fullPath(dir);
1560 try {
1561 File.saveContent(devfile, dir);
1562 print("Development directory set to "+dir);
1563 }
1564 catch (e:Dynamic) {
1565 print('Could not write to $devfile');
1566 }
1567 }
1568
1569 }
1570 }
1571
1572
1573 function removeExistingDevLib(proj:String):Void {
1574 //TODO: ask if existing repo have changes.
1575
1576 // find existing repo:
1577 var vcs = Vcs.getVcsForDevLib(proj, settings);
1578 // remove existing repos:
1579 while(vcs != null) {
1580 deleteRec(proj + "/" + vcs.directory);
1581 vcs = Vcs.getVcsForDevLib(proj, settings);
1582 }
1583 }
1584
1585 inline function useVcs(id:VcsID, fn:Vcs->Void):Void {
1586 // Prepare check vcs.available:
1587 var vcs = Vcs.get(id, settings);
1588 if(vcs == null || !vcs.available)
1589 throw 'Could not use $id, please make sure it is installed and available in your PATH.';
1590 return fn(vcs);
1591 }
1592
1593 function vcs(id:VcsID) {
1594 var rep = getRepository();
1595 useVcs(id, function(vcs) doVcsInstall(rep, vcs, param("Library name"), param(vcs.name + " path"), paramOpt(), paramOpt(), paramOpt()));
1596 }
1597
1598 function doVcsInstall(rep:String, vcs:Vcs, libName:String, url:String, branch:String, subDir:String, version:String) {
1599
1600 var proj = rep + Data.safe(libName);
1601
1602 var libPath = proj + "/" + vcs.directory;
1603
1604 function doVcsClone() {
1605 print("Installing " +libName + " from " +url + ( branch != null ? " branch: " + branch : "" ));
1606 try {
1607 vcs.clone(libPath, url, branch, version);
1608 } catch(error:VcsError) {
1609 deleteRec(libPath);
1610 var message = switch(error) {
1611 case VcsUnavailable(vcs):
1612 'Could not use ${vcs.executable}, please make sure it is installed and available in your PATH.';
1613 case CantCloneRepo(vcs, repo, stderr):
1614 'Could not clone ${vcs.name} repository' + (stderr != null ? ":\n" + stderr : ".");
1615 case CantCheckoutBranch(vcs, branch, stderr):
1616 'Could not checkout branch, tag or path "$branch": ' + stderr;
1617 case CantCheckoutVersion(vcs, version, stderr):
1618 'Could not checkout tag "$version": ' + stderr;
1619 };
1620 throw message;
1621 }
1622 }
1623
1624 if ( FileSystem.exists(proj + "/" + Data.safe(vcs.directory)) ) {
1625 print("You already have "+libName+" version "+vcs.directory+" installed.");
1626
1627 var wasUpdated = this.alreadyUpdatedVcsDependencies.exists(libName);
1628 var currentBranch = if (wasUpdated) this.alreadyUpdatedVcsDependencies.get(libName) else null;
1629
1630 if (branch != null && (!wasUpdated || (wasUpdated && currentBranch != branch))
1631 && ask("Overwrite branch: " + (currentBranch == null?"<unspecified>":"\"" + currentBranch + "\"") + " with \"" + branch + "\""))
1632 {
1633 deleteRec(libPath);
1634 doVcsClone();
1635 }
1636 else if (!wasUpdated)
1637 {
1638 print("Updating " + libName+" version " + vcs.directory + " ...");
1639 updateByName(rep, libName);
1640 }
1641 } else {
1642 doVcsClone();
1643 }
1644
1645 // finish it!
1646 if (subDir != null) {
1647 libPath += "/" + subDir;
1648 File.saveContent(proj + "/.dev", libPath);
1649 print("Development directory set to "+libPath);
1650 } else {
1651 File.saveContent(proj + "/.current", vcs.directory);
1652 print("Library "+libName+" current version is now "+vcs.directory);
1653 }
1654
1655 this.alreadyUpdatedVcsDependencies.set(libName, branch);
1656
1657 var jsonPath = libPath + "/haxelib.json";
1658 if(FileSystem.exists(jsonPath))
1659 doInstallDependencies(rep, Data.readData(File.getContent(jsonPath), false).dependencies);
1660 }
1661
1662
1663 function run() {
1664 var rep = getRepository();
1665 var project = param("Library");
1666 var temp = project.split(":");
1667 doRun(rep, temp[0], temp[1]);
1668 }
1669
1670 function haxeVersion():SemVer {
1671 if(__haxeVersion == null) {
1672 var p = new Process('haxe', ['--version']);
1673 if(p.exitCode() != 0) {
1674 throw 'Cannot get haxe version: ${p.stderr.readAll().toString()}';
1675 }
1676 var str = p.stdout.readAll().toString();
1677 __haxeVersion = SemVer.ofString(str.split('+')[0]);
1678 }
1679 return __haxeVersion;
1680 }
1681 static var __haxeVersion:SemVer;
1682
1683 function doRun( rep:String, project:String, version:String ) {
1684 var pdir = rep + Data.safe(project);
1685 if( !FileSystem.exists(pdir) )
1686 throw "Library "+project+" is not installed";
1687 pdir += "/";
1688 if (version == null)
1689 version = getCurrent(project, pdir);
1690 var dev = try getDev(pdir) catch ( e : Dynamic ) null;
1691 var vdir = dev != null ? dev : pdir + Data.safe(version);
1692
1693 var infos =
1694 try
1695 Data.readData(File.getContent(vdir + '/haxelib.json'), false)
1696 catch (e:Dynamic)
1697 throw 'Error parsing haxelib.json for $project@$version: $e';
1698
1699 args.push(Sys.getCwd());
1700 Sys.setCwd(vdir);
1701
1702 var callArgs =
1703 if (infos.main != null) {
1704 runScriptArgs(project, infos.main, infos.dependencies);
1705 } else if(FileSystem.exists('$vdir/run.n')) {
1706 ["neko", vdir + "/run.n"];
1707 } else if(FileSystem.exists('$vdir/Run.hx')) {
1708 runScriptArgs(project, 'Run', infos.dependencies);
1709 } else {
1710 throw 'Library $project version $version does not have a run script';
1711 }
1712 for (i in argcur...args.length)
1713 callArgs.push(args[i]);
1714
1715 Sys.putEnv("HAXELIB_RUN", "1");
1716 Sys.putEnv("HAXELIB_RUN_NAME", project);
1717 var cmd = callArgs.shift();
1718 Sys.exit(Sys.command(cmd, callArgs));
1719 }
1720
1721 function runScriptArgs(project:String, main:String, dependencies:Dependencies):Array<String> {
1722 var deps = dependencies.toArray();
1723 deps.push( { name: project, version: DependencyVersion.DEFAULT } );
1724 var args = [];
1725 // TODO: change comparison to '4.0.0' upon Haxe 4.0 release
1726 if(settings.global && SemVer.compare(haxeVersion(), SemVer.ofString('4.0.0-rc.5')) >= 0) {
1727 args.push('--haxelib-global');
1728 }
1729 for (d in deps) {
1730 args.push('-lib');
1731 args.push(d.name + if (d.version == '') '' else ':${d.version}');
1732 }
1733 args.unshift('haxe');
1734 args.push('--run');
1735 args.push(main);
1736 return args;
1737 }
1738
1739 function proxy() {
1740 var rep = getRepository();
1741 var host = param("Proxy host");
1742 if( host == "" ) {
1743 if( FileSystem.exists(rep + "/.proxy") ) {
1744 FileSystem.deleteFile(rep + "/.proxy");
1745 print("Proxy disabled");
1746 } else
1747 print("No proxy specified");
1748 return;
1749 }
1750 var port = Std.parseInt(param("Proxy port"));
1751 var authName = param("Proxy user login");
1752 var authPass = authName == "" ? "" : param("Proxy user pass");
1753 var proxy = {
1754 host : host,
1755 port : port,
1756 auth : authName == "" ? null : { user : authName, pass : authPass },
1757 };
1758 Http.PROXY = proxy;
1759 print("Testing proxy...");
1760 try Http.requestUrl(SERVER.protocol + "://lib.haxe.org") catch( e : Dynamic ) {
1761 if(!ask("Proxy connection failed. Use it anyway")) {
1762 return;
1763 }
1764 }
1765 File.saveContent(rep + "/.proxy", haxe.Serializer.run(proxy));
1766 print("Proxy setup done");
1767 }
1768
1769 function loadProxy() {
1770 var rep = getRepository();
1771 try Http.PROXY = haxe.Unserializer.run(File.getContent(rep + "/.proxy")) catch( e : Dynamic ) { };
1772 }
1773
1774 function convertXml() {
1775 var cwd = Sys.getCwd();
1776 var xmlFile = cwd + "haxelib.xml";
1777 var jsonFile = cwd + "haxelib.json";
1778
1779 if (!FileSystem.exists(xmlFile)) {
1780 print('No `haxelib.xml` file was found in the current directory.');
1781 Sys.exit(0);
1782 }
1783
1784 var xmlString = File.getContent(xmlFile);
1785 var json = ConvertXml.convert(xmlString);
1786 var jsonString = ConvertXml.prettyPrint(json);
1787
1788 File.saveContent(jsonFile, jsonString);
1789 print('Saved to $jsonFile');
1790 }
1791
1792 function newRepo() {
1793 var path = absolutePath(REPODIR);
1794 var created = FsUtils.safeDir(path, true);
1795 if (created)
1796 print('Local repository created ($path)');
1797 else
1798 print('Local repository already exists ($path)');
1799 }
1800
1801 function deleteRepo() {
1802 var path = absolutePath(REPODIR);
1803 var deleted = FsUtils.deleteRec(path);
1804 if (deleted)
1805 print('Local repository deleted ($path)');
1806 else
1807 print('No local repository found ($path)');
1808 }
1809
1810 // ----------------------------------
1811
1812 inline function print(str)
1813 Sys.println(str);
1814
1815 static function main() {
1816 switch(Sys.getEnv("HAXELIB_NO_SSL")) {
1817 case "1", "true":
1818 SERVER.noSsl = true;
1819 SERVER.protocol = "http";
1820 case _:
1821 }
1822 try {
1823 new Main().process();
1824 } catch(e:Dynamic) {
1825 for(arg in Sys.args()) {
1826 if(arg == '--debug') {
1827 Util.rethrow(e);
1828 }
1829 }
1830 Sys.stderr().writeString(Std.string(e) + '\n');
1831 }
1832 }
1833
1834 // haxe 3.1.3 doesn't have FileSystem.absolutePath()
1835 static function absolutePath(path:String) {
1836 if (StringTools.startsWith(path, '/') || path.charAt(1) == ':' || StringTools.startsWith(path, '\\\\')) {
1837 return path;
1838 }
1839 return haxe.io.Path.join([Sys.getCwd(), path]);
1840 }
1841
1842 // deprecated commands
1843 function local() {
1844 doInstallFile(getRepository(), param("Package"), true, true);
1845 }
1846
1847 function updateSelf() {
1848 updateByName(getGlobalRepository(), HAXELIB_LIBNAME);
1849 }
1850 }