All files / src/lib/project createProject.ts

96.15% Statements 25/26
33.33% Branches 1/3
100% Functions 2/2
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 472x 2x 2x 2x 2x 2x 2x               2x 1x 1x 1x 1x 1x     1x 1x 1x   1x       1x 1x     1x       1x 1x 1x     2x   3x  
import fs from "fs-extra";
import path from "path";
import os from "os";
import stripInvalidFilenameCharacters from "shared/lib/helpers/stripInvalidFilenameCharacters";
import { ERR_PROJECT_EXISTS, projectTemplatesRoot } from "consts";
import copy from "lib/helpers/fsCopy";
import { getGlobalPluginsPath } from "lib/pluginManager/globalPlugins";
 
export interface CreateProjectInput {
  name: string;
  template: string;
  path: string;
}
 
const createProject = async (options: CreateProjectInput) => {
  const projectFolderName = stripInvalidFilenameCharacters(options.name);
  const projectPath = path.join(options.path, projectFolderName);
  const globalPluginsPath = getGlobalPluginsPath();
  const isPlugin = path.basename(options.template) === "project.gbsproj";
  const templatePath = isPlugin
    ? path.join(globalPluginsPath, path.dirname(options.template))
    : path.join(projectTemplatesRoot, options.template);
  const projectTmpDataPath = `${projectPath}/project.gbsproj`;
  const projectDataPath = `${projectPath}/${projectFolderName}.gbsproj`;
  const { username } = os.userInfo();
 
  Iif (fs.existsSync(projectPath)) {
    throw ERR_PROJECT_EXISTS;
  }
 
  await fs.ensureDir(projectPath);
  await copy(templatePath, projectPath);
 
  // Replace placeholders in data file
  const dataFile = (await fs.readFile(projectTmpDataPath, "utf8"))
    .replace(/___PROJECT_NAME___/g, projectFolderName)
    .replace(/___AUTHOR___/g, username);
 
  await fs.unlink(projectTmpDataPath);
  await fs.writeFile(projectDataPath, dataFile);
  return projectDataPath;
};
 
export default createProject;
 
export { ERR_PROJECT_EXISTS };