fs#copyFileSync TypeScript Examples

The following examples show how to use fs#copyFileSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: createCHANGELOG.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export function run(rootpath?: string) {
  // get workspace folder
  let workspaceFolders = Workspace.workspaceFolders;
  if (workspaceFolders === undefined) {
    window.showErrorMessage("No workspace are opened.");
    return 1;
  }

  //Select the rootpath
  if (rootpath === undefined || typeof rootpath !== "string") {
    rootpath = workspaceFolders?.[0].uri.fsPath;
  }

  // Check if CHANGELOG.md already exists
  let changelogFilePath = join(rootpath, "CHANGELOG.md");
  if (existsSync(changelogFilePath)) {
    window.showErrorMessage("CHANGELOG.md already exists, aborting.");
    return 2;
  }
  let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
    .extensionPath;
  let changelogTemplatePath: string = join(
    myExtDir,
    "templates/CHANGELOG_template.md"
  );
  copyFileSync(changelogTemplatePath, changelogFilePath);
  return 0;
}
Example #2
Source File: processAssets.ts    From yfm-docs with MIT License 6 votes vote down vote up
/**
 * Processes assets files (everything except .yaml and .md files)
 * @param {string} outputBundlePath
 * @return {void}
 */
export function processAssets(outputBundlePath: string) {
    const {
        input: inputFolderPath,
        output: outputFolderPath,
    } = ArgvService.getConfig();

    const assetFilePath: string[] = walkSync(inputFolderPath, {
        directories: false,
        includeBasePath: false,
        ignore: [
            '**/*.yaml',
            '**/*.md',
        ],
    });

    for (const pathToAsset of assetFilePath) {
        const outputDir: string = resolve(outputFolderPath, dirname(pathToAsset));
        const from = resolve(inputFolderPath, pathToAsset);
        const to = resolve(outputFolderPath, pathToAsset);

        shell.mkdir('-p', outputDir);
        copyFileSync(from, to);

        logger.copy(pathToAsset);
    }

    /* Copy js bundle to user' output folder */
    const sourceBundlePath = resolve(BUILD_FOLDER_PATH, BUNDLE_FILENAME);
    const destBundlePath = resolve(outputBundlePath, BUNDLE_FILENAME);
    shell.mkdir('-p', outputBundlePath);
    shell.cp(sourceBundlePath, destBundlePath);
}
Example #3
Source File: images.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
copyLocalImage = async (imagePath: string, postId: string, postPath: string): Promise<string> => {
    const imageName = basename(imagePath).replace(/\s/g,'-');
    const newPath = join('assets', postId);

    console.log(`Copying image ${join(postPath, imagePath)}`);

    mkdirSync(join(publicPath, newPath), {
        recursive: true
    });
    copyFileSync(join(postPath, imagePath), join(publicPath, newPath, imageName));

    console.log(`Copied to ${join(newPath, imageName)}`);

    return join(newPath, imageName);
}
Example #4
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
async download(
    key: string,
    destination: string,
    useCached: boolean
  ): Promise<string> {
    if (useCached) {
      // note this scope of code working with the cache is async safe, it won't be interuptted because none of the functions used are async
      const cachedPath = this.lruFileCache.get(key);
      // if there is a cached path, use it
      if (cachedPath) {
        this._useCacheCount++;
        // TODO: It would be nice if we could just resolve with the cachedPath and let user use that, but
        // unfortunately that invokes a race condition where downloading two files causes one file's cache to be
        // invalidated and thus unretrievable after we give the user the old cachedPath. This race condition shouldn't
        // happen often, if ever unless there are very little bots and max size is low.
        // a better optimization would be to
        copyFileSync(cachedPath, destination);
        return destination;
      }
    }
    await this.writeFileFromBucket(key, destination);
    // store in cache
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const cachedPath = await this.lruFileCache.add(key, destination);
    this.log.system(`${key} cached to ${cachedPath}`);
    return destination;
  }
