UNPKG

@transact-open-ux/cli

Version:

Command line for rapid development/deployment on the Transact Platform

131 lines (114 loc) 3.13 kB
/** * @license * Copyright (c) 2019 Avoka Technologies Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ const download = require("download"); const execa = require("execa"); function downloadRepo(repo, dest, clone, directUrl) { const isGitUrl = /(?:git|ssh|https?|git@[-\w.]+):(\/\/)?(.*?)(\.git)(\/?|#[-\d\w._]+?)$/; let url; if (directUrl) { url = repo; } else if (isGitUrl.test(repo)) { if (!clone) throw Error("This repo must be cloned unless you use the short syntax"); url = repo; } else { repo = normalize(repo); url = getUrl(repo, clone); } return new Promise(async (resolve, reject) => { try { if (clone) { await gitClone(url, dest, !isGitUrl && repo.checkout); } else { await download(url, dest, { extract: true, strip: 1, mode: "666", headers: { accept: "application/zip" } }); } resolve(url); } catch (e) { reject(e); } }); } async function gitClone(url, dest, branch) { return execa.shell( `git clone ${url} ${dest} ${branch ? `-b ${branch}` : ""}`, { cwd: process.cwd() } ); } /** * Normalize a repo string. * * @param {String} repo * @return {Object} */ function normalize(repo) { const regex = /^((github|gitlab|bitbucket):)?((.+):)?([^/]+)\/([^#]+)(#(.+))?$/; const match = regex.exec(repo); const type = match[2] || "github"; let origin = match[4] || null; const owner = match[5]; const name = match[6]; const checkout = match[8] || "master"; if (origin == null) { origin = { github: "github.com", gitlab: "gitlab.com", bitbucket: "bitbucket.org" }[type]; } return { type, origin, owner, name, checkout }; } /** * Return a zip or git url for a given `repo`. * * @param {Object} repo * @param {boolean} clone * @return {String} */ function getUrl(repo, clone) { let { origin, type, owner, name, checkout } = repo; let url; // Get origin with protocol and add trailing slash or colon (for ssh) if (!/^(f|ht)tps?:\/\//i.test(origin)) origin = `https://${origin}`; else if (/^git@/i.test(origin)) { origin = origin + ":"; } else { origin = origin + "/"; } if (clone) { return `${origin}/${owner}/${name}.git`; } // Build url url = { github: `${origin}/${owner}/${name}/archive/${checkout}.zip`, gitlab: `${origin}/${owner}/${name}/repository/archive.zip?ref=/${checkout}`, bitbucket: `${origin}/${owner}/${name}/get/${checkout}.zip` }[type]; return url; } module.exports = downloadRepo;