Skip to content

Commit

Permalink
Merge pull request #849 from appwrite/feat-console-flow
Browse files Browse the repository at this point in the history
feat(cli): Adding console for get & list methods
  • Loading branch information
christyjacob4 authored Jun 11, 2024
2 parents 1d0350b + 169bb86 commit 2014675
Show file tree
Hide file tree
Showing 19 changed files with 1,550 additions and 550 deletions.
9 changes: 9 additions & 0 deletions src/SDK/Language.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,15 @@ public function getFilters(): array
return [];
}

/**
* Language specific functions.
* @return array
*/
public function getFunctions(): array
{
return [];
}

protected function toPascalCase(string $value): string
{
return \ucfirst($this->toCamelCase($value));
Expand Down
72 changes: 72 additions & 0 deletions src/SDK/Language/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,66 @@

namespace Appwrite\SDK\Language;

use Twig\TwigFunction;

class CLI extends Node
{
/**
* List of functions to ignore for console preview.
* @var array
*/
private $consoleIgnoreFunctions = [
'listidentities',
'listmfafactors',
'getprefs',
'getsession',
'getattribute',
'listdocumentlogs',
'getindex',
'listcollectionlogs',
'getcollectionusage',
'listlogs',
'listruntimes',
'getusage',
'getusage',
'listvariables',
'getvariable',
'listproviderlogs',
'listsubscriberlogs',
'getsubscriber',
'listtopiclogs',
'getemailtemplate',
'getsmstemplate',
'getfiledownload',
'getfilepreview',
'getfileview',
'getusage',
'listlogs',
'getprefs',
'getusage',
'listlogs',
'getmembership',
'listmemberships',
'listmfafactors',
'getmfarecoverycodes',
'getprefs',
'listtargets',
'gettarget',
];

/**
* List of SDK services to ignore for console preview.
* @var array
*/
private $consoleIgnoreServices = [
'health',
'migrations',
'locale',
'avatars',
'project',
'proxy',
'vcs'
];
/**
* @var array
*/
Expand Down Expand Up @@ -290,4 +348,18 @@ public function getParamExample(array $param): string

return $output;
}

/**
* Language specific filters.
* @return array
*/
public function getFunctions(): array
{
return [
/** Return true if the entered service->method is enabled for a console preview link */
new TwigFunction('hasConsolePreview', fn($method, $service) => preg_match('/^([Gg]et|[Ll]ist)/', $method)
&& !in_array(strtolower($method), $this->consoleIgnoreFunctions)
&& !in_array($service, $this->consoleIgnoreServices)),
];
}
}
7 changes: 7 additions & 0 deletions src/SDK/SDK.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ public function __construct(Language $language, Spec $spec)
'debug' => true
]);

/**
* Add language-specific functions
*/
foreach ($this->language->getFunctions() as $function) {
$this->twig->addFunction($function);
}

/**
* Add language specific filters
*/
Expand Down
11 changes: 11 additions & 0 deletions templates/cli/base/requests/api.twig
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,19 @@
fs.writeFileSync(destination, response);
{%~ endif %}
if (parseOutput) {
{%~ if hasConsolePreview(method.name,service.name) %}
if(console) {
showConsoleLink('{{service.name}}', '{{ method.name }}'
{%- for parameter in method.parameters.path -%}{%- set param = (parameter.name | caseCamel | escapeKeyword) -%}{%- if param ends with 'Id' -%}, {{ param }} {%- endif -%}{%- endfor -%}
);
} else {
parse(response)
success()
}
{%~ else %}
parse(response)
success()
{%~ endif %}
}

return response;
23 changes: 23 additions & 0 deletions templates/cli/index.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,21 @@ const chalk = require("chalk");
const { version } = require("./package.json");
const { commandDescriptions, cliConfig } = require("./lib/parser");
const { client } = require("./lib/commands/generic");
const inquirer = require("inquirer");
{% if sdk.test != "true" %}
const { login, logout, whoami } = require("./lib/commands/generic");
const { init } = require("./lib/commands/init");
const { pull } = require("./lib/commands/pull");
const { push } = require("./lib/commands/push");
{% else %}
const { migrate } = require("./lib/commands/generic");
{% endif %}
{% for service in spec.services %}
const { {{ service.name | caseLower }} } = require("./lib/commands/{{ service.name | caseLower }}");
{% endfor %}

