-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathproject-service.ts
296 lines (262 loc) · 8.07 KB
/
project-service.ts
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import * as constants from "../constants";
import * as path from "path";
import simpleGit, { SimpleGit } from "simple-git";
import { exported } from "../common/decorators";
import { Hooks } from "../constants";
import { performanceLog } from "../common/decorators";
import {
IProjectService,
IProjectDataService,
IProjectTemplatesService,
ICreateProjectData,
IProjectSettings,
IProjectCreationSettings,
ITemplateData,
IProjectConfigService,
} from "../definitions/project";
import {
INodePackageManager,
IOptions,
IProjectNameService,
IStaticConfig,
} from "../declarations";
import {
IHooksService,
IErrors,
IFileSystem,
IProjectHelper,
IChildProcess,
} from "../common/declarations";
import * as _ from "lodash";
import { injector } from "../common/yok";
import { ITempService } from "../definitions/temp-service";
export class ProjectService implements IProjectService {
constructor(
private $options: IOptions,
private $hooksService: IHooksService,
private $packageManager: INodePackageManager,
private $errors: IErrors,
private $fs: IFileSystem,
private $logger: ILogger,
private $pacoteService: IPacoteService,
private $projectDataService: IProjectDataService,
private $projectConfigService: IProjectConfigService,
private $projectHelper: IProjectHelper,
private $projectNameService: IProjectNameService,
private $projectTemplatesService: IProjectTemplatesService,
private $tempService: ITempService,
private $staticConfig: IStaticConfig,
private $childProcess: IChildProcess
) {}
public async validateProjectName(opts: {
projectName: string;
force: boolean;
pathToProject: string;
}): Promise<string> {
let projectName = opts.projectName;
if (!projectName) {
this.$errors.failWithHelp(
"You must specify <App name> when creating a new project."
);
}
projectName = await this.$projectNameService.ensureValidName(projectName, {
force: opts.force,
});
const projectDir = this.getValidProjectDir(opts.pathToProject, projectName);
if (this.$fs.exists(projectDir) && !this.$fs.isEmptyDir(projectDir)) {
this.$errors.fail("Path already exists and is not empty %s", projectDir);
}
return projectName;
}
@exported("projectService")
@performanceLog()
public async createProject(
projectOptions: IProjectSettings
): Promise<ICreateProjectData> {
const projectName = await this.validateProjectName({
projectName: projectOptions.projectName,
force: projectOptions.force,
pathToProject: projectOptions.pathToProject,
});
const projectDir = this.getValidProjectDir(
projectOptions.pathToProject,
projectName
);
this.$fs.createDirectory(projectDir);
const appId =
projectOptions.appId ||
this.$projectHelper.generateDefaultAppId(
projectName,
constants.DEFAULT_APP_IDENTIFIER_PREFIX
);
this.$logger.trace(
`Creating a new NativeScript project with name ${projectName} and id ${appId} at location ${projectDir}`
);
const projectCreationData = await this.createProjectCore({
template: projectOptions.template,
projectDir,
ignoreScripts: projectOptions.ignoreScripts,
appId: appId,
projectName,
});
// can pass --no-git to skip creating a git repo
// useful in monorepos where we're creating
// sub projects in an existing git repo.
if (this.$options.git) {
try {
if (!this.$options.force) {
const git: SimpleGit = simpleGit(projectDir);
if (await git.checkIsRepo()) {
// throwing here since we're catching below.
throw new Error("Already part of a git repository.");
}
}
await this.$childProcess.exec(`git init ${projectDir}`);
await this.$childProcess.exec(`git -C ${projectDir} add --all`);
await this.$childProcess.exec(
`git -C ${projectDir} commit --no-verify -m "init"`
);
} catch (err) {
this.$logger.trace(
"Unable to initialize git repository. Error is: ",
err
);
}
}
this.$logger.trace(`Project ${projectName} was successfully created.`);
return projectCreationData;
}
@exported("projectService")
public isValidNativeScriptProject(pathToProject?: string): boolean {
try {
const projectData = this.$projectDataService.getProjectData(
pathToProject
);
return (
!!projectData &&
!!projectData.projectDir &&
!!(
projectData.projectIdentifiers.ios &&
projectData.projectIdentifiers.android
)
);
} catch (e) {
return false;
}
}
private getValidProjectDir(
pathToProject: string,
projectName: string
): string {
const selectedPath = path.resolve(pathToProject || ".");
const projectDir = path.join(selectedPath, projectName);
return projectDir;
}
private async createProjectCore(
projectCreationSettings: IProjectCreationSettings
): Promise<ICreateProjectData> {
const {
template,
projectDir,
appId,
projectName,
ignoreScripts,
} = projectCreationSettings;
try {
const templateData = await this.$projectTemplatesService.prepareTemplate(
template,
projectDir
);
await this.extractTemplate(projectDir, templateData);
this.alterPackageJsonData(projectCreationSettings);
this.$projectConfigService.writeDefaultConfig(projectDir, appId);
await this.ensureAppResourcesExist(projectDir);
// Install devDependencies and execute all scripts:
await this.$packageManager.install(projectDir, projectDir, {
disableNpmInstall: false,
frameworkPath: null,
ignoreScripts,
});
} catch (err) {
this.$fs.deleteDirectory(projectDir);
throw err;
}
await this.$hooksService.executeAfterHooks(Hooks.createProject, {
hookArgs: projectCreationSettings,
});
return { projectName, projectDir };
}
@performanceLog()
private async extractTemplate(
projectDir: string,
templateData: ITemplateData
): Promise<void> {
this.$fs.ensureDirectoryExists(projectDir);
const fullTemplateName = templateData.version
? `${templateData.templateName}@${templateData.version}`
: templateData.templateName;
await this.$pacoteService.extractPackage(fullTemplateName, projectDir);
}
@performanceLog()
public async ensureAppResourcesExist(projectDir: string): Promise<void> {
const projectData = this.$projectDataService.getProjectData(projectDir);
const appResourcesDestinationPath = projectData.getAppResourcesDirectoryPath(
projectDir
);
if (!this.$fs.exists(appResourcesDestinationPath)) {
this.$logger.trace(
"Project does not have App_Resources - fetching from default template."
);
this.$fs.createDirectory(appResourcesDestinationPath);
const tempDir = await this.$tempService.mkdirSync("ns-default-template");
// the template installed doesn't have App_Resources -> get from a default template
await this.$pacoteService.extractPackage(
constants.RESERVED_TEMPLATE_NAMES["default"],
tempDir
);
const templateProjectData = this.$projectDataService.getProjectData(
tempDir
);
const templateAppResourcesDir = templateProjectData.getAppResourcesDirectoryPath(
tempDir
);
this.$fs.copyFile(
path.join(templateAppResourcesDir, "*"),
appResourcesDestinationPath
);
}
}
@performanceLog()
private alterPackageJsonData(
projectCreationSettings: IProjectCreationSettings
): void {
const { projectDir, projectName } = projectCreationSettings;
const projectFilePath = path.join(
projectDir,
this.$staticConfig.PROJECT_FILE_NAME
);
let packageJsonData = this.$fs.readJson(projectFilePath);
// clean up keys from the template package.json that we don't care about.
Object.keys(packageJsonData).forEach((key) => {
if (
key.startsWith("_") ||
constants.TemplatesV2PackageJsonKeysToRemove.includes(key)
) {
delete packageJsonData[key];
}
});
// this is used to ensure the order of keys is consistent, the blanks are filled in from the template
const packageJsonSchema = {
name: projectName,
main: "",
version: "1.0.0",
private: true,
dependencies: {},
devDependencies: {},
// anythign else would go below
};
packageJsonData = Object.assign(packageJsonSchema, packageJsonData);
this.$fs.writeJson(projectFilePath, packageJsonData);
}
}
injector.register("projectService", ProjectService);