@puls-atlas/cli
Version:
The Puls Atlas CLI tool for managing Atlas projects
75 lines • 2.74 kB
JavaScript
import fs from 'fs';
import path from 'path';
import inquirer from 'inquirer';
import { logger } from '../../utils/index.js';
export const COMPOSER_AUTH_GITIGNORE_ENTRY = 'auth.json';
export const COMPOSER_AUTH_FILE_MODE = 0o600;
export const createComposerTokenPrompt = () => ({
type: 'password',
name: 'token',
message: 'Enter the vendor token from packagist.com:',
validate: input => {
if (input.length === 0) {
return 'Please enter a valid developer token.';
}
return true;
}
});
export const createComposerAuthJson = token => ({
'http-basic': {
'puls.repo.packagist.com': {
username: 'token',
password: token
}
}
});
const hasIgnoreEntry = (contents, entry) => {
const normalizedEntries = contents.split(/\r?\n/u).map(line => line.trim()).filter(Boolean);
return normalizedEntries.includes(entry) || normalizedEntries.includes(`/${entry}`);
};
export const ensureIgnoreFileContainsEntry = (ignoreFilePath, entry) => {
const ignoreContents = fs.existsSync(ignoreFilePath) ? fs.readFileSync(ignoreFilePath, 'utf8') : '';
if (hasIgnoreEntry(ignoreContents, entry)) {
return 'unchanged';
}
const nextContents = ignoreContents.trim().length > 0 ? `${ignoreContents.replace(/\s*$/u, '')}\n${entry}\n` : `${entry}\n`;
fs.writeFileSync(ignoreFilePath, nextContents, 'utf8');
return ignoreContents.length > 0 ? 'updated' : 'created';
};
export const writeComposerAuthFile = (authJsonPath, authJson) => {
fs.writeFileSync(authJsonPath, JSON.stringify(authJson, null, 4), {
encoding: 'utf8',
mode: COMPOSER_AUTH_FILE_MODE
});
fs.chmodSync(authJsonPath, COMPOSER_AUTH_FILE_MODE);
};
export default async () => {
const cwd = process.cwd();
const authJsonPath = path.join(cwd, COMPOSER_AUTH_GITIGNORE_ENTRY);
const gitignorePath = path.join(cwd, '.gitignore');
if (fs.existsSync(authJsonPath)) {
logger.error('An auth.json file already exists.', false);
const {
overwrite
} = await inquirer.prompt([{
type: 'confirm',
name: 'overwrite',
message: 'Do you want to overwrite the existing auth.json file?',
default: false
}]);
if (!overwrite) {
return;
}
}
const {
token
} = await inquirer.prompt([createComposerTokenPrompt()]);
const authJson = createComposerAuthJson(token);
writeComposerAuthFile(authJsonPath, authJson);
const gitignoreStatus = ensureIgnoreFileContainsEntry(gitignorePath, COMPOSER_AUTH_GITIGNORE_ENTRY);
logger.success('auth.json file created.');
if (gitignoreStatus !== 'unchanged') {
logger.info('Added auth.json to .gitignore to reduce accidental commits.');
}
logger.warning('Keep auth.json out of version control and treat it as a secret.');
};