Skip to content

Commit

Permalink
feat: replace netrc with json
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Dec 18, 2024
1 parent 16c91fc commit d3ed9ed
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 16 deletions.
49 changes: 44 additions & 5 deletions src/creds.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,49 @@
import { access, readFile, writeFile } from 'node:fs/promises'
import { access } from 'node:fs/promises'
import { join } from 'node:path'
import { FileSystemError, handleFileSystemError, konsola } from './utils'
import chalk from 'chalk'
import { colorPalette, regionCodes } from './constants'
import { colorPalette } from './constants'
import { getStoryblokGlobalPath, readFile, saveToFile } from './utils/filesystem'

export interface NetrcMachine {
export const getCredentials = async (filePath = join(getStoryblokGlobalPath(), 'credentials.json')) => {
try {
await access(filePath)
const content = await readFile(filePath)
return JSON.parse(content)
}
catch (error) {
handleFileSystemError('read', error as NodeJS.ErrnoException)
return {}
}
}

export const addCredentials = async ({
filePath = join(getStoryblokGlobalPath(), 'credentials.json'),
machineName,
login,
password,
region,
}: Record<string, string>) => {
const credentials = {
...await getCredentials(filePath),
[machineName]: {
login,
password,
region,
},
}

try {
await saveToFile(filePath, JSON.stringify(credentials, null, 2), { mode: 0o600 })

konsola.ok(`Successfully added/updated entry for machine ${machineName} in ${chalk.hex(colorPalette.PRIMARY)(filePath)}`, true)
}
catch (error) {
throw new FileSystemError('invalid_argument', 'write', error as NodeJS.ErrnoException, `Error adding/updating entry for machine ${machineName} in .netrc file`)
}
}

/* export interface NetrcMachine {
login: string
password: string
region: string
Expand All @@ -15,7 +54,7 @@ export const getNetrcFilePath = () => {
process.platform.startsWith('win') ? 'USERPROFILE' : 'HOME'
] || process.cwd()
return join(homeDirectory, '.netrc')
return join(homeDirectory, '.storyblok')
}
const readNetrcFileAsync = async (filePath: string) => {
Expand Down Expand Up @@ -257,4 +296,4 @@ export async function isAuthorized() {
handleFileSystemError('authorization_check', error as NodeJS.ErrnoException)
return false
}
}
} */
8 changes: 6 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import './commands/user'
import './commands/pull-languages'

import { loginWithToken } from './commands/login/actions'

Check failure on line 12 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

'loginWithToken' is defined but never used
import { session } from './session'

dotenv.config() // This will load variables from .env into process.env
const program = getProgram()
Expand All @@ -31,8 +32,11 @@ program.command('test').action(async () => {
konsola.title(`Test`, '#8556D3', 'Attempting a test...')
const verbose = program.opts().verbose
try {
// await loginWithEmailAndPassword('aw', 'passwrod', 'eu')
await loginWithToken('WYSYDHYASDHSYD', 'eu')
const { state, updateSession, persistCredentials, initializeSession } = session()

Check failure on line 35 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

'updateSession' is assigned a value but never used. Allowed unused vars must match /^_/u

Check failure on line 35 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

'persistCredentials' is assigned a value but never used. Allowed unused vars must match /^_/u

await initializeSession()

console.log(state)
}
catch (error) {
handleError(error as Error, verbose)
Expand Down
10 changes: 5 additions & 5 deletions src/session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// session.ts
import type { RegionCode } from './constants'
import { addNetrcEntry, getCredentialsForMachine, getNetrcCredentials } from './creds'
import { addCredentials, getCredentials } from './creds'

interface SessionState {
isLoggedIn: boolean
Expand Down Expand Up @@ -29,9 +29,9 @@ function createSession() {
return
}

// If no environment variables, fall back to netrc
const machines = await getNetrcCredentials()
const creds = getCredentialsForMachine(machines, machineName)
// If no environment variables, fall back to .storyblok/credentials.json
const machines = await getCredentials()
const creds = machines[machineName || 'api.storyblok.com']
if (creds) {
state.isLoggedIn = true
state.login = creds.login
Expand Down Expand Up @@ -65,7 +65,7 @@ function createSession() {

async function persistCredentials(machineName: string) {
if (state.isLoggedIn && state.login && state.password && state.region) {
await addNetrcEntry({
await addCredentials({
machineName,
login: state.login,
password: state.password,
Expand Down
30 changes: 26 additions & 4 deletions src/utils/filesystem.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,20 @@
import { parse, resolve } from 'node:path'
import { mkdir, writeFile } from 'node:fs/promises'
import { join, parse, resolve } from 'node:path'
import { mkdir, readFile as readFileImpl, writeFile } from 'node:fs/promises'
import { handleFileSystemError } from './error/filesystem-error'

export const saveToFile = async (filePath: string, data: string) => {
export interface FileOptions {
mode?: number
}

export const getStoryblokGlobalPath = () => {
const homeDirectory = process.env[
process.platform.startsWith('win') ? 'USERPROFILE' : 'HOME'
] || process.cwd()

return join(homeDirectory, '.storyblok')
}

export const saveToFile = async (filePath: string, data: string, options: FileOptions) => {
// Get the directory path
const resolvedPath = parse(filePath).dir

Expand All @@ -17,11 +29,21 @@ export const saveToFile = async (filePath: string, data: string) => {

// Write the file
try {
await writeFile(filePath, data)
await writeFile(filePath, data, options)
}
catch (writeError) {
handleFileSystemError('write', writeError as Error)
}
}

export const readFile = async (filePath: string) => {
try {
return await readFileImpl(filePath, 'utf8')
}
catch (error) {
handleFileSystemError('read', error as Error)
return ''
}
}

export const resolvePath = (path: string | undefined, folder: string) => path ? resolve(process.cwd(), path) : resolve(resolve(process.cwd(), '.storyblok'), folder)

0 comments on commit d3ed9ed

Please sign in to comment.