Debian Codegraph @

extra/haxelib_src/src/haxelib/Data.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;
23
24 import haxe.CallStack;
25 import haxe.ds.Option;
26 import haxe.ds.*;
27 import haxe.zip.Reader;
28 import haxe.zip.Entry;
29 import haxe.Json;
30 import haxelib.Validator;
31
32 using StringTools;
33
34 typedef UserInfos = {
35 var name : String;
36 var fullname : String;
37 var email : String;
38 var projects : Array<String>;
39 }
40
41 typedef VersionInfos = {
42 var date : String;
43 var name : SemVer;//TODO: this should eventually be called `number`
44 var downloads : Int;
45 var comments : String;
46 }
47
48 typedef ProjectInfos = {
49 var name : String;
50 var desc : String;
51 var website : String;
52 var owner : String;
53 var contributors : Array<{ name:String, fullname:String }>;
54 var license : String;
55 var curversion : String;
56 var downloads : Int;
57 var versions : Array<VersionInfos>;
58 var tags : List<String>;
59 }
60
61 @:enum abstract CheckLevel(Int) {
62 var NoCheck = 0;
63 var CheckSyntax = 1;
64 var CheckData = 2;
65
66 @:from static inline function fromBool(check:Bool):CheckLevel {
67 return check ? CheckData : NoCheck;
68 }
69
70 @:op(A > B) function gt(b:CheckLevel):Bool;
71 @:op(A >= B) function gte(b:CheckLevel):Bool;
72 @:op(A == B) function eq(b:CheckLevel):Bool;
73 @:op(A <= B) function lte(b:CheckLevel):Bool;
74 @:op(A < B) function lt(b:CheckLevel):Bool;
75 }
76
77 abstract DependencyVersion(String) to String from SemVer {
78 inline function new(s:String)
79 this = s;
80
81 @:to function toValidatable():Validatable
82 return
83 if (this == '' || this == 'git' || (Std.is(this, String) && this.startsWith('git:')))
84 { validate: function () return None }
85 else
86 @:privateAccess new SemVer(this);
87
88 static public function isValid(s:String)
89 return new DependencyVersion(s).toValidatable().validate() == None;
90
91 static public var DEFAULT(default, null) = new DependencyVersion('');
92 static public var GIT(default, null) = new DependencyVersion('git');
93 }
94
95 abstract Dependencies(Dynamic<DependencyVersion>) from Dynamic<DependencyVersion> {
96 @:to public function toArray():Array<Dependency> {
97 var fields = Reflect.fields(this);
98 fields.sort(Reflect.compare);
99
100 var result:Array<Dependency> = new Array<Dependency>();
101
102 for (f in fields) {
103 var value:String = Reflect.field(this, f);
104
105 var isGit = value != null && (value + "").startsWith("git:");
106
107 if ( !isGit )
108 {
109 result.push ({
110 name: f,
111 type: (DependencyType.Haxelib : DependencyType),
112 version: (cast value : DependencyVersion),
113 url: (null : String),
114 subDir: (null : String),
115 branch: (null : String),
116 });
117 }
118 else
119 {
120 value = value.substr(4);
121 var urlParts = value.split("#");
122 var url = urlParts[0];
123 var branch = urlParts.length > 1 ? urlParts[1] : null;
124
125 result.push ({
126 name: f,
127 type: (DependencyType.Git : DependencyType),
128 version: (DependencyVersion.DEFAULT : DependencyVersion),
129 url: (url : String),
130 subDir: (null : String),
131 branch: (branch : String),
132 });
133 }
134
135
136 }
137
138 return result;
139 }
140 public inline function iterator()
141 return toArray().iterator();
142 }
143
144 @:enum abstract DependencyType(String) {
145 var Haxelib = null;
146 var Git = 'git';
147 var Mercurial = 'hg';
148 }
149
150 typedef Dependency = {
151 name : String,
152 ?version : DependencyVersion,
153 ?type: DependencyType,
154 ?url: String,
155 ?subDir: String,
156 ?branch: String,
157 }
158
159 typedef Infos = {
160 // IMPORTANT: if you change this or its fields types,
161 // make sure to update `schema.json` file accordingly,
162 // and make an update PR to https://github.com/SchemaStore/schemastore
163 var name : ProjectName;
164 @:optional var url : String;
165 @:optional var description : String;
166 var license : License;
167 var version : SemVer;
168 @:optional var classPath : String;
169 var releasenote : String;
170 @:requires('Specify at least one contributor' => _.length > 0)
171 var contributors : Array<String>;
172 @:optional var tags : Array<String>;
173 @:optional var dependencies : Dependencies;
174 @:optional var main : String;
175 @:optional var documentation : LibraryDocumentation;
176 }
177
178 /** Documentation data held in the `documentation` field of the `haxelib.json` file. **/
179 typedef LibraryDocumentation = {
180 @:optional var defines : String;
181 @:optional var metadata : String;
182 }
183
184 /** Metadata documentation data as should be declared in the json linked in the
185 * `documentation.metadata` field of the `haxelib.json` file. **/
186 typedef MetadataDocumentation = {
187 var metadata : String;
188 var doc : String;
189 @:optional var platforms : Array<String>;
190 @:optional var params : Array<String>;
191 @:optional var targets : Array<String>;
192 @:optional var links : Array<String>;
193 }
194
195 /** Define documentation data as should be declared in the json linked in the
196 * `documentation.defines` field of the `haxelib.json` file. **/
197 typedef DefineDocumentation = {
198 var define : String;
199 var doc : String;
200 @:optional var platforms : Array<String>;
201 @:optional var params : Array<String>;
202 @:optional var links : Array<String>;
203 }
204
205 @:enum abstract License(String) to String {
206 var Gpl = 'GPL';
207 var Lgpl = 'LGPL';
208 var Mit = 'MIT';
209 var Bsd = 'BSD';
210 var Public = 'Public';
211 var Apache = 'Apache';
212 }
213
214 abstract ProjectName(String) to String {
215 static var RESERVED_NAMES = ["haxe", "all"];
216 static var RESERVED_EXTENSIONS = ['.zip', '.hxml'];
217 inline function new(s:String)
218 this = s;
219
220 @:to function toValidatable():Validatable
221 return {
222 validate:
223 function ():Option<String> {
224 for (r in rules)
225 if (!r.check(this))
226 return Some(r.msg.replace('%VALUE', '`' + Json.stringify(this) + '`'));
227 return None;
228 }
229 }
230
231 static var rules = {//using an array because order might matter
232 var a = new Array<{ msg: String, check:String->Bool }>();
233
234 function add(m, r)
235 a.push( { msg: m, check: r } );
236
237 add("%VALUE is not a String", Std.is.bind(_, String));
238 add("%VALUE is too short", function (s) return s.length >= 3);
239 add("%VALUE contains invalid characters", Data.alphanum.match);
240 add("%VALUE is a reserved name", function(s) return RESERVED_NAMES.indexOf(s.toLowerCase()) == -1);
241 add("%VALUE ends with a reserved suffix", function(s) {
242 s = s.toLowerCase();
243 for (ext in RESERVED_EXTENSIONS)
244 if (s.endsWith(ext)) return false;
245 return true;
246 });
247
248 a;
249 }
250
251 public function validate()
252 return toValidatable().validate();
253
254 static public function ofString(s:String)
255 return switch new ProjectName(s) {
256 case _.toValidatable().validate() => Some(e): throw e;
257 case v: v;
258 }
259
260 static public var DEFAULT(default, null) = new ProjectName('unknown');
261 }
262
263 class Data {
264
265 public static var JSON(default, null) = "haxelib.json";
266 public static var DOCXML(default, null) = "haxedoc.xml";
267 public static var REPOSITORY(default, null) = "files/3.0";
268 public static var alphanum(default, null) = ~/^[A-Za-z0-9_.-]+$/;
269
270
271 public static function safe( name : String ) {
272 if( !alphanum.match(name) )
273 throw "Invalid parameter : "+name;
274 return name.split(".").join(",");
275 }
276
277 public static function unsafe( name : String ) {
278 return name.split(",").join(".");
279 }
280
281 public static function fileName( lib : String, ver : String ) {
282 return safe(lib)+"-"+safe(ver)+".zip";
283 }
284
285 static public function getLatest(info:ProjectInfos, ?preview:SemVer.Preview->Bool):Null<SemVer> {
286 if (info.versions.length == 0) return null;
287 if (preview == null)
288 preview = function (p) return p == null;
289
290 var versions = info.versions.copy();
291 versions.sort(function (a, b) return -SemVer.compare(a.name, b.name));
292
293 for (v in versions)
294 if (preview(v.name.preview)) return v.name;
295
296 return versions[0].name;
297 }
298
299 /**
300 Return the directory that contains *haxelib.json*.
301 If it is at the root, `""`.
302 If it is in a folder, the path including a trailing slash is returned.
303 */
304 public static function locateBasePath( zip : List<Entry> ):String {
305 var f = getJson(zip);
306 return f.fileName.substr(0, f.fileName.length - JSON.length);
307 }
308
309 static function getJson(zip:List<Entry>)
310 return switch topmost(zip, fileNamed(JSON)) {
311 case Some(f): f;
312 default: throw 'No $JSON found';
313 }
314
315 static function fileNamed(name:String)
316 return function (f:Entry) return f.fileName.endsWith(name);
317
318 static function topmost(zip:List<Entry>, predicate:Entry->Bool):Option<Entry> {
319 var best:Entry = null,
320 bestDepth = 0xFFFF;
321
322 for (f in zip)
323 if (predicate(f)) {
324 var depth = f.fileName.replace('\\', '/').split('/').length;//TODO: consider Path.normalize
325 if ((depth == bestDepth && f.fileName < best.fileName) || depth < bestDepth) {
326 best = f;
327 bestDepth = depth;
328 }
329 }
330
331 return
332 if (best == null)
333 None;
334 else
335 Some(best);
336 }
337
338 public static function readDoc( zip : List<Entry> ) : Null<String>
339 return switch topmost(zip, fileNamed(DOCXML)) {
340 case Some(f): Reader.unzip(f).toString();
341 case None: null;
342 }
343
344
345 public static function readInfos( zip : List<Entry>, check : CheckLevel ) : Infos
346 return readData(Reader.unzip(getJson(zip)).toString(), check);
347
348 public static function checkClassPath( zip : List<Entry>, infos : Infos ) {
349 if ( infos.classPath != "" ) {
350 var basePath = Data.locateBasePath(zip);
351 var cp = basePath + infos.classPath;
352
353 for( f in zip ) {
354 if( StringTools.startsWith(f.fileName,cp) )
355 return;
356 }
357 throw 'Class path `${infos.classPath}` not found';
358 }
359 }
360
361 /** Throws an exception if files referenced in `documentation` field of an `infos` do not exist or are invalid **/
362 public static function checkDocumentation( zip : List<Entry>, infos : Infos ) {
363 if (infos.documentation == null) return;
364
365 var hasDefines = infos.documentation.defines != null;
366 var hasMetadata = infos.documentation.metadata != null;
367 if (!hasDefines && !hasMetadata) return;
368
369 var basePath = Data.locateBasePath(zip);
370 var definesPath = hasDefines ? basePath + infos.documentation.defines : null;
371 var metadataPath = hasMetadata ? basePath + infos.documentation.metadata : null;
372 var definesFound = false;
373 var metadataFound = false;
374
375 for (f in zip) {
376 if (hasDefines && StringTools.startsWith(f.fileName, definesPath)) {
377 definesFound = true;
378 try {
379 var jsondata = Reader.unzip(f).toString();
380 var defines:Array<DefineDocumentation> = Json.parse(jsondata);
381 Validator.validate(defines);
382 } catch (_:Dynamic) {
383 throw 'Defines documentation json file does not match expected format';
384 }
385 } else if (hasMetadata && StringTools.startsWith(f.fileName, metadataPath)) {
386 metadataFound = true;
387 try {
388 var jsondata = Reader.unzip(f).toString();
389 var metas:Array<MetadataDocumentation> = Json.parse(jsondata);
390 Validator.validate(metas);
391 } catch (_:Dynamic) {
392 throw 'Metadata documentation json file does not match expected format';
393 }
394 }
395
396 if ((!hasDefines || definesFound) && (!hasMetadata || metadataFound)) break;
397 }
398
399 if (hasDefines && !definesFound) throw 'Json file `${infos.documentation.defines}` not found';
400 if (hasMetadata && !metadataFound) throw 'Json file `${infos.documentation.metadata}` not found';
401 }
402
403 public static function readData( jsondata: String, check : CheckLevel ) : Infos {
404 var doc:Infos =
405 try Json.parse(jsondata)
406 catch ( e : Dynamic )
407 if (check >= CheckLevel.CheckSyntax)
408 throw 'JSON parse error: $e';
409 else {
410 name : ProjectName.DEFAULT,
411 url : '',
412 version : SemVer.DEFAULT,
413 releasenote: 'No haxelib.json found',
414 license: Mit,
415 description: 'No haxelib.json found',
416 contributors: [],
417 }
418
419 if (check >= CheckLevel.CheckData)
420 Validator.validate(doc);
421 else {
422 if (!doc.version.valid)
423 doc.version = SemVer.DEFAULT;
424 }
425
426 //TODO: we have really weird ways to go about nullability and defaults
427
428 if (doc.dependencies == null)
429 doc.dependencies = {};
430
431 for (dep in doc.dependencies)
432 if (!DependencyVersion.isValid(dep.version))
433 Reflect.setField(doc.dependencies, dep.name, DependencyVersion.DEFAULT);//TODO: this is pure evil
434
435 if (doc.classPath == null)
436 doc.classPath = '';
437
438 if (doc.name.validate() != None)
439 doc.name = ProjectName.DEFAULT;
440
441 if (doc.description == null)
442 doc.description = '';
443
444 if (doc.tags == null)
445 doc.tags = [];
446
447 if (doc.url == null)
448 doc.url = '';
449
450 return doc;
451 }
452 }