Example #5
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
async download(
    key: string,
    destination: string,
    useCached: boolean
  ): Promise<string> {
    return new Promise((resolve) => {
      if (useCached) {
        const cachedPath = this.lruFileCache.get(key);
        // if there is a cached path, use it
        if (cachedPath) {
          copyFileSync(cachedPath, destination);
          resolve(destination);
          return;
        }
      }
      const file = this.dimensionBucket.file(key);
      const ws = file
        .createReadStream()
        .pipe(fs.createWriteStream(destination));
      ws.on('close', async () => {
        // store in cache
        const cachedPath = await this.lruFileCache.add(key, destination);
        this.log.system(
          `writing from bucket ${key} -> ${destination}; cached to ${cachedPath}`
        );
        resolve(destination);
      });
    });
  }
Example #6
Source File: cpGHPages.ts    From fzstd with MIT License 6 votes vote down vote up
git.log({
  from: 'HEAD~1',
  to: 'HEAD'
}).then(async log => {
  const hash = log.latest.hash.slice(0, 7);
  await git.checkout('gh-pages');
  for (const f of readdirSync(to('.'))) {
    if (statSync(f).isFile())
      unlinkSync(to(f));
  }
  const files = readdirSync(to('dist'))
  for (const f of files) {
    copyFileSync(to('dist', f), to(f));
  }
  await git.add(files);
  await git.commit('Build demo from ' + hash);
  await git.checkout('master');
});
Example #7
Source File: copy-eslint-config.ts    From s-libs with MIT License 6 votes vote down vote up
export function copyEslintConfig() {
  const targetFolder = 'dist/eslint-config-ng';
  rmdirSync(targetFolder, { recursive: true });
  mkdirSync(targetFolder);

  const srcFolder = 'projects/eslint-config-ng';
  for (const file of readdirSync(srcFolder)) {
    copyFileSync(join(srcFolder, file), join(targetFolder, file));
  }
}
Example #8
Source File: configuration.ts    From cross-seed with Apache License 2.0 6 votes vote down vote up
export function generateConfig({
	force = false,
	docker = false,
}: GenerateConfigParams): void {
	createAppDir();
	const dest = path.join(appDir(), "config.js");
	const templatePath = path.join(
		`./config.template${docker ? ".docker" : ""}.cjs`
	);
	if (!force && existsSync(dest)) {
		console.log("Configuration file already exists.");
		return;
	}
	copyFileSync(new URL(templatePath, import.meta.url), dest);
	console.log("Configuration file created at", chalk.yellow.bold(dest));
}
Example #9
Source File: LRUFileCache.ts    From Dimensions with MIT License 5 votes vote down vote up
/**
   * Adds key to file path pair to cache and copies file to new location. Does not delete the given file at filepath
   *
   * Automatically throws out least recently used items if not enough space left to
   * fit new file
   *
   * Resolves with path to cached file location
   *
   * @param key - the key pointing to the given file path
   * @param filepath - the file path representing the file to cache
   */
  async add(key: string, filepath: string): Promise<string> {
    let newfilesize = 0;
    key = key.replace(/\//g, '_');
    try {
      const meta = fs.statSync(filepath);
      newfilesize = meta.size;
    } catch (err) {
      if (err.errno === -constants.ENOENT) {
        throw new Error('file does not exist');
      }
    }
    if (newfilesize > this.max) {
      throw new Error(
        `file is at ${filepath} too large, ${newfilesize} > ${this.max} allocated bytes`
      );
    }
    let trimmedSize = this.size;
    const removeFilePromises: Array<Promise<void>> = [];

    while (newfilesize + trimmedSize > this.max) {
      // find files until under max
      const newtail = this.queueTail.prev;
      trimmedSize -= this.queueTail.filesize;
      removeFilePromises.push(
        removeDirectory(
          path.dirname(
            this.getCachedFilePath(this.queueTail.filepath, this.queueTail.key)
          )
        ).catch(noop)
      );
      this.cache.delete(this.queueTail.key);
      if (newtail) {
        newtail.next = null;
        this.queueTail = newtail;
      }
    }
    await Promise.all(removeFilePromises);

    const node = new LRUFileCacheNode(filepath, newfilesize, key);

    if (this.cache.size === 0) {
      this.queueHead = node;
      this.queueTail = node;
    } else if (this.cache.size === 1) {
      this.queueTail = this.queueHead;
      this.queueHead = node;
      this.queueHead.next = this.queueTail;
      this.queueTail.prev = this.queueHead;
    } else {
      // integrate new node into queue.
      node.next = this.queueHead;
      this.queueHead.prev = node;
      this.queueHead = node;
    }
    this.cache.set(key, node);

    // copy file

    const cachedPath = this.getCachedFilePath(filepath, key);
    mkdirSync(path.dirname(cachedPath), {
      recursive: true,
    });
    copyFileSync(filepath, cachedPath);
    this.size = trimmedSize + newfilesize;
    return cachedPath;
  }
Example #10
Source File: processPages.ts    From yfm-docs with MIT License 5 votes vote down vote up
function copyFileWithoutChanges(resolvedPathToFile: string, outputDir: string, filename: string): void {
    const from = resolvedPathToFile;
    const to = resolve(outputDir, filename);

    copyFileSync(from, to);
}
Example #11
Source File: tocs.ts    From yfm-docs with MIT License 5 votes vote down vote up
/**
 * Copies all files of include toc to original dir.
 * @param tocPath
 * @param destDir
 * @return
 * @private
 */
function _copyTocDir(tocPath: string, destDir: string) {
    const {input: inputFolderPath} = ArgvService.getConfig();

    const {dir: tocDir} = parse(tocPath);
    const files: string[] = walkSync(tocDir, {
        globs: ['**/*.*'],
        ignore: ['**/toc.yaml'],
        directories: false,
    });

    files.forEach((relPath) => {
        const from = resolve(tocDir, relPath);
        const to = resolve(destDir, relPath);
        const fileExtension = extname(relPath);
        const isMdFile = fileExtension === '.md';

        shell.mkdir('-p', parse(to).dir);

        if (isMdFile) {
            const fileContent = readFileSync(from, 'utf8');
            const sourcePath = relative(inputFolderPath, from);
            const fileData = {sourcePath};
            const updatedFileContent = getContentWithUpdatedStaticMetadata(fileContent, {
                fileData,
                addSourcePath: true,
            });

            writeFileSync(to, updatedFileContent);
        } else {
            copyFileSync(from, to);
        }
    });
}
Example #12
Source File: jest.image.ts    From bpmn-visualization-js with Apache License 2.0 5 votes vote down vote up
function saveAndRegisterImages(matcherContext: MatcherContext, received: Buffer, options: MatchImageSnapshotOptions): void {
  const snapshotIdentifier = <string>options.customSnapshotIdentifier;
  // Manage expected and received images
  const baseImagePathWithName = `${options.customDiffDir}/${snapshotIdentifier}`;
  const expectedImagePath = `${baseImagePathWithName}-expected.png`;
  copyFileSync(`${options.customSnapshotsDir}/${snapshotIdentifier}-snap.png`, expectedImagePath);
  // this image is generated by jest-image-snapshot when activating `storeReceivedOnFailure`
  const receivedImagePath = `${baseImagePathWithName}-received.png`;

  // Attach the images to jest-html-reports
  // Chain the calls to preserve the attachment order
  // Create a custom context as the async call can be done whereas the global jest context has changed (another test is currently running).
  // So the test name and path changed, and the images would be attached to the wrong test.
  // For the context object structure, see https://github.com/Hazyzh/jest-html-reporters/blob/v3.0.5/helper.ts#L95
  const context: { [key: symbol]: unknown } = {};
  context[Symbol('bpmn-visualization')] = {
    state: {
      currentTestName: matcherContext.currentTestName,
      testPath: matcherContext.testPath,
    },
    matchers: {}, // required by the jest-html-reporters getJestGlobalData function even if not used
  };

  addAttach({
    attach: computeRelativePathFromReportToSnapshots(`${baseImagePathWithName}-diff.png`),
    description: 'diff',
    bufferFormat: 'png',
    context,
  })
    .then(() =>
      addAttach({
        attach: computeRelativePathFromReportToSnapshots(expectedImagePath),
        description: 'expected',
        bufferFormat: 'png',
        context,
      }),
    )
    .then(() => {
      addAttach({
        attach: computeRelativePathFromReportToSnapshots(receivedImagePath),
        description: 'received',
        bufferFormat: 'png',
        context,
      });
    })
    .catch(e =>
      console.error(
        `Error while attaching images to test ${snapshotIdentifier}.` +
          `The 'jest-html-reporters' reporter is probably not in use. For instance, this occurs when running tests with the IntelliJ/Webstorm Jest runner.`,
        e,
      ),
    );
}
Example #13
Source File: createScript.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
export function run(rootpath?: string) {
  let AuthorName: string = Workspace.getConfiguration("sourcepawn").get(
    "AuthorName"
  );
  if (!AuthorName) {
    window
      .showWarningMessage("You didn't specify an author name.", "Open Settings")
      .then((choice) => {
        if (choice === "Open Settings") {
          commands.executeCommand(
            "workbench.action.openSettings",
            "@ext:sarrus.sourcepawn-vscode"
          );
        }
      });
  }

  let GithubName: string = Workspace.getConfiguration("sourcepawn").get(
    "GithubName"
  );

  // get workspace folder
  let workspaceFolders = Workspace.workspaceFolders;
  if (!workspaceFolders) {
    window.showErrorMessage("No workspace are opened.");
    return 1;
  }

  //Select the rootpath
  if (rootpath === undefined) {
    rootpath = workspaceFolders?.[0].uri.fsPath;
  }

  let rootname = basename(rootpath);

  // create a scripting folder if it doesn't exist
  let scriptingFolderPath = join(rootpath, "scripting");
  if (!existsSync(scriptingFolderPath)) {
    mkdirSync(scriptingFolderPath);
  }

  // Check if file already exists
  let scriptFileName: string = rootname + ".sp";
  let scriptFilePath = join(rootpath, "scripting", scriptFileName);
  if (existsSync(scriptFilePath)) {
    window.showErrorMessage(scriptFileName + " already exists, aborting.");
    return 2;
  }
  let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
    .extensionPath;
  let tasksTemplatesPath: string = join(
    myExtDir,
    "templates/plugin_template.sp"
  );
  copyFileSync(tasksTemplatesPath, scriptFilePath);

  // Replace placeholders
  try {
    let data = readFileSync(scriptFilePath, "utf8");
    let result = data.replace(/\${AuthorName}/gm, AuthorName);
    result = result.replace(/\${plugin_name}/gm, rootname);
    result = result.replace(/\${GithubName}/gm, GithubName);
    writeFileSync(scriptFilePath, result, "utf8");
  } catch (err) {
    console.log(err);
    return 3;
  }
  workspace
    .openTextDocument(URI.file(scriptFilePath))
    .then((document) => window.showTextDocument(document));
  return 0;
}
Example #14
Source File: createREADME.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
export function run(rootpath?: string) {
  let GithubName: string = Workspace.getConfiguration("sourcepawn").get(
    "GithubName"
  );
  if (!GithubName) {
    window
      .showWarningMessage(
        "You didn't specify a GitHub username.",
        "Open Settings"
      )
      .then((choice) => {
        if (choice === "Open Settings") {
          commands.executeCommand(
            "workbench.action.openSettings",
            "@ext:sarrus.sourcepawn-vscode"
          );
        }
      });
  }

  // get workspace folder
  let workspaceFolders = Workspace.workspaceFolders;
  if (!workspaceFolders) {
    window.showErrorMessage("No workspace are opened.");
    return 1;
  }

  //Select the rootpath
  if (rootpath === undefined) {
    rootpath = workspaceFolders?.[0].uri.fsPath;
  }

  let rootname = basename(rootpath);

  // Check if README.md already exists
  let readmeFilePath = join(rootpath, "README.md");
  if (existsSync(readmeFilePath)) {
    window.showErrorMessage("README.md already exists, aborting.");
    return 2;
  }
  let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
    .extensionPath;
  let tasksTemplatesPath: string = join(
    myExtDir,
    "templates/README_template.MD"
  );
  copyFileSync(tasksTemplatesPath, readmeFilePath);

  // Replace placeholders
  try {
    let result = readFileSync(readmeFilePath, "utf8");
    result = result.replace(/\${plugin_name}/gm, rootname);
    result = result.replace(/\${GithubName}/gm, GithubName);
    writeFileSync(readmeFilePath, result, "utf8");
  } catch (err) {
    console.log(err);
    return 3;
  }
  return 0;
}
Example #15
Source File: 04-dimensions.tournament.spec.ts    From Dimensions with MIT License 4 votes vote down vote up
describe('Testing /api/dimensions/:dimensionID/tournaments API', () => {
  const base = '/api/dimensions/:dimensionID';
  let origin = 'http://localhost:';
  let endpoint = '';
  let dimension: Dimension.DimensionType;
  let t: Ladder;
  const paper = './tests/kits/js/normal/paper.js';
  const rock = './tests/kits/js/normal/rock.js';
  const botList = [rock, paper];
  // list of bots not in DB
  const anonBotList = [
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock1',
      existingID: 'anon1',
    },
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock2',
      existingID: 'anon2',
    },
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock3',
      existingID: 'anon3',
    },
  ];
  // list of bots in DB
  const botListWithIDs = [
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock1',
      existingID: 'rock1',
    },
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock2',
      existingID: 'rock2',
    },
    {
      file: './tests/kits/js/normal/rock.js',
      name: 'rock3',
      existingID: 'rock3',
    },
  ];
  const mongo = new MongoDB(
    'mongodb://root:rootpassword@localhost:27017/test?authSource=admin&readPreference=primary'
  );
  const fsstore = new FileSystemStorage();

  before(async () => {
    const rpsDesign = new RockPaperScissorsDesign('RPS');
    dimension = Dimension.create(rpsDesign, {
      activateStation: true,
      observe: true,
      loggingLevel: Logger.LEVEL.NONE,
      id: 'abcdef4',
      defaultMatchConfigs: {
        storeErrorLogs: false,
      },
      stationConfigs: {
        requireAuth: false,
      },
    });
    origin += dimension.getStation().port;
    endpoint = origin + `/api/dimensions/${dimension.id}`;
    t = createLadderTourney(dimension, botList, {
      id: 'tournamentid',
    });
    await dimension.use(mongo);
    await dimension.use(fsstore);
  });
  it(`GET ${base}/tournaments - should return all tournaments`, async () => {
    const res = await chai.request(endpoint).get(`/tournaments`);
    expect(res.status).to.equal(200);
    expect({
      error: null,
      tournaments: {
        tournamentid: t,
      },
    }).to.containSubset(res.body);
  });

  it(`GET ${base}/tournaments/:tournamentID - should return tournament with id tournamentID`, async () => {
    const res = await chai.request(endpoint).get(`/tournaments/${t.id}`);
    expect(res.status).to.equal(200);
    expect({
      error: null,
      tournament: t,
    }).to.containSubset(res.body);
  });

  it(`GET ${base}/tournaments/:tournamentID - should return 400, if tournament with id tournamentID does not exist`, async () => {
    const res = await chai
      .request(endpoint)
      .get(`/tournaments/faketournamentID`);
    expect(res.status).to.equal(400);
    expect(res.body).to.eql({
      error: {
        status: 400,
        message: `No tournament found with name or id of 'faketournamentID' in dimension ${dimension.id} - '${dimension.name}'`,
      },
    });
  });

  it(`POST ${base}/tournaments/:tournamentID/upload-by-key - should upload bot by key`, async () => {
    const t = createLadderTourney(dimension, botListWithIDs, {
      id: 'ladderTestWithUploadBykey',
      tournamentConfigs: {
        selfMatchMake: false,
      },
      defaultMatchConfigs: {
        bestOf: 9,
      },
    });
    mkdirSync(path.join(fsstore.bucketPath, 'testfolder'), {
      recursive: true,
    });
    copyFileSync(
      './tests/kits/js/normal/paper.zip',
      path.join(fsstore.bucketPath, 'testfolder/bot.zip')
    );
    const res = await chai
      .request(endpoint)
      .post(`/tournaments/${t.id}/upload-by-key`)
      .send({
        botname: 'rock2withpaper',
        botkey: 'testfolder/bot.zip',
        playerID: 'rock2',
        pathtofile: 'paper.js',
      });
    const { playerStat } = await t.getPlayerStat('rock2');
    expect(playerStat.player.botDirPath).to.equal(null);
    expect(playerStat.player.botkey).to.equal('testfolder/bot.zip');
    expect(playerStat.player.disabled).to.equal(false);
    expect(playerStat.player.file).to.equal('paper.js');
    expect(playerStat.player.zipFile).to.equal(null);
    expect(res.status).to.equal(200);
    await t.destroy();
  });

  it(`POST ${base}/tournaments/:tournamentID/match-queue - should schedule matches`, async () => {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      const t = createLadderTourney(dimension, anonBotList, {
        id: 'ladderWithoutSelfMatchmake',
        tournamentConfigs: {
          selfMatchMake: false,
        },
        defaultMatchConfigs: {
          bestOf: 9,
        },
      });
      const matchQueue = [
        ['anon1', 'anon2'],
        ['anon2', 'anon3'],
      ];
      await t.run();
      const res = await chai
        .request(endpoint)
        .post(`/tournaments/${t.id}/match-queue`)
        .send({ matchQueue });
      expect(res.status).to.equal(200);
      expect(res.body).to.eql({
        error: null,
        message: `Queued ${matchQueue.length} matches`,
      });
      let count = 0;
      t.on(Tournament.Events.MATCH_HANDLED, async () => {
        if (++count === 2) {
          try {
            expect(t.state.playerStats.get('anon1').matchesPlayed).to.equal(1);
            expect(t.state.playerStats.get('anon2').matchesPlayed).to.equal(2);
            expect(t.state.playerStats.get('anon3').matchesPlayed).to.equal(1);
            await t.destroy();
            resolve();
          } catch (err) {
            await t.destroy();
            reject(err);
          }
        }
      });
    });
  });
  after(async () => {
    await mongo.db.close();
  });
});
Example #16
Source File: createTask.ts    From sourcepawn-vscode with MIT License 4 votes vote down vote up
export function run(rootpath?: string) {
  // Get configuration
  let sm_home: string = Workspace.getConfiguration("sourcepawn").get(
    "SourcemodHome"
  );
  if (!sm_home) {
    window
      .showWarningMessage(
        "SourceMod API not found in the project. You should set SourceMod Home for tasks generation to work. Do you want to install it automatically?",
        "Yes",
        "No, open Settings"
      )
      .then((choice) => {
        if (choice == "Yes") {
          commands.executeCommand("sourcepawn-vscode.installSM");
        } else if (choice === "No, open Settings") {
          commands.executeCommand(
            "workbench.action.openSettings",
            "@ext:sarrus.sourcepawn-vscode"
          );
        }
      });
  }

  let SpcompPath: string = Workspace.getConfiguration("sourcepawn").get(
    "SpcompPath"
  );
  if (!SpcompPath) {
    window
      .showErrorMessage(
        "SourceMod compiler not found in the project. You need to set SpcompPath for tasks generation to work.",
        "Open Settings"
      )
      .then((choice) => {
        if (choice === "Open Settings") {
          commands.executeCommand(
            "workbench.action.openSettings",
            "@ext:sarrus.sourcepawn-vscode"
          );
        }
      });
    return 1;
  }

  // get workspace folder
  let workspaceFolders = Workspace.workspaceFolders;
  if (!workspaceFolders) {
    window.showErrorMessage("No workspace are opened.");
    return 2;
  }

  //Select the rootpath
  if (rootpath === undefined) {
    rootpath = workspaceFolders?.[0].uri.fsPath;
  }

  // create task folder if it doesn't exist
  let taskFolderPath = join(rootpath, ".vscode");
  if (!existsSync(taskFolderPath)) {
    mkdirSync(taskFolderPath);
  }

  // Check if file already exists
  let taskFilePath = join(rootpath, ".vscode/tasks.json");
  if (existsSync(taskFilePath)) {
    window.showErrorMessage("tasks.json file already exists.");
    return 3;
  }
  let myExtDir: string = extensions.getExtension("Sarrus.sourcepawn-vscode")
    .extensionPath;
  let tasksTemplatesPath: string = join(myExtDir, "templates/tasks.json");
  copyFileSync(tasksTemplatesPath, taskFilePath);
  SpcompPath = SpcompPath.replace(/\\/gm, "\\\\");
  sm_home = sm_home.replace(/\\/gm, "\\\\");
  // Replace placeholders
  try {
    let data = readFileSync(taskFilePath, "utf8");
    let result = data.replace(/\${SpcompPath}/gm, SpcompPath);
    result = result.replace(/\${include_path}/gm, sm_home);
    writeFileSync(taskFilePath, result, "utf8");
  } catch (err) {
    console.log(err);
    return 4;
  }
  return 0;
}
Example #17
Source File: angular-universal.adapter.ts    From nx-plugins with MIT License 4 votes vote down vote up
deploy(
    context: BuilderContext,
    cwd: string,
    options: NxDeployItDeployBuilderSchema,
    configuration: string,
    targetOptions: any
  ): Observable<BuilderOutput> {
    const distributationPath = getDistributionPath(context);
    const project = getProjectConfig(context);
    const infrastructureFolder = resolve(
      context.workspaceRoot,
      project.root,
      'infrastructure'
    );
    const deploymentType: ANGULAR_UNIVERSAL_DEPLOYMENT_TYPE =
      targetOptions.pulumi.angularUniversalDeploymentType;

    let baseHref = '/';
    switch (this.options.provider) {
      case PROVIDER.AWS:
        baseHref = `/${context.target.configuration || 'dev'}/`;
        break;

      default:
        break;
    }

    let build$: Observable<BuilderOutput>;

    switch (deploymentType) {
      case ANGULAR_UNIVERSAL_DEPLOYMENT_TYPE.PRERENDERING:
        build$ = from(
          context
            .scheduleTarget({
              target: 'prerender',
              project: context.target.project,
              configuration: context.target.configuration || undefined
            })
            .then(build => build.result)
        );
        break;

      case ANGULAR_UNIVERSAL_DEPLOYMENT_TYPE.SERVER_SIDE_RENDERING:
        build$ = from(
          Promise.all([
            context.scheduleTarget(
              {
                target: 'build',
                project: context.target.project,
                configuration: context.target.configuration || undefined
              },
              {
                baseHref
              }
            ),
            context.scheduleTarget(
              {
                target: 'server',
                project: context.target.project,
                configuration: context.target.configuration || undefined
              },
              {
                main: resolve(infrastructureFolder, 'functions/main/index.ts'),
                tsConfig: resolve(infrastructureFolder, 'tsconfig.json')
              }
            )
          ]).then(([build, server]) =>
            Promise.all([build.result, server.result])
          )
        ).pipe(
          switchMap(() => {
            if (this.options.provider === PROVIDER.GOOGLE_CLOUD_PLATFORM) {
              copyFileSync(
                join(
                  context.workspaceRoot,
                  `${project.architect.server.options.outputPath}/main.js`
                ),
                join(
                  context.workspaceRoot,
                  `${project.architect.server.options.outputPath}/index.js`
                )
              );
            }
            return of({ success: true });
          })
        );
        break;

      default:
        throw new Error(
          'Unknown deployment type! Supported types are: ["prerendering", "ssr"]'
        );
    }

    return build$.pipe(
      switchMap(() =>
        this.up(
          cwd,
          options,
          configuration,
          targetOptions,
          distributationPath,
          context.target.project
        )
      )
    );
  }