forked from teambit/bit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope-json.js
106 lines (89 loc) · 2.62 KB
/
scope-json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/** @flow */
import pathlib from 'path';
import { writeFile, cleanObject, readFile, existsSync } from '../utils';
import { Remote } from '../remotes';
import { SCOPE_JSON } from '../constants';
export function getPath(scopePath: string): string {
return pathlib.join(scopePath, SCOPE_JSON);
}
export type ScopeJsonProps = {
name: string,
resolverPath?: string,
license?: string,
groupName: ?string;
remotes?: { name: string, url: string };
};
export class ScopeJson {
_name: string;
resolverPath: ?string;
license: string;
remotes: {[string]: string};
groupName: string;
constructor({ name, remotes, resolverPath, license, groupName }: ScopeJsonProps) {
this.name = name;
this.resolverPath = resolverPath;
this.license = license;
this.remotes = remotes || {};
this.groupName = groupName || '';
}
set name(suggestedName: string) {
suggestedName = suggestedName.toLowerCase();
const cleanName = suggestedName.split('')
.map((char) => {
if (/^[$\-_!.a-z0-9]+$/.test(char)) return char;
return '';
}).join('');
if (!cleanName) {
throw new Error('scope name created by directory name have to contains at least one charecter or number');
}
this._name = cleanName;
return this;
}
get name(): string {
return this._name;
}
toPlainObject() {
return cleanObject({
name: this.name,
remotes: this.remotes,
resolverPath: this.resolverPath,
license: this.license,
groupName: this.groupName
});
}
toJson(readable: boolean = true) {
if (!readable) return JSON.stringify(this.toPlainObject());
return JSON.stringify(this.toPlainObject(), null, 4);
}
set(key: string, val: string) {
if (!this.hasOwnProperty(key)) throw `unknown key ${key}`;
this[key] = val;
return this;
}
get(key: string) : string{
if (!this.hasOwnProperty(key)) throw `unknown key ${key}`;
return this[key];
}
del(key: string) : string{
if (!this.hasOwnProperty(key)) throw `unknown key ${key}`;
return this[key];
}
addRemote(remote: Remote) {
this.remotes[remote.name] = remote.host;
return this;
}
rmRemote(name: string) {
delete this.remotes[name];
return this;
}
write(path: string) {
return writeFile(pathlib.join(path, SCOPE_JSON), this.toJson());
}
static loadFromJson(json: string) {
return new ScopeJson(JSON.parse(json));
}
getPopulatedLicense() : Promise<string> {
if (!this.get('license') || !existsSync(this.get('license'))) return Promise.resolve();
return readFile(this.get('license')).then(license => license.toString());
}
}