Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(config): support multiple profiles #25

Merged
merged 1 commit into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"lodash": "^4.17.21",
"stream-json": "^1.7.5",
"yaml": "^2.3.0",
"yargs": "^17.7.2"
"yargs": "^17.7.2",
"zod": "^3.22.2"
},
"devDependencies": {
"eslint": "^8.40.0",
Expand Down
3 changes: 2 additions & 1 deletion src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

import { parser } from "./parser.js";
import { isUsageError } from "./errors.js";
import { loadYargsConfig } from "./utils/config.js";

try {
await parser.parse();
await parser.config(loadYargsConfig()).parse();
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to catch load errors

} catch (err) {
if (isUsageError(err)) {
parser.showHelp();
Expand Down
3 changes: 2 additions & 1 deletion src/middleware/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { Client } from "@ibm-generative-ai/node-sdk";

import { version } from "../utils/version.js";

const agent = version ? `cli/${version}` : "cli";

export const clientMiddleware = (args) => {
const agent = version ? `cli/${version}` : "cli";
args.client = new Client({
apiKey: args.apiKey,
endpoint: args.endpoint,
Expand Down
15 changes: 15 additions & 0 deletions src/middleware/profile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { loadConfig } from "../utils/config.js";

// If profile has been selected, merge its configuration into yargs
export const profileMiddleware = (args) => {
if (!args.profile) return;

const { configuration, credentials } = loadConfig();
const profileConfig = {
...(configuration.profiles && configuration.profiles[args.profile]),
...(credentials.profiles && credentials.profiles[args.profile]),
};
Object.entries(profileConfig).forEach(([key, value]) => {
args[key] = value;
});
Comment on lines +12 to +14
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 This can probably be replaced with the following:

Object.assign(args, profileConfig)

};
45 changes: 34 additions & 11 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import { groupOptions } from "./utils/yargs.js";
import { loadConfig, mergeConfig, storeConfig } from "./utils/config.js";
import { clientMiddleware } from "./middleware/client.js";
import { profileMiddleware } from "./middleware/profile.js";

export const parser = yargs(hideBin(process.argv))
.options({
Expand All @@ -50,7 +51,13 @@ export const parser = yargs(hideBin(process.argv))
type: "number",
defaultDescription: "none",
},
profile: {
describe: "Use a specific profile from your configuration",
requiresArg: true,
type: "string",
},
})
.middleware(profileMiddleware)
.help()
.alias("h", "help")
.updateStrings({ "Options:": "Global Options:" })
Expand Down Expand Up @@ -88,13 +95,26 @@ export const parser = yargs(hideBin(process.argv))
configuration: {},
credentials: {},
};
const profile = await question("Profile (leave empty for default): ");
if (profile) {
config.configuration.profiles = { [profile]: {} };
config.credentials.profiles = { [profile]: {} };
}
const endpoint = await question("Endpoint (leave empty to skip): ");
if (endpoint) {
config.configuration.endpoint = endpoint;
if (profile) {
config.configuration.profiles[profile].endpoint = endpoint;
} else {
config.configuration.endpoint = endpoint;
}
}
const apiKey = await question("API Key (leave empty to skip): ");
if (apiKey) {
config.credentials.apiKey = apiKey;
if (profile) {
config.credentials.profiles[profile].apiKey = apiKey;
} else {
config.credentials.apiKey = apiKey;
}
}

rl.close();
Expand Down Expand Up @@ -1117,14 +1137,17 @@ export const parser = yargs(hideBin(process.argv))
.demandCommand(1, 1, "Please choose a command")
)
.demandCommand(1, 1, "Please choose a command")
.config(loadConfig().configuration)
.strict()
.fail(false)
.completion('completion', "Generate completion script", (current, argv, completionFilter, done) => {
completionFilter((err, defaultCompletions) => {
const filteredCompletions = defaultCompletions
.filter(completion => !completion.startsWith("$0"))
.filter(completion => !completion.startsWith("completion"))
done(filteredCompletions)
})
});
.completion(
"completion",
"Generate completion script",
(current, argv, completionFilter, done) => {
completionFilter((err, defaultCompletions) => {
const filteredCompletions = defaultCompletions
.filter((completion) => !completion.startsWith("$0"))
.filter((completion) => !completion.startsWith("completion"));
done(filteredCompletions);
});
}
);
76 changes: 70 additions & 6 deletions src/utils/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,71 @@ import fs, { writeFileSync } from "fs";

import YAML from "yaml";
import _ from "lodash";
import { z } from "zod";

const CONFIG_DIR_PATH = path.join(os.homedir(), ".genai");
const CONFIG_PATH = path.join(CONFIG_DIR_PATH, "configuration.yml");
// Credentials and their storage are defined by the Node SDK. Currently, the SDK doesn't expose any utilities to manage them.
const CREDENTIALS_PATH = path.join(CONFIG_DIR_PATH, "credentials.yml");

const configurationSchema = z
.object({
endpoint: z.string(), // default profile
profiles: z.record(
z
.object({
endpoint: z.string(),
})
.partial()
),
})
.partial();

const credentialsSchema = z
.object({
apiKey: z.string(), // default profile
profiles: z.record(
z
.object({
apiKey: z.string(),
})
.partial()
),
})
.partial();

const parseYamlFromFile = (path) =>
fs.existsSync(path) ? YAML.parse(fs.readFileSync(path, "utf8")) : {};

let cachedConfig = null;
export const loadConfig = () => {
const parseYamlFromFile = (path) =>
fs.existsSync(path) ? YAML.parse(fs.readFileSync(path, "utf8")) : {};
return {
configuration: parseYamlFromFile(CONFIG_PATH),
credentials: parseYamlFromFile(CREDENTIALS_PATH),
};
if (cachedConfig) return cachedConfig;
cachedConfig = {};
try {
cachedConfig.configuration = configurationSchema.parse(
parseYamlFromFile(CONFIG_PATH)
);
} catch (err) {
cachedConfig = null;
throw new Error(
`Failed to load the configuration, patch or remove ${CONFIG_PATH}\nDetails: ${YAML.stringify(
err.format()
)}`
);
}
try {
cachedConfig.credentials = credentialsSchema.parse(
parseYamlFromFile(CREDENTIALS_PATH)
);
} catch (err) {
cachedConfig = null;
throw new Error(
`Failed to load credentials, patch or remove ${CREDENTIALS_PATH}\nDetails: ${YAML.stringify(
err.format()
)}`
);
}
return cachedConfig;
};

export const storeConfig = (config) => {
Expand All @@ -25,9 +77,21 @@ export const storeConfig = (config) => {
}
writeFileSync(CONFIG_PATH, YAML.stringify(config.configuration ?? {}));
writeFileSync(CREDENTIALS_PATH, YAML.stringify(config.credentials ?? {}));
cachedConfig = config;
};

export const mergeConfig = (config) => {
const currentConfig = loadConfig();
storeConfig(_.merge({}, currentConfig, config));
};

export const loadYargsConfig = () => {
const {
configuration: { profiles: _, ...configuration },
credentials: { profiles: __, ...credentials },
} = loadConfig();
return {
...configuration,
...credentials,
};
};
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ __metadata:
stream-json: ^1.7.5
yaml: ^2.3.0
yargs: ^17.7.2
zod: ^3.22.2
bin:
genai: ./src/cli.js
languageName: unknown
Expand Down Expand Up @@ -1978,3 +1979,10 @@ __metadata:
checksum: f185ba87342ff16f7a06686767c2b2a7af41110c7edf7c1974095d8db7a73792696bcb4a00853de0d2edeb34a5b2ea6a55871bc864227dace682a0a28de33e1f
languageName: node
linkType: hard

"zod@npm:^3.22.2":
version: 3.22.2
resolution: "zod@npm:3.22.2"
checksum: 231e2180c8eabb56e88680d80baff5cf6cbe6d64df3c44c50ebe52f73081ecd0229b1c7215b9552537f537a36d9e36afac2737ddd86dc14e3519bdbc777e82b9
languageName: node
linkType: hard