UNPKG

1.96 kBJavaScriptView Raw
1// @flow
2
3const fs = require('fs');
4
5/*::
6type PackageRepositoryDetails = string | {
7 type: string,
8 url: string
9};
10
11type PackageData = {
12 author: string,
13 license: ?string,
14 name: string,
15 private: boolean,
16 repository: PackageRepositoryDetails
17};
18
19type Repository = {
20 host: string,
21 path: string
22};
23*/
24
25const REPO_REGEXES = [
26 /^.*(github\.com)\/(.*)\.git.*$/, // github
27 /^.*(bitbucket\.org)\/(.*)\.git.*$/ // bitbucket
28];
29
30class Package {
31 /*::
32 author: string;
33 license: ?string;
34 name: string;
35 private: boolean;
36 repository: PackageRepositoryDetails;
37 */
38
39 constructor(data /*: PackageData */) {
40 this.author = data.author;
41 this.license = data.license;
42 this.name = data.name;
43 this.private = data.private;
44 this.repository = data.repository;
45 }
46
47 static deserialize(json) /*: Package */ {
48 const repository = json.repository;
49
50 return new Package({
51 author: json.author,
52 license: json.license,
53 name: json.name,
54 private: json.private || false,
55 repository: repository
56 });
57 }
58
59 static readFromFile(filename /*: string */) /*: Promise<Package> */ {
60 return new Promise((resolve, reject) => {
61 fs.readFile(filename, 'utf-8', (err, content) => {
62 if (err) {
63 return reject(err);
64 }
65
66 try {
67 resolve(Package.deserialize(JSON.parse(content)));
68 } catch (e) {
69 reject(e);
70 }
71 });
72 });
73 }
74
75 getRepositry() /*: ?Repository */ {
76 const url = this.getRepositoryUrl();
77 const match = REPO_REGEXES.reduce(function(memo, regex) {
78 return memo || regex.exec(url);
79 }, false);
80
81 return match ? {
82 host: match[1],
83 path: match[2].split('/').splice(0, 2).join('/')
84 } : null;
85 }
86
87 getRepositoryUrl() /*: string */ {
88 if (typeof this.repository == 'string') {
89 return this.repository;
90 }
91
92 return (this.repository || {}).url;
93 }
94}
95
96module.exports = {
97 Package
98};