Skip to content
This repository has been archived by the owner on Oct 31, 2024. It is now read-only.

Commit

Permalink
feat(cli): use current package version on project init (#1597)
Browse files Browse the repository at this point in the history
* feat(cli): use current package version on project init

* feat: generate env file

* feat(cli): auth cache in cli
  • Loading branch information
patzick authored Jul 19, 2021
1 parent 9c5bd13 commit ed564b5
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 130 deletions.
24 changes: 6 additions & 18 deletions packages/cli/src/commands/domains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,24 +67,12 @@ Synchronize the domain's related config from backend (in order to build a domain
}

// Get Auth Token for API
let authToken;
try {
authToken = await toolbox.fetchPluginsAuthToken(toolbox.inputParameters);
} catch (error) {
if (!toolbox.isDefaultDemoData()) {
if (error.response.status === 401) {
toolbox.print.error(
"Invalid credentials, aborting domain import. Please try again. This synchronization is required."
);
return -1;
}
toolbox.print.error(
`Error during API authentication: ${error.response.status} (${error.response.statusText})
Please try again. This synchronization is required.
`
);
return -1;
}
const authToken = await toolbox.auth.getAuthToken();
if (!authToken) {
toolbox.print.error(
`Please try again. This synchronization is required.`
);
return -1;
}

let domainsMap = {};
Expand Down
29 changes: 11 additions & 18 deletions packages/cli/src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getDefaultConfigFile } from "@shopware-pwa/commons";
import { GluegunToolbox } from "gluegun";
import path from "path";

module.exports = {
name: "init",
Expand All @@ -20,8 +21,6 @@ module.exports = {
warning(`You're running CLI in development mode!`);
}

const availablePwaVersions = await toolbox.shopware.getPwaVersions();

const currentSetup = await getDefaultConfigFile();
toolbox.reloadInputParameters({
shopwareEndpoint: currentSetup.shopwareEndpoint,
Expand Down Expand Up @@ -53,31 +52,25 @@ module.exports = {
message: "Shopware instance access token:",
initial: inputParameters.shopwareAccessToken,
};
const stageQuestion = {
type: "select",
name: "stage",
message: "Which version you'd like to use:",
choices: availablePwaVersions,
initial: inputParameters.stage,
};

const answers = await toolbox.prompt.ask([
shopwareEndpointQuestion,
shopwareAccessTokenQuestion,
stageQuestion,
]);
Object.assign(inputParameters, answers);
}

await toolbox.checkApiCompatibility();
await toolbox.generateNuxtProject();

const defaultVersion = availablePwaVersions[0];
let stage = inputParameters.stage || defaultVersion;
if (inputParameters.stage === "stable") stage = defaultVersion;
const packageJson = require(path.join("..", "..", "package.json"));
const currentVersion = `^${packageJson.version}`;
const isLocalSetup = inputParameters.stage === "local";

const updateConfigSpinner = spin(
"Updating configuration for option: " + stage
`Updating configuration for v: ${currentVersion}${
isLocalSetup ? " - CONTRIBUTION MODE (local setup)" : ""
}`
);

// Adding Shopware PWA core dependencies
Expand Down Expand Up @@ -114,22 +107,22 @@ module.exports = {
delete config.devDependencies[packageName];
});

if (stage !== "local") {
if (!isLocalSetup) {
// add dependencies with version
coreDevPackages.forEach((packageName) => {
config.devDependencies[packageName] = stage;
config.devDependencies[packageName] = currentVersion;
});
} else {
// add local dependencies and link them
localCoreDevPackages.forEach((packageName) => {
config.devDependencies[packageName] = defaultVersion;
config.devDependencies[packageName] = currentVersion;
});
}

return sortPackageJson(config);
});

if (stage === "local") {
if (isLocalSetup) {
await run(`npx yalc add -D ${localCoreDevPackages.join(" ")}`);
await run(`yarn link ${localCoreDevPackages.join(" ")}`);
}
Expand Down
13 changes: 2 additions & 11 deletions packages/cli/src/commands/snippets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,8 @@ module.exports = {
}

// Get Auth Token for API
let authToken;
try {
authToken = await toolbox.fetchPluginsAuthToken(toolbox.inputParameters);
} catch (error) {
if (error.response.status === 401) {
toolbox.print.error("Invalid credentials, aborting snippet import.");
return -1;
}
toolbox.print.error(
`Error during API authentication: ${error.response.status} (${error.response.statusText})`
);
const authToken = await toolbox.auth.getAuthToken();
if (!authToken) {
return -1;
}

Expand Down
5 changes: 5 additions & 0 deletions packages/cli/src/extensions/nuxt-extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ module.exports = (toolbox: GluegunToolbox) => {
},
});
}
const isEnvFileCreated = exists(".env");
const isTemplateEnvFile = exists(".env.template");
if (!isEnvFileCreated && isTemplateEnvFile) {
await toolbox.filesystem.copyAsync(".env.template", ".env");
}
};

toolbox.copyThemeFolder = async (folderName, destination) => {
Expand Down
56 changes: 10 additions & 46 deletions packages/cli/src/extensions/plugins-extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,46 +32,6 @@ module.exports = (toolbox: GluegunToolbox) => {
);
};