inquirer.registerPrompt('search-list', require('inquirer-search-list'));

program
.description(commandDescriptions['main'])
.configureHelp({
Expand All @@ -29,12 +34,30 @@ program
.version(version, "-v, --version")
.option("--verbose", "Show complete error log")
.option("--json", "Output in JSON format")
.hook('preAction', migrate)
.option("-f,--force", "Flag to confirm all warnings")
.option("-a,--all", "Flag to push all resources")
.option("--id [id...]", "Flag to pass list of ids for a giving action")
.option("--report", "Enable reporting in case of CLI errors")
.on("option:json", () => {
cliConfig.json = true;
})
.on("option:verbose", () => {
cliConfig.verbose = true;
})
.on("option:report", function() {
cliConfig.report = true;
cliConfig.reportData = { data: this };
})
.on("option:force", () => {
cliConfig.force = true;
})
.on("option:all", () => {
cliConfig.all = true;
})
.on("option:id", function() {
cliConfig.ids = this.opts().id;
})
.showSuggestionAfterError()
{% if sdk.test != "true" %}
.addCommand(whoami)
Expand Down
11 changes: 10 additions & 1 deletion templates/cli/lib/client.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ const { fetch, FormData, Agent } = require("undici");
const JSONbig = require("json-bigint")({ storeAsString: false });
const {{spec.title | caseUcfirst}}Exception = require("./exception.js");
const { globalConfig } = require("./config.js");
const chalk = require("chalk");

class Client {
CHUNK_SIZE = 5*1024*1024; // 5MB

constructor() {
this.endpoint = '{{spec.endpoint}}';
this.headers = {
Expand Down Expand Up @@ -144,6 +145,14 @@ class Client {
} catch (error) {
throw new {{spec.title | caseUcfirst}}Exception(text, response.status, "", text);
}

if (path !== '/account' && json.code === 401 && json.type === 'user_more_factors_required') {
console.log(`${chalk.cyan.bold("ℹ Info")} ${chalk.cyan("Unusable account found, removing...")}`);

const current = globalConfig.getCurrentSession();
globalConfig.setCurrentSession('');
globalConfig.removeSession(current);
}
throw new {{spec.title | caseUcfirst}}Exception(json.message, json.code, json.type, json);
}

Expand Down
6 changes: 5 additions & 1 deletion templates/cli/lib/commands/command.js.twig
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const tar = require("tar");
const ignore = require("ignore");
const { promisify } = require('util');
const libClient = require('../client.js');
const { getAllFiles } = require('../utils.js');
const { getAllFiles, showConsoleLink } = require('../utils.js');
const { Command } = require('commander');
const { sdkForProject, sdkForConsole } = require('../sdks')
const { parse, actionRunner, parseInteger, parseBool, commandDescriptions, success, log } = require('../parser')
Expand Down Expand Up @@ -70,6 +70,7 @@ const {{ service.name | caseLower }}{{ method.name | caseUcfirst }} = async ({
{%- if 'multipart/form-data' in method.consumes -%},onProgress = () => {}{%- endif -%}

{%- if method.type == 'location' -%}, destination{%- endif -%}
{% if hasConsolePreview(method.name,service.name) %}, console{%- endif -%}
}) => {
{%~ endblock %}
let client = !sdk ? await {% if service.name == "projects" %}sdkForConsole(){% else %}sdkForProject(){% endif %} :
Expand All @@ -94,6 +95,9 @@ const {{ service.name | caseLower }}{{ method.name | caseUcfirst }} = async ({
{% if method.type == 'location' %}
.requiredOption(`--destination <path>`, `output file path.`)
{% endif %}
{% if hasConsolePreview(method.name,service.name) %}
.option(`--console`, `Get the resource console url`)
{% endif %}
{% endautoescape %}
.action(actionRunner({{ service.name | caseLower }}{{ method.name | caseUcfirst }}))

Expand Down
Loading

0 comments on commit 2014675

Please sign in to comment.