Skip to content

Commit

Permalink
feat: improved error handling for file permissions
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Oct 29, 2024
1 parent 3235497 commit c8472d0
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 14 deletions.
11 changes: 5 additions & 6 deletions src/commands/logout/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,12 @@ export const logoutCommand = program
.description('Logout from the Storyblok CLI')
.action(async () => {
const verbose = program.opts().verbose

const isAuth = await isAuthorized()
if (!isAuth) {
konsola.ok(`You are already logged out. If you want to login, please use the login command.`)
return
}
try {
const isAuth = await isAuthorized()
if (!isAuth) {
konsola.ok(`You are already logged out. If you want to login, please use the login command.`)
return
}
await removeAllNetrcEntries()

konsola.ok(`Successfully logged out`)
Expand Down
26 changes: 18 additions & 8 deletions src/creds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ export const getNetrcCredentials = async (filePath: string = getNetrcFilePath())
await access(filePath)
}
catch {
konsola.warn(`.netrc file not found at path: ${filePath}`)
return {}
}
try {
Expand Down Expand Up @@ -161,10 +160,16 @@ export const addNetrcEntry = async ({
let machines: Record<string, NetrcMachine> = {}

// Check if the file exists
await access(filePath)
// File exists, read and parse it
const content = await readFile(filePath, 'utf8')
machines = parseNetrcContent(content)
try {
await access(filePath)
// File exists, read and parse it
const content = await readFile(filePath, 'utf8')
machines = parseNetrcContent(content)
}
catch {
// File does not exist
konsola.ok(`.netrc file not found at path: ${filePath}. A new file will be created.`)
}

// Add or update the machine entry
machines[machineName] = {
Expand Down Expand Up @@ -227,9 +232,14 @@ export const removeNetrcEntry = async (
}

export function removeAllNetrcEntries(filePath = getNetrcFilePath()) {
return writeFile(filePath, '', {
mode: 0o600, // Set file permissions
})
try {
writeFile(filePath, '', {
mode: 0o600, // Set file permissions
})
}
catch (error) {
handleFileSystemError('write', error as NodeJS.ErrnoException)
}
}

export async function isAuthorized() {
Expand Down
1 change: 1 addition & 0 deletions src/utils/error/filesystem-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export class FileSystemError extends Error {
return {
name: this.name,
message: this.message,
code: this.code,
cause: this.cause,
errorId: this.errorId,
stack: this.stack,
Expand Down

0 comments on commit c8472d0

Please sign in to comment.