Main.hx 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. /*
  2. * Copyright (C)2005-2012 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 tools.haxelib;
  23. import haxe.crypto.Md5;
  24. import haxe.*;
  25. import haxe.io.Path;
  26. import haxe.zip.Reader;
  27. import tools.haxelib.Data;
  28. import sys.FileSystem;
  29. import sys.io.*;
  30. import haxe.ds.Option;
  31. using StringTools;
  32. enum Answer {
  33. Yes;
  34. No;
  35. Always;
  36. }
  37. class SiteProxy extends haxe.remoting.Proxy<tools.haxelib.SiteApi> {
  38. }
  39. class Progress extends haxe.io.Output {
  40. var o : haxe.io.Output;
  41. var cur : Int;
  42. var max : Int;
  43. var start : Float;
  44. public function new(o) {
  45. this.o = o;
  46. cur = 0;
  47. start = Timer.stamp();
  48. }
  49. function bytes(n) {
  50. cur += n;
  51. if( max == null )
  52. Sys.print(cur+" bytes\r");
  53. else
  54. Sys.print(cur+"/"+max+" ("+Std.int((cur*100.0)/max)+"%)\r");
  55. }
  56. public override function writeByte(c) {
  57. o.writeByte(c);
  58. bytes(1);
  59. }
  60. public override function writeBytes(s,p,l) {
  61. var r = o.writeBytes(s,p,l);
  62. bytes(r);
  63. return r;
  64. }
  65. public override function close() {
  66. super.close();
  67. o.close();
  68. var time = Timer.stamp() - start;
  69. var speed = (cur / time) / 1024;
  70. time = Std.int(time * 10) / 10;
  71. speed = Std.int(speed * 10) / 10;
  72. Sys.print("Download complete : "+cur+" bytes in "+time+"s ("+speed+"KB/s)\n");
  73. }
  74. public override function prepare(m) {
  75. max = m;
  76. }
  77. }
  78. class ProgressIn extends haxe.io.Input {
  79. var i : haxe.io.Input;
  80. var pos : Int;
  81. var tot : Int;
  82. public function new( i, tot ) {
  83. this.i = i;
  84. this.pos = 0;
  85. this.tot = tot;
  86. }
  87. public override function readByte() {
  88. var c = i.readByte();
  89. doRead(1);
  90. return c;
  91. }
  92. public override function readBytes(buf,pos,len) {
  93. var k = i.readBytes(buf,pos,len);
  94. doRead(k);
  95. return k;
  96. }
  97. function doRead( nbytes : Int ) {
  98. pos += nbytes;
  99. Sys.print( Std.int((pos * 100.0) / tot) + "%\r" );
  100. }
  101. }
  102. class Main {
  103. static var VERSION = SemVer.ofString('3.0.0');
  104. static var REPNAME = "lib";
  105. static var SERVER = {
  106. host : "lib.haxe.org",
  107. port : 80,
  108. dir : "",
  109. url : "index.n",
  110. apiVersion : VERSION.major+"."+VERSION.minor,
  111. };
  112. var argcur : Int;
  113. var args : Array<String>;
  114. var commands : List<{ name : String, doc : String, f : Void -> Void, net : Bool }>;
  115. var siteUrl : String;
  116. var site : SiteProxy;
  117. function new() {
  118. args = Sys.args();
  119. commands = new List();
  120. addCommand("install", install, "install a given library, or all libraries from a hxml file");
  121. addCommand("list", list, "list all installed libraries", false);
  122. addCommand("upgrade", upgrade, "upgrade all installed libraries");
  123. addCommand("update", update, "update a single library");
  124. addCommand("selfupdate", updateSelf, "update haxelib itself");
  125. addCommand("remove", remove, "remove a given library/version", false);
  126. addCommand("set", set, "set the current version for a library", false);
  127. addCommand("search", search, "list libraries matching a word");
  128. addCommand("info", info, "list informations on a given library");
  129. addCommand("user", user, "list informations on a given user");
  130. addCommand("register", register, "register a new user");
  131. addCommand("submit", submit, "submit or update a library package");
  132. addCommand("setup", setup, "set the haxelib repository path", false);
  133. addCommand("convertxml", convertXml, "convert haxelib.xml file to haxelib.json");
  134. addCommand("config", config, "print the repository path", false);
  135. addCommand("path", path, "give paths to libraries", false);
  136. addCommand("run", run, "run the specified library with parameters", false);
  137. addCommand("local", local, "install the specified package locally", false);
  138. addCommand("dev", dev, "set the development directory for a given library", false);
  139. addCommand("git", git, "uses git repository as library");
  140. addCommand("proxy", proxy, "setup the Http proxy");
  141. initSite();
  142. }
  143. function initSite() {
  144. siteUrl = "http://" + SERVER.host + ":" + SERVER.port + "/" + SERVER.dir;
  145. site = new SiteProxy(haxe.remoting.HttpConnection.urlConnect(siteUrl + "api/" + SERVER.apiVersion + "/" + SERVER.url).api);
  146. }
  147. function param( name, ?passwd ) {
  148. if( args.length > argcur )
  149. return args[argcur++];
  150. Sys.print(name+" : ");
  151. if( passwd ) {
  152. var s = new StringBuf();
  153. do switch Sys.getChar(false) {
  154. case 10, 13: break;
  155. case c: s.addChar(c);
  156. }
  157. while (true);
  158. print("");
  159. return s.toString();
  160. }
  161. return Sys.stdin().readLine();
  162. }
  163. function ask( question ) {
  164. while( true ) {
  165. Sys.print(question+" [y/n/a] ? ");
  166. switch( Sys.stdin().readLine() ) {
  167. case "n": return No;
  168. case "y": return Yes;
  169. case "a": return Always;
  170. }
  171. }
  172. return null;
  173. }
  174. function paramOpt() {
  175. if( args.length > argcur )
  176. return args[argcur++];
  177. return null;
  178. }
  179. function addCommand( name, f, doc, ?net = true ) {
  180. commands.add({ name : name, doc : doc, f : f, net : net });
  181. }
  182. function usage() {
  183. print("Haxe Library Manager " + VERSION + " - (c)2006-2013 Haxe Foundation");
  184. print(" Usage : haxelib [command] [options]");
  185. print(" Commands :");
  186. for( c in commands )
  187. print(" "+c.name+" : "+c.doc);
  188. Sys.exit(1);
  189. }
  190. function process() {
  191. var debug = false;
  192. argcur = 0;
  193. while( true ) {
  194. var a = args[argcur++];
  195. if( a == null )
  196. break;
  197. switch( a ) {
  198. case "-debug":
  199. debug = true;
  200. case "-notimeout":
  201. haxe.remoting.HttpConnection.TIMEOUT = 0;
  202. case "-R":
  203. var path = args[argcur++];
  204. var r = ~/^(http:\/\/)?([^:\/]+)(:[0-9]+)?\/?(.*)$/;
  205. if( !r.match(path) )
  206. throw "Invalid repository format '"+path+"'";
  207. SERVER.host = r.matched(2);
  208. if( r.matched(3) != null )
  209. SERVER.port = Std.parseInt(r.matched(3).substr(1));
  210. SERVER.dir = r.matched(4);
  211. initSite();
  212. default:
  213. argcur--;
  214. break;
  215. }
  216. }
  217. var cmd = args[argcur++];
  218. if( cmd == null )
  219. usage();
  220. for( c in commands )
  221. if( c.name == cmd ) {
  222. try {
  223. if( c.net ) loadProxy();
  224. c.f();
  225. } catch( e : Dynamic ) {
  226. if( e == "std@host_resolve" ) {
  227. print("Host "+SERVER.host+" was not found");
  228. print("Please ensure that your internet connection is on");
  229. print("If you don't have an internet connection or if you are behing a proxy");
  230. print("please download manually the file from http://lib.haxe.org/files/3.0/");
  231. print("and run 'haxelib local <file>' to install the Library.");
  232. print("You can also setup the proxy with 'haxelib proxy'.");
  233. Sys.exit(1);
  234. }
  235. if( e == "Blocked" ) {
  236. print("Http connection timeout. Try running haxelib -notimeout <command> to disable timeout");
  237. Sys.exit(1);
  238. }
  239. if( debug )
  240. neko.Lib.rethrow(e);
  241. print(Std.string(e));
  242. Sys.exit(1);
  243. }
  244. return;
  245. }
  246. print("Unknown command "+cmd);
  247. usage();
  248. }
  249. // ---- COMMANDS --------------------
  250. function search() {
  251. var word = param("Search word");
  252. var l = site.search(word);
  253. for( s in l )
  254. print(s.name);
  255. print(l.length+" libraries found");
  256. }
  257. function info() {
  258. var prj = param("Library name");
  259. var inf = site.infos(prj);
  260. print("Name: "+inf.name);
  261. print("Tags: "+inf.tags.join(", "));
  262. print("Desc: "+inf.desc);
  263. print("Website: "+inf.website);
  264. print("License: "+inf.license);
  265. print("Owner: "+inf.owner);
  266. print("Version: "+inf.curversion);
  267. print("Releases: ");
  268. if( inf.versions.length == 0 )
  269. print(" (no version released yet)");
  270. for( v in inf.versions )
  271. print(" "+v.date+" "+v.name+" : "+v.comments);
  272. }
  273. function user() {
  274. var uname = param("User name");
  275. var inf = site.user(uname);
  276. print("Id: "+inf.name);
  277. print("Name: "+inf.fullname);
  278. print("Mail: "+inf.email);
  279. print("Libraries: ");
  280. if( inf.projects.length == 0 )
  281. print(" (no libraries)");
  282. for( p in inf.projects )
  283. print(" "+p);
  284. }
  285. function register() {
  286. doRegister(param("User"));
  287. print("Registration successful");
  288. }
  289. function doRegister(name) {
  290. var email = param("Email");
  291. var fullname = param("Fullname");
  292. var pass = param("Password",true);
  293. var pass2 = param("Confirm",true);
  294. if( pass != pass2 )
  295. throw "Password does not match";
  296. pass = Md5.encode(pass);
  297. site.register(name,pass,email,fullname);
  298. return pass;
  299. }
  300. function submit() {
  301. var file = param("Package");
  302. var data = File.getBytes(file);
  303. var zip = Reader.readZip(new haxe.io.BytesInput(data));
  304. var infos = Data.readInfos(zip,true);
  305. var user = infos.developers.first();
  306. var password;
  307. if( site.isNewUser(user) ) {
  308. print("This is your first submission as '"+user+"'");
  309. print("Please enter the following informations for registration");
  310. password = doRegister(user);
  311. } else {
  312. if( infos.developers.length > 1 )
  313. user = param("User");
  314. password = Md5.encode(param("Password",true));
  315. if( !site.checkPassword(user,password) )
  316. throw "Invalid password for "+user;
  317. }
  318. site.checkDeveloper(infos.project,user);
  319. // check dependencies validity
  320. for( d in infos.dependencies ) {
  321. var infos = site.infos(d.project);
  322. if( d.version == "" )
  323. continue;
  324. var found = false;
  325. for( v in infos.versions )
  326. if( v.name == d.version ) {
  327. found = true;
  328. break;
  329. }
  330. if( !found )
  331. throw "Library "+d.project+" does not have version "+d.version;
  332. }
  333. // check if this version already exists
  334. var sinfos = try site.infos(infos.project) catch( _ : Dynamic ) null;
  335. if( sinfos != null )
  336. for( v in sinfos.versions )
  337. if( v.name == infos.version.toString() && ask("You're about to overwrite existing version '"+v.name+"', please confirm") == No )
  338. throw "Aborted";
  339. // query a submit id that will identify the file
  340. var id = site.getSubmitId();
  341. // directly send the file data over Http
  342. var h = new Http("http://"+SERVER.host+":"+SERVER.port+"/"+SERVER.url);
  343. h.onError = function(e) { throw e; };
  344. h.onData = print;
  345. h.fileTransfert("file",id,new ProgressIn(new haxe.io.BytesInput(data),data.length),data.length);
  346. print("Sending data.... ");
  347. h.request(true);
  348. // processing might take some time, make sure we wait
  349. print("Processing file.... ");
  350. haxe.remoting.HttpConnection.TIMEOUT = 1000;
  351. // ask the server to register the sent file
  352. var msg = site.processSubmit(id,user,password);
  353. print(msg);
  354. }
  355. function install() {
  356. var prj = param("Library name or hxml file:");
  357. // No library given, install libraries listed in *.hxml in given directory
  358. if( prj == "all")
  359. {
  360. installFromAllHxml();
  361. return;
  362. }
  363. if( sys.FileSystem.exists(prj) && !sys.FileSystem.isDirectory(prj) ) {
  364. // *.hxml provided, install all libraries/versions in this hxml file
  365. if( prj.endsWith(".hxml") )
  366. {
  367. installFromHxml(prj);
  368. return;
  369. }
  370. // *.zip provided, install zip as haxe library
  371. if( prj.endsWith(".zip") )
  372. {
  373. doInstallFile(prj,true,true);
  374. return;
  375. }
  376. }
  377. // Name provided that wasn't a local hxml or zip, so try to install it from server
  378. var inf = site.infos(prj);
  379. var reqversion = paramOpt();
  380. var version = getVersion(inf, reqversion);
  381. doInstall(inf.name,version,version == inf.curversion);
  382. }
  383. function getVersion( inf:ProjectInfos, ?reqversion:String )
  384. {
  385. if( inf.curversion == null )
  386. throw "The library "+inf.name+" has not yet released a version";
  387. var version = if( reqversion != null ) reqversion else inf.curversion;
  388. var found = false;
  389. for( v in inf.versions )
  390. if( v.name == version ) {
  391. found = true;
  392. break;
  393. }
  394. if( !found )
  395. throw "No such version "+version+" for library "+inf.name;
  396. return version;
  397. }
  398. function installFromHxml( path )
  399. {
  400. var hxml = sys.io.File.getContent(path);
  401. var lines = hxml.split("\n");
  402. var libsToInstall = new Map<String, {name:String,version:String}>();
  403. for (l in lines)
  404. {
  405. l = l.trim();
  406. if (l.startsWith("-lib"))
  407. {
  408. var key = l.substr(5);
  409. var parts = key.split(":");
  410. var libName = parts[0].trim();
  411. var libVersion = if (parts.length > 1) parts[1].trim() else null;
  412. if (libsToInstall.exists(key) == false)
  413. {
  414. libsToInstall.set(key, { name:libName, version:libVersion });
  415. }
  416. }
  417. }
  418. installMany(libsToInstall);
  419. }
  420. function installFromAllHxml()
  421. {
  422. var hxmlFiles = sys.FileSystem.readDirectory(Sys.getCwd()).filter(function (f) return f.endsWith(".hxml"));
  423. if (hxmlFiles.length > 0)
  424. {
  425. for (file in hxmlFiles)
  426. {
  427. if (file.endsWith(".hxml"))
  428. {
  429. print('Installing all libraries from $file:');
  430. installFromHxml(Sys.getCwd()+file);
  431. }
  432. }
  433. }
  434. else
  435. {
  436. print ("No hxml files found in the current directory.");
  437. }
  438. }
  439. function installMany( libs:Iterable<{name:String,version:String}>, ?setCurrent=true )
  440. {
  441. if (Lambda.count(libs) == 0) return;
  442. // Check the version numbers are all good
  443. // TODO: can we collapse this into a single API call? It's getting too slow otherwise.
  444. print("Loading info about the required libraries");
  445. for (l in libs)
  446. {
  447. var inf = site.infos(l.name);
  448. l.version = getVersion(inf, l.version);
  449. }
  450. // Print a list with all the info
  451. print("Haxelib is going to install these libraries:");
  452. for (l in libs)
  453. {
  454. var vString = (l.version == null) ? "" : " - " + l.version;
  455. print(" " + l.name + vString);
  456. }
  457. // Install if they confirm
  458. if (ask("Continue?") != No)
  459. {
  460. for (l in libs)
  461. {
  462. doInstall(l.name, l.version, setCurrent);
  463. }
  464. }
  465. }
  466. function doInstall( project, version, setcurrent ) {
  467. var rep = getRepository();
  468. // check if exists already
  469. if( FileSystem.exists(rep+Data.safe(project)+"/"+Data.safe(version)) ) {
  470. print("You already have "+project+" version "+version+" installed");
  471. setCurrent(project,version,true);
  472. return;
  473. }
  474. // download to temporary file
  475. var filename = Data.fileName(project,version);
  476. var filepath = rep+filename;
  477. var out = File.write(filepath,true);
  478. var progress = new Progress(out);
  479. var h = new Http(siteUrl+Data.REPOSITORY+"/"+filename);
  480. h.onError = function(e) {
  481. progress.close();
  482. FileSystem.deleteFile(filepath);
  483. throw e;
  484. };
  485. print("Downloading "+filename+"...");
  486. h.customRequest(false,progress);
  487. doInstallFile(filepath, setcurrent);
  488. site.postInstall(project, version);
  489. }
  490. function doInstallFile(filepath,setcurrent,?nodelete) {
  491. // read zip content
  492. var f = File.read(filepath,true);
  493. var zip = Reader.readZip(f);
  494. f.close();
  495. var infos = Data.readInfos(zip,false);
  496. // create directories
  497. var pdir = getRepository() + Data.safe(infos.project);
  498. safeDir(pdir);
  499. pdir += "/";
  500. var target = pdir + Data.safe(infos.version.toString());
  501. safeDir(target);
  502. target += "/";
  503. // locate haxelib.json base path
  504. var basepath = Data.locateBasePath(zip);
  505. // unzip content
  506. for( zipfile in zip ) {
  507. var n = zipfile.fileName;
  508. if( n.startsWith(basepath) ) {
  509. // remove basepath
  510. n = n.substr(basepath.length,n.length-basepath.length);
  511. if( n.charAt(0) == "/" || n.charAt(0) == "\\" || n.split("..").length > 1 )
  512. throw "Invalid filename : "+n;
  513. var dirs = ~/[\/\\]/g.split(n);
  514. var path = "";
  515. var file = dirs.pop();
  516. for( d in dirs ) {
  517. path += d;
  518. safeDir(target+path);
  519. path += "/";
  520. }
  521. if( file == "" ) {
  522. if( path != "" ) print(" Created "+path);
  523. continue; // was just a directory
  524. }
  525. path += file;
  526. print(" Install "+path);
  527. var data = Reader.unzip(zipfile);
  528. File.saveBytes(target+path,data);
  529. }
  530. }
  531. // set current version
  532. if( setcurrent || !FileSystem.exists(pdir+".current") ) {
  533. File.saveContent(pdir + ".current", infos.version.toString());
  534. print(" Current version is now "+infos.version);
  535. }
  536. // end
  537. if( !nodelete )
  538. FileSystem.deleteFile(filepath);
  539. print("Done");
  540. // process dependencies
  541. doInstallDependencies(infos.dependencies);
  542. }
  543. function doInstallDependencies( dependencies:List<{ project: String, version : String }> )
  544. {
  545. for( d in dependencies ) {
  546. print("Installing dependency "+d.project+" "+d.version);
  547. if( d.version == "" )
  548. d.version = site.infos(d.project).curversion;
  549. doInstall(d.project,d.version,false);
  550. }
  551. }
  552. function safeDir( dir ) {
  553. if( FileSystem.exists(dir) ) {
  554. if( !FileSystem.isDirectory(dir) )
  555. throw ("A file is preventing "+dir+" to be created");
  556. }
  557. try {
  558. FileSystem.createDirectory(dir);
  559. } catch( e : Dynamic ) {
  560. throw "You don't have enough user rights to create the directory "+dir;
  561. }
  562. return true;
  563. }
  564. function safeDelete( file ) {
  565. try {
  566. FileSystem.deleteFile(file);
  567. return true;
  568. } catch (e:Dynamic) {
  569. if( Sys.systemName() == "Windows") {
  570. try {
  571. Sys.command("attrib -R \"" +file+ "\"");
  572. FileSystem.deleteFile(file);
  573. return true;
  574. } catch (e:Dynamic) {
  575. }
  576. }
  577. return false;
  578. }
  579. }
  580. function getRepository( ?setup : Bool ) {
  581. var win = Sys.systemName() == "Windows";
  582. var haxepath = Sys.getEnv("HAXEPATH");
  583. if( haxepath != null ) {
  584. var last = haxepath.charAt(haxepath.length - 1);
  585. if( last != "/" && last != "\\" )
  586. haxepath += "/";
  587. }
  588. var config_file;
  589. if( win )
  590. config_file = Sys.getEnv("HOMEDRIVE") + Sys.getEnv("HOMEPATH");
  591. else
  592. config_file = Sys.getEnv("HOME");
  593. config_file += "/.haxelib";
  594. var rep = try
  595. File.getContent(config_file)
  596. catch( e : Dynamic ) try
  597. File.getContent("/etc/.haxelib")
  598. catch( e : Dynamic ) {
  599. if( setup ) {
  600. (win ? haxepath : "/usr/lib/haxe/")+REPNAME;
  601. } else if( win ) {
  602. // Windows have a default directory (no need for setup)
  603. if( haxepath == null )
  604. throw "HAXEPATH environment variable not defined, please run haxesetup.exe first";
  605. var rep = haxepath+REPNAME;
  606. try {
  607. safeDir(rep);
  608. } catch( e : String ) {
  609. throw "Error accessing Haxelib repository: $e";
  610. }
  611. return rep+"\\";
  612. } else
  613. throw "This is the first time you are runing haxelib. Please run `haxelib setup` first";
  614. }
  615. rep = rep.trim();
  616. if( setup ) {
  617. if( args.length <= argcur ) {
  618. print("Please enter haxelib repository path with write access");
  619. print("Hit enter for default (" + rep + ")");
  620. }
  621. var line = param("Path");
  622. if( line != "" )
  623. rep = line;
  624. if( !FileSystem.exists(rep) ) {
  625. try {
  626. FileSystem.createDirectory(rep);
  627. } catch( e : Dynamic ) {
  628. print("Failed to create directory '"+rep+"' ("+Std.string(e)+"), maybe you need appropriate user rights");
  629. print("Check also that the parent directory exists");
  630. Sys.exit(1);
  631. }
  632. }
  633. rep = try FileSystem.fullPath(rep) catch( e : Dynamic ) rep;
  634. File.saveContent(config_file, rep);
  635. } else if( !FileSystem.exists(rep) ) {
  636. throw "haxelib Repository "+rep+" does not exists. Please run `haxelib setup` again";
  637. } else if ( !FileSystem.isDirectory(rep) ) {
  638. throw "haxelib Repository "+rep+" exists, but was a file, not a directory. Please remove it and run `haxelib setup` again.";
  639. }
  640. return rep+"/";
  641. }
  642. function setup() {
  643. var path = getRepository(true);
  644. print("haxelib repository is now "+path);
  645. }
  646. function config() {
  647. print(getRepository());
  648. }
  649. function getCurrent( dir ) {
  650. return (FileSystem.exists(dir+"/.dev")) ? "dev" : File.getContent(dir + "/.current").trim();
  651. }
  652. function getDev( dir ) {
  653. return File.getContent(dir + "/.dev").trim();
  654. }
  655. function list() {
  656. var rep = getRepository();
  657. var folders = FileSystem.readDirectory(rep);
  658. var filter = paramOpt();
  659. if ( filter != null )
  660. folders = folders.filter( function (f) return f.toLowerCase().indexOf(filter.toLowerCase()) > -1 );
  661. for( p in folders ) {
  662. if( p.charAt(0) == "." )
  663. continue;
  664. var versions = new Array();
  665. var current = getCurrent(rep + p);
  666. var dev = try File.getContent(rep+p+"/.dev").trim() catch( e : Dynamic ) null;
  667. for( v in FileSystem.readDirectory(rep+p) ) {
  668. if( v.charAt(0) == "." )
  669. continue;
  670. v = Data.unsafe(v);
  671. if( dev == null && v == current )
  672. v = "["+v+"]";
  673. versions.push(v);
  674. }
  675. if( dev != null )
  676. versions.push("[dev:"+dev+"]");
  677. print(Data.unsafe(p) + ": "+versions.join(" "));
  678. }
  679. }
  680. function upgrade() {
  681. var state = { rep : getRepository(), prompt : true, updated : false };
  682. for( p in FileSystem.readDirectory(state.rep) ) {
  683. if( p.charAt(0) == "." || !FileSystem.isDirectory(state.rep+"/"+p) )
  684. continue;
  685. var p = Data.unsafe(p);
  686. print("Checking " + p);
  687. doUpdate(p,state);
  688. }
  689. if( state.updated )
  690. print("Done");
  691. else
  692. print("All libraries are up-to-date");
  693. }
  694. function doUpdate( p : String, state ) {
  695. var rep = state.rep;
  696. if( FileSystem.exists(rep + "/" + p + "/git") && FileSystem.isDirectory(rep + "/" + p + "/git") ) {
  697. checkGit();
  698. var oldCwd = Sys.getCwd();
  699. Sys.setCwd(rep + "/" + p + "/git");
  700. Sys.command("git pull");
  701. Sys.setCwd(oldCwd);
  702. state.updated = true;
  703. } else {
  704. var inf = try site.infos(p) catch( e : Dynamic ) { Sys.println(e); return; };
  705. if( !FileSystem.exists(rep+Data.safe(p)+"/"+Data.safe(inf.curversion)) ) {
  706. if( state.prompt )
  707. switch ask("Upgrade "+p+" to "+inf.curversion) {
  708. case Yes:
  709. case Always: state.prompt = false;
  710. case No:
  711. return;
  712. }
  713. doInstall(p,inf.curversion,true);
  714. state.updated = true;
  715. } else
  716. setCurrent(p, inf.curversion, true);
  717. }
  718. }
  719. function updateByName(prj:String) {
  720. var state = { rep : getRepository(), prompt : false, updated : false };
  721. doUpdate(prj,state);
  722. return state.updated;
  723. }
  724. function update() {
  725. var prj = param('Library');
  726. if (!updateByName(prj))
  727. print(prj + " is up to date");
  728. }
  729. function updateSelf() {
  730. function tryBuild() {
  731. var p = new Process('haxe', ['-neko', 'test.n', '-lib', 'haxelib_client', '-main', 'tools.haxelib.Main', '--no-output']);
  732. return
  733. if (p.exitCode() == 0) None;
  734. else Some(p.stderr.readAll().toString());
  735. }
  736. if (!updateByName('haxelib_client'))
  737. print("haxelib is up to date");
  738. switch tryBuild() {
  739. case None:
  740. var win = Sys.systemName() == "Windows";
  741. var haxepath =
  742. if (win) Sys.getEnv("HAXEPATH");
  743. else new Path(new Process('which', ['haxelib']).stdout.readAll().toString()).dir + '/';
  744. if (haxepath == null)
  745. throw (win ? 'HAXEPATH environment variable not defined' : 'unable to locate haxelib through `which haxelib`');
  746. else
  747. haxepath +=
  748. switch (haxepath.charAt(haxepath.length - 1)) {
  749. case '/', '\\': '';
  750. default: '/';
  751. }
  752. if (win) {
  753. File.saveContent('update.hxml', '-lib haxelib_client\n--run tools.haxelib.Rebuild');
  754. Sys.println('Please run haxe update.hxml');
  755. }
  756. else {
  757. var p = new Process('haxelib', ['path', 'haxelib_client']);
  758. if (p.exitCode() == 0) {
  759. var args = [];
  760. for (arg in p.stdout.readAll().toString().split('\n')) {
  761. arg = arg.trim();
  762. if (arg.charAt(0) == '-')
  763. args.push(arg);
  764. else if (arg.length > 0)
  765. args.push('-cp "$arg"');
  766. };
  767. var file = haxepath+'haxelib';
  768. try File.saveContent(
  769. file,
  770. '#!/bin/sh\nexec haxe '+args.join(' ')+' --run tools.haxelib.Main "$@"'
  771. )
  772. catch (e:Dynamic)
  773. throw 'Error writing file $file. Please ensure you have write permissions. \n ' + Std.string(e);
  774. }
  775. else throw p.stdout.readAll();
  776. }
  777. case Some(error):
  778. throw 'Error compiling haxelib client: $error';
  779. }
  780. }
  781. function deleteRec(dir) {
  782. for( p in FileSystem.readDirectory(dir) ) {
  783. var path = dir+"/"+p;
  784. if( FileSystem.isDirectory(path) )
  785. deleteRec(path);
  786. else
  787. safeDelete(path);
  788. }
  789. FileSystem.deleteDirectory(dir);
  790. }
  791. function remove() {
  792. var prj = param("Library");
  793. var version = paramOpt();
  794. var rep = getRepository();
  795. var pdir = rep + Data.safe(prj);
  796. if( version == null ) {
  797. if( !FileSystem.exists(pdir) )
  798. throw "Library "+prj+" is not installed";
  799. deleteRec(pdir);
  800. print("Library "+prj+" removed");
  801. return;
  802. }
  803. var vdir = pdir + "/" + Data.safe(version);
  804. if( !FileSystem.exists(vdir) )
  805. throw "Library "+prj+" does not have version "+version+" installed";
  806. var cur = getCurrent(pdir);
  807. if( cur == version )
  808. throw "Can't remove current version of library "+prj;
  809. deleteRec(vdir);
  810. print("Library "+prj+" version "+version+" removed");
  811. }
  812. function set() {
  813. var prj = param("Library");
  814. var version = param("Version");
  815. setCurrent(prj,version,false);
  816. }
  817. function setCurrent( prj : String, version : String, doAsk : Bool ) {
  818. var pdir = getRepository() + Data.safe(prj);
  819. var vdir = pdir + "/" + Data.safe(version);
  820. if( !FileSystem.exists(vdir) )
  821. throw "Library "+prj+" version "+version+" is not installed";
  822. if( getCurrent(pdir) == version )
  823. return;
  824. if( doAsk && ask("Set "+prj+" to version "+version) == No )
  825. return;
  826. File.saveContent(pdir+"/.current",version);
  827. print("Library "+prj+" current version is now "+version);
  828. }
  829. function checkRec( prj : String, version : String, l : List<{ project : String, version : String }> ) {
  830. var pdir = getRepository() + Data.safe(prj);
  831. if( !FileSystem.exists(pdir) )
  832. throw "Library "+prj+" is not installed : run 'haxelib install "+prj+"'";
  833. var version = if( version != null ) version else getCurrent(pdir);
  834. var vdir = pdir + "/" + Data.safe(version);
  835. if( vdir.endsWith("dev") )
  836. vdir = getDev(pdir);
  837. if( !FileSystem.exists(vdir) )
  838. throw "Library "+prj+" version "+version+" is not installed";
  839. for( p in l )
  840. if( p.project == prj ) {
  841. if( p.version == version )
  842. return;
  843. throw "Library "+prj+" has two version included "+version+" and "+p.version;
  844. }
  845. l.add({ project : prj, version : version });
  846. var json = try File.getContent(vdir+"/"+Data.JSON) catch( e : Dynamic ) null;
  847. if( json == null )
  848. return; // ignore missing haxelib.json, assume no dependencies
  849. var inf = Data.readData(json,false);
  850. for( d in inf.dependencies )
  851. checkRec(d.project,if( d.version == "" ) null else d.version,l);
  852. }
  853. function path() {
  854. var list = new List();
  855. while( argcur < args.length ) {
  856. var a = args[argcur++].split(":");
  857. checkRec(a[0],a[1],list);
  858. }
  859. var rep = getRepository();
  860. for( d in list ) {
  861. var pdir = Data.safe(d.project)+"/"+Data.safe(d.version)+"/";
  862. var dir = rep + pdir;
  863. try {
  864. dir = getDev(rep+Data.safe(d.project));
  865. if( dir.length == 0 || (dir.charAt(dir.length-1) != '/' && dir.charAt(dir.length-1) != '\\') )
  866. dir += "/";
  867. pdir = dir;
  868. } catch( e : Dynamic ) {
  869. }
  870. var ndir = dir + "ndll";
  871. if( FileSystem.exists(ndir) ) {
  872. var sysdir = ndir+"/"+Sys.systemName();
  873. var is64 = neko.Lib.load("std", "sys_is64", 0)();
  874. if( is64 ) sysdir += "64";
  875. if( !FileSystem.exists(sysdir) )
  876. throw "Library "+d.project+" version "+d.version+" does not have a neko dll for your system";
  877. Sys.println("-L "+pdir+"ndll/");
  878. }
  879. try {
  880. var f = File.getContent(dir + "extraParams.hxml");
  881. Sys.println(f.trim());
  882. } catch( e : Dynamic ) {
  883. }
  884. Sys.println(dir);
  885. Sys.println("-D "+d.project);
  886. }
  887. }
  888. function dev() {
  889. var rep = getRepository();
  890. var project = param("Library");
  891. var dir = paramOpt();
  892. var proj = rep + Data.safe(project);
  893. if( !FileSystem.exists(proj) ) {
  894. FileSystem.createDirectory(proj);
  895. File.saveContent(proj + "/.current", "dev");
  896. }
  897. var devfile = proj+"/.dev";
  898. if( dir == null ) {
  899. if( FileSystem.exists(devfile) )
  900. FileSystem.deleteFile(devfile);
  901. print("Development directory disabled");
  902. } else {
  903. dir = try FileSystem.fullPath(dir)+"/" catch( e : Dynamic ) rep;
  904. try {
  905. File.saveContent(devfile, dir);
  906. print("Development directory set to "+dir);
  907. try {
  908. // Check for haxelib.json, install dependencies
  909. var haxelibJsonPath = dir + "haxelib.json";
  910. if (FileSystem.exists(haxelibJsonPath))
  911. {
  912. var haxelibJson = File.getContent(haxelibJsonPath);
  913. var infos = Data.readData(haxelibJson,true);
  914. doInstallDependencies(infos.dependencies);
  915. }
  916. }
  917. catch (e:Dynamic) {
  918. print('Error installing dependencies for $project:\n $e');
  919. }
  920. }
  921. catch (e:Dynamic) {
  922. print("Could not write to " +proj + "/.dev");
  923. }
  924. }
  925. }
  926. function checkGit() {
  927. var gitExists = function()
  928. try { command("git", []); return true; } catch (e:Dynamic) return false;
  929. if( gitExists() )
  930. return;
  931. // if we have already msys git/cmd in our PATH
  932. var match = ~/(.*)git([\\|\/])cmd$/ ;
  933. for (path in Sys.getEnv("PATH").split(";")) {
  934. if (match.match(path.toLowerCase()))
  935. {
  936. var newPath = match.matched(1) + "git" +match.matched(2) + "bin";
  937. Sys.putEnv("PATH", Sys.getEnv("PATH") + ";" +newPath);
  938. }
  939. }
  940. if( gitExists() )
  941. return;
  942. // look at a few default paths
  943. for( path in ["C:\\Program Files (x86)\\Git\\bin","C:\\Progra~1\\Git\\bin"] )
  944. if( FileSystem.exists(path) ) {
  945. Sys.putEnv("PATH", Sys.getEnv("PATH") + ";" +path);
  946. if( gitExists() )
  947. return;
  948. }
  949. print("Could not execute git, please make sure it is installed and available in your PATH.");
  950. }
  951. function git() {
  952. var libName = param("Library name");
  953. var rep = getRepository();
  954. var libPath = rep + Data.safe(libName) + "/git";
  955. if( FileSystem.exists(libPath) ) {
  956. var state = { rep : rep, prompt : false, updated : false };
  957. doUpdate(libName,state);
  958. if( !state.updated )
  959. print("You already have a git version of "+libName+" installed");
  960. return;
  961. }
  962. var gitPath = param("Git path");
  963. var branch = paramOpt();
  964. var subDir = paramOpt();
  965. print("Installing " +libName + " from " +gitPath);
  966. checkGit();
  967. if( Sys.command("git clone \"" +gitPath + "\" \"" +libPath + "\"") != 0 ) {
  968. print("Could not clone git repository");
  969. return;
  970. }
  971. Sys.setCwd(libPath);
  972. if (branch != null) {
  973. var ret = command("git", ["checkout", branch]);
  974. if (ret.code != 0)
  975. {
  976. print("Could not checkout branch, tag or path: " +ret.out);
  977. // TODO: We might have to get rid of the cloned repository here
  978. return;
  979. }
  980. }
  981. var revision = command("git", ["rev-parse", "HEAD"]).out;
  982. var devPath = libPath + (subDir == null ? "" : "/" + subDir);
  983. var haxelibJsonPath = devPath + "/haxelib.json";
  984. var haxelibJson:String;
  985. if (FileSystem.exists(haxelibJsonPath))
  986. {
  987. haxelibJson = File.getContent(haxelibJsonPath);
  988. }
  989. else
  990. {
  991. haxelibJson = '{
  992. "name": "$libName",
  993. "url" : "$gitPath",
  994. "license": "",
  995. "tags": [],
  996. "description": "",
  997. "version": "0.0.0",
  998. "releasenote": "Updated from git.",
  999. "contributors": [],
  1000. "dependencies": {}
  1001. }';
  1002. File.saveContent(haxelibJsonPath, haxelibJson);
  1003. }
  1004. var infos = Data.readData(haxelibJson,true);
  1005. doInstallDependencies(infos.dependencies);
  1006. Sys.setCwd(libPath + "/../");
  1007. File.saveContent(".current", "dev");
  1008. File.saveContent(".dev", devPath);
  1009. print("Done");
  1010. }
  1011. function run() {
  1012. var rep = getRepository();
  1013. var project = param("Library");
  1014. var temp = project.split(":");
  1015. project = temp[0];
  1016. var pdir = rep + Data.safe(project);
  1017. if( !FileSystem.exists(pdir) )
  1018. throw "Library "+project+" is not installed";
  1019. pdir += "/";
  1020. var version = temp[1] != null ? temp[1] : getCurrent(pdir);
  1021. var dev = try getDev(pdir) catch ( e : Dynamic ) null;
  1022. var vdir = dev!=null ? dev : pdir + Data.safe(version);
  1023. var rdir = vdir + "/run.n";
  1024. if( !FileSystem.exists(rdir) )
  1025. throw "Library "+project+" version "+version+" does not have a run script";
  1026. args.push(Sys.getCwd());
  1027. Sys.setCwd(vdir);
  1028. var cmd = "neko run.n";
  1029. for( i in argcur...args.length )
  1030. cmd += " "+escapeArg(args[i]);
  1031. Sys.exit(Sys.command(cmd));
  1032. }
  1033. function escapeArg( a : String ) {
  1034. if( a.indexOf(" ") == -1 )
  1035. return a;
  1036. return '"'+a+'"';
  1037. }
  1038. function local() {
  1039. var file = param("Package");
  1040. doInstallFile(file,true,true);
  1041. }
  1042. function command( cmd:String, args:Array<String> ) {
  1043. var p = new sys.io.Process(cmd, args);
  1044. var code = p.exitCode();
  1045. return { code:code, out: code == 0 ? p.stdout.readAll().toString() : p.stderr.readAll().toString() };
  1046. }
  1047. function proxy() {
  1048. var rep = getRepository();
  1049. var host = param("Proxy host");
  1050. if( host == "" ) {
  1051. if( FileSystem.exists(rep + "/.proxy") ) {
  1052. FileSystem.deleteFile(rep + "/.proxy");
  1053. print("Proxy disabled");
  1054. } else
  1055. print("No proxy specified");
  1056. return;
  1057. }
  1058. var port = Std.parseInt(param("Proxy port"));
  1059. var authName = param("Proxy user login");
  1060. var authPass = authName == "" ? "" : param("Proxy user pass");
  1061. var proxy = {
  1062. host : host,
  1063. port : port,
  1064. auth : authName == "" ? null : { user : authName, pass : authPass },
  1065. };
  1066. Http.PROXY = proxy;
  1067. print("Testing proxy...");
  1068. try Http.requestUrl("http://www.google.com") catch( e : Dynamic ) {
  1069. print("Proxy connection failed");
  1070. return;
  1071. }
  1072. File.saveContent(rep + "/.proxy", haxe.Serializer.run(proxy));
  1073. print("Proxy setup done");
  1074. }
  1075. function loadProxy() {
  1076. var rep = getRepository();
  1077. try Http.PROXY = haxe.Unserializer.run(File.getContent(rep + "/.proxy")) catch( e : Dynamic ) { };
  1078. }
  1079. function convertXml() {
  1080. var cwd = Sys.getCwd();
  1081. var xmlFile = cwd + "haxelib.xml";
  1082. var jsonFile = cwd + "haxelib.json";
  1083. if (!FileSystem.exists(xmlFile))
  1084. {
  1085. print('No `haxelib.xml` file was found in the current directory.');
  1086. Sys.exit(0);
  1087. }
  1088. var xmlString = File.getContent(xmlFile);
  1089. var json = convert(xmlString);
  1090. var jsonString = prettyPrint(json);
  1091. File.saveContent(jsonFile, jsonString);
  1092. print('Saved to $jsonFile');
  1093. }
  1094. function convert(inXml:String) {
  1095. // Set up the default JSON structure
  1096. var json = {
  1097. "name": "",
  1098. "url" : "",
  1099. "license": "",
  1100. "tags": [],
  1101. "description": "",
  1102. "version": "0.0.1",
  1103. "releasenote": "",
  1104. "contributors": [],
  1105. "dependencies": {}
  1106. };
  1107. // Parse the XML and set the JSON
  1108. var xml = Xml.parse(inXml);
  1109. var project = xml.firstChild();
  1110. json.name = project.get("name");
  1111. json.license = project.get("license");
  1112. json.url = project.get("url");
  1113. for (node in project)
  1114. {
  1115. switch (node.nodeType)
  1116. {
  1117. case Xml.Element:
  1118. switch (node.nodeName)
  1119. {
  1120. case "tag":
  1121. json.tags.push(node.get("v"));
  1122. case "user":
  1123. json.contributors.push(node.get("name"));
  1124. case "version":
  1125. json.version = node.get("name");
  1126. json.releasenote = node.firstChild().toString();
  1127. case "description":
  1128. json.description = node.firstChild().toString();
  1129. case "depends":
  1130. var name = node.get("name");
  1131. var version = node.get("version");
  1132. if (version == null) version = "";
  1133. Reflect.setField(json.dependencies, name, version);
  1134. default:
  1135. }
  1136. default:
  1137. }
  1138. }
  1139. return json;
  1140. }
  1141. function prettyPrint(json:Dynamic, indent="")
  1142. {
  1143. var sb = new StringBuf();
  1144. sb.add("{\n");
  1145. var firstRun = true;
  1146. for (f in Reflect.fields(json))
  1147. {
  1148. if (!firstRun) sb.add(",\n");
  1149. firstRun = false;
  1150. var value = switch (f) {
  1151. case "dependencies":
  1152. var d = Reflect.field(json, f);
  1153. prettyPrint(d, indent + " ");
  1154. default:
  1155. Json.stringify(Reflect.field(json, f));
  1156. }
  1157. sb.add(indent+' "$f": $value');
  1158. }
  1159. sb.add('\n$indent}');
  1160. return sb.toString();
  1161. }
  1162. // ----------------------------------
  1163. static function print(str) {
  1164. Sys.print(str+"\n");
  1165. }
  1166. static function main() {
  1167. new Main().process();
  1168. }
  1169. }