toolbox.fetchPluginsAuthToken = async (
{ shopwareEndpoint, username, password } = toolbox.inputParameters
) => {
const normalizedShopwareEndpoint =
toolbox.normalizeBaseUrl(shopwareEndpoint);
let authTokenResponse;
// Temporary turn off automatic credentials
// if (
// !username &&
// !password &&
// normalizedShopwareEndpoint === toolbox.defaultInitConfig?.shopwareEndpoint
// ) {
// try {
// authTokenResponse = await axios.post(
// `${normalizedShopwareEndpoint}/api/oauth/token`,
// {
// grant_type: "client_credentials",
// client_id: toolbox.defaultInitConfig.INSTANCE_READ_API_KEY,
// client_secret: toolbox.defaultInitConfig.INSTANCE_READ_API_SECRET,
// }
// );
// } catch (error) {
// console.warn("error", error);
// }
// } else {
authTokenResponse = await axios.post(
`${normalizedShopwareEndpoint}/api/oauth/token`,
{
client_id: "administration",
grant_type: "password",
scopes: "write",
username,
password,
}
);
// }

return authTokenResponse?.data?.access_token;
};

toolbox.fetchPluginsBuildArtifact = async ({
shopwareEndpoint,
authToken,
Expand Down Expand Up @@ -319,19 +279,23 @@ module.exports = (toolbox: GluegunToolbox) => {
};

toolbox.loadPluginsAssets = async () => {
const FETCH_ERROR_MESSAGE =
"Plugin settings are not fetched from shopware instance.";

if (
!toolbox.inputParameters.username ||
!toolbox.inputParameters.password
) {
toolbox.print.warning(
"Plugin settings are not fetched from shopware instance."
);
toolbox.print.warning(FETCH_ERROR_MESSAGE);
return;
}
try {
const authToken = await toolbox.fetchPluginsAuthToken(
toolbox.inputParameters
);
const authToken = await toolbox.auth.getAuthToken();
if (!authToken) {
toolbox.print.error(FETCH_ERROR_MESSAGE);
return;
}

const buildArtifact = await toolbox.fetchPluginsBuildArtifact({
...toolbox.inputParameters,
authToken,
Expand Down
80 changes: 44 additions & 36 deletions packages/cli/src/extensions/shopware-pwa-extension.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { GluegunToolbox } from "gluegun";
import axios from "axios";
import { minor } from "semver";
import {
defaultPwaConfigFile,
ShopwarePwaConfigFile,
Expand All @@ -18,39 +17,6 @@ const INSTANCE_READ_API_SECRET =
module.exports = (toolbox: GluegunToolbox) => {
toolbox.shopware = {};

/**
* Returns list of available versions, should return current stable, previous stable, canary and local.
* Example:
* ^0.7.2
* ^0.6.1
* canary
* local
*/
toolbox.shopware.getPwaVersions = async function () {
const gitHubReleasesResponse = await axios.get(
`https://api.github.com/repos/vuestorefront/shopware-pwa/releases`
);

const SHOW_NUMBER_OF_STABLE_VERSIONS = 2;
const versions = [];
const groups = [];
gitHubReleasesResponse.data.forEach((releaseInfo) => {
const version = toolbox.semver.clean(releaseInfo.tag_name);
// TODO: group by MAJOR after v1.0 release
const versionGroup = minor(version);
if (
!groups.includes(versionGroup) &&
groups.length < SHOW_NUMBER_OF_STABLE_VERSIONS
) {
groups.push(versionGroup);
versions.push(`^${version}`);
}
});
versions.push("canary");
versions.push("local");
return versions;
};

toolbox.defaultInitConfig = {
...defaultPwaConfigFile,
INSTANCE_READ_API_KEY,
Expand Down Expand Up @@ -134,9 +100,13 @@ module.exports = (toolbox: GluegunToolbox) => {
toolbox.config.shopwareAccessToken,
pwaHost: toolbox.parameters.options.pwaHost || toolbox.config.pwaHost,
username:
toolbox.parameters.options.username || toolbox.parameters.options.u,
toolbox.parameters.options.username ||
toolbox.parameters.options.u ||
process.env.ADMIN_USER,
password:
toolbox.parameters.options.password || toolbox.parameters.options.p,
toolbox.parameters.options.password ||
toolbox.parameters.options.p ||
process.env.ADMIN_PASSWORD,
devMode: toolbox.parameters.options.devMode,
ci: toolbox.parameters.options.ci,
stage: toolbox.parameters.options.stage,
Expand Down Expand Up @@ -202,4 +172,42 @@ module.exports = (toolbox: GluegunToolbox) => {
);
}
};

toolbox.auth ??= {};

let authTokenCache: string = "";
toolbox.auth.getAuthToken = async (
{ shopwareEndpoint, username, password } = toolbox.inputParameters
) => {
if (authTokenCache) return authTokenCache;

try {
const normalizedShopwareEndpoint =
toolbox.normalizeBaseUrl(shopwareEndpoint);
const authTokenResponse = await axios.post(
`${normalizedShopwareEndpoint}/api/oauth/token`,
{
client_id: "administration",
grant_type: "password",
scopes: "write",
username,
password,
}
);

authTokenCache = authTokenResponse?.data?.access_token;
return authTokenCache;
} catch (error) {
if (!toolbox.isDefaultDemoData()) {
if (error.response.status === 401) {
toolbox.print.error(
"Invalid credentials, aborting domain import. Please try again. This synchronization is required."
);
}
toolbox.print.error(
`Error during API authentication: ${error.response.status} (${error.response.statusText}).`
);
}
}
};
};
2 changes: 1 addition & 1 deletion packages/cli/src/templates/project-template/.env.template
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ ADMIN_USER=admin
ADMIN_PASSWORD=shopware
ENABLE_DEVTOOLS=true
NODE_ENV=dev
EXPERIMENTAL_IMAGE_PROCESSING_SERVER
EXPERIMENTAL_IMAGE_PROCESSING_SERVER=

0 comments on commit ed564b5

Please sign in to comment.