# All files / src/Site SiteDeployManager.ts

88.29% Statements 83/94
80.55% Branches 29/36
100% Functions 9/9
88.29% Lines 83/94

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
    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
    2162x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    29x
    29x

    24x

    24x
    24x

    24x

    24x
    14x
    14x

    14x

    24x
    24x
    1x

    23x

    23x

    23x
    1x
    1x
    1x

    23x
    21x
    21x
    4x

    17x

    17x
    4x

    3x

    13x
    4x

    3x

    9x

    4x
    4x

    3x

    5x
    4x

    3x

    1x

    12x

    14x
    14x

    16x
    8x

    8x
    8x
    8x
    4x

    4x
    4x

    14x
    14x

    14x
    14x
    14x

    14x

    14x
    14x

    14x
    14x
    14x
    14x

    14x
    14x
    14x
    14x

    14x
    14x
    14x
    14x
    14x
    14x

    14x
    13x

    1x

    14x

     import fs from 'fs-extra';
    import path from 'path';
    import simpleGit, { SimpleGit } from 'simple-git';
    import ghpages, { PublishOptions } from 'gh-pages';
    import * as gitUtil from '../utils/git';
    import * as logger from '../utils/logger';
    import { _ } from './constants';
    import { SiteConfig } from './SiteConfig';

    export type DeployOptions = {
      branch: string,
      message: string,
      repo: string,
      remote: string,
      user?: { name: string; email: string; },
    };

    /**
     * Handles the deployment of the generated site to GitHub Pages or other configured remote repositories.
     */
    export class SiteDeployManager {
      rootPath: string;
      outputPath: string;
      siteConfig!: SiteConfig;

      constructor(rootPath: string, outputPath: string) {
        this.rootPath = rootPath;
        this.outputPath = outputPath;
      }

      deploy(ciTokenVar: string | boolean) {
        const defaultDeployConfig: DeployOptions = {
          branch: 'gh-pages',
          message: 'Site Update.',
          repo: '',
          remote: 'origin',
        };
        process.env.NODE_DEBUG = 'gh-pages';
        return this.generateDepUrl(ciTokenVar, defaultDeployConfig);
      }

      /**
       * Helper function for deploy(). Returns the ghpages link where the repo will be hosted.
       */
      async generateDepUrl(ciTokenVar: boolean | string, defaultDeployConfig: DeployOptions) {
        Iif (!this.siteConfig) {
          throw new Error('Site config not initialized');
        }

        const depOptions = await this.getDepOptions(ciTokenVar, defaultDeployConfig, ghpages.publish);
        try {
          return await SiteDeployManager.getDepUrl(depOptions);
        } finally {
          ghpages.clean();
        }
      }

      /**
       * Helper function for deploy(). Set the options needed to be used by ghpages.publish.
       */
      async getDepOptions(ciTokenVar: boolean | string, defaultDeployConfig: DeployOptions,
                          publish: (basePath: string, options: PublishOptions) => Promise<void>) {
        const basePath = this.siteConfig.deploy.baseDir || this.outputPath;
        if (!fs.existsSync(basePath)) {
          throw new Error(
            'The site directory does not exist. Please build the site first before deploy.');
        }
        const options: DeployOptions = {
          branch: this.siteConfig.deploy.branch || defaultDeployConfig.branch,
          message: this.siteConfig.deploy.message || defaultDeployConfig.message,
          repo: this.siteConfig.deploy.repo || defaultDeployConfig.repo,
          remote: defaultDeployConfig.remote,
        };
        options.message = options.message.concat(' [skip ci]');

        // Globally set Cache Directory to /node_modules/.cache for gh-pages
        if (!process.env.CACHE_DIR || ['true', 'false', '1', '0'].includes(process.env.CACHE_DIR as string)) {
          const cacheDirectory = path.join(this.rootPath, 'node_modules', '.cache');
          fs.emptydirSync(path.join(cacheDirectory, 'gh-pages'));
          process.env.CACHE_DIR = cacheDirectory;
        }

        if (ciTokenVar) {
          const ciToken = _.isBoolean(ciTokenVar) ? 'GITHUB_TOKEN' : ciTokenVar;
          if (!process.env[ciToken]) {
            throw new Error(`The environment variable ${ciToken} does not exist.`);
          }
          const githubToken = process.env[ciToken];
          let repoSlug;

          if (process.env.TRAVIS) {
            repoSlug = SiteDeployManager.extractRepoSlug(options.repo, process.env.TRAVIS_REPO_SLUG);

            options.user = {
              name: 'Deployment Bot',
              email: 'deploy@travis-ci.org',
            };
          } else if (process.env.APPVEYOR) {
            repoSlug = SiteDeployManager.extractRepoSlug(options.repo, process.env.APPVEYOR_REPO_NAME);

            options.user = {
              name: 'AppVeyorBot',
              email: 'deploy@appveyor.com',
            };
          } else if (process.env.GITHUB_ACTIONS) {
            // Set cache folder to a location Github Actions can find.
            process.env.CACHE_DIR = path.join(process.env.GITHUB_WORKSPACE || '.cache');
            repoSlug = SiteDeployManager.extractRepoSlug(options.repo, process.env.GITHUB_REPOSITORY);

            options.user = {
              name: 'github-actions',
              email: 'github-actions@github.com',
            };
          } else if (process.env.CIRCLECI) {
            repoSlug = SiteDeployManager.extractRepoSlug(
              options.repo,
              `${process.env.CIRCLE_PROJECT_USERNAME}/${process.env.CIRCLE_PROJECT_REPONAME}`,
            );

            options.user = {
              name: 'circleci-bot',
              email: 'deploy@circleci.com',
            };
          } else {
            throw new Error('-c/--ci should only be run in CI environments.');
          }

          options.repo = `https://x-access-token:${githubToken}@github.com/${repoSlug}.git`;
        }

        // Waits for the repo to be updated.
        await publish(basePath, options);
        return options;
      }

      /**
       * Extract repo slug from user-specified repo URL so that we can include the access token
       */
      static extractRepoSlug(repo: string, ciRepoSlug: string | undefined) {
        if (!repo) {
          return ciRepoSlug;
        }
        const repoSlugRegex = /github\.com[:/]([\w-]+\/[\w-.]+)\.git$/;
        const repoSlugMatch = repoSlugRegex.exec(repo);
        if (!repoSlugMatch) {
          throw new Error('-c/--ci expects a GitHub repository.\n'
                + `The specified repository ${repo} is not valid.`);
        }
        const [, repoSlug] = repoSlugMatch;
        return repoSlug;
      }

      /**
       * Helper function for deploy().
       */
      static getDepUrl(options: DeployOptions) {
        const git = simpleGit({ baseDir: process.cwd() });
        return SiteDeployManager.getDeploymentUrl(git, options);
      }

      /**
       * Gets the deployed website's url, returning null if there was an error retrieving it.
       */
      static async getDeploymentUrl(git: SimpleGit, options: DeployOptions) {
        const HTTPS_PREAMBLE = 'https://';
        const SSH_PREAMBLE = 'git@github.com:';
        const GITHUB_IO_PART = 'github.io';

        // https://<name|org name>.github.io/<repo name>/
        function constructGhPagesUrl(remoteUrl: string) {
          Iif (!remoteUrl) {
            return null;
          }
          const parts = remoteUrl.split('/');
          if (remoteUrl.startsWith(HTTPS_PREAMBLE)) {
            // https://github.com/<name|org>/<repo>.git (HTTPS)
            const repoNameWithExt = parts[parts.length - 1];
            const repoName = repoNameWithExt.substring(0, repoNameWithExt.lastIndexOf('.'));
            const name = parts[parts.length - 2].toLowerCase();
            return `https://${name}.${GITHUB_IO_PART}/${repoName}`;
          } else IEif (remoteUrl.startsWith(SSH_PREAMBLE)) {
            // git@github.com:<name|org>/<repo>.git (SSH)
            const repoNameWithExt = parts[parts.length - 1];
            const repoName = repoNameWithExt.substring(0, repoNameWithExt.lastIndexOf('.'));
            const name = parts[0].substring(SSH_PREAMBLE.length);
            return `https://${name}.${GITHUB_IO_PART}/${repoName}`;
          }
          return null;
        }

        const { remote, branch, repo } = options;
        const cnamePromise = gitUtil.getRemoteBranchFile(git, 'blob', remote, branch, 'CNAME');
        const remoteUrlPromise = gitUtil.getRemoteUrl(git, remote);
        const promises = [cnamePromise, remoteUrlPromise];

        try {
          const promiseResults: string[] = await Promise.all(promises) as string[];
          const generateGhPagesUrl = (results: string[]) => {
            const cname = results[0];
            const remoteUrl = results[1];
            Iif (cname) {
              return cname.trim();
            } else if (repo) {
              return constructGhPagesUrl(repo);
            }
            return constructGhPagesUrl(remoteUrl.trim());
          };

          return generateGhPagesUrl(promiseResults);
        } catch (err) {
          logger.error(err);
          return null;
        }
      }
    }