This commit is contained in:
bipproduction
2025-09-25 12:16:04 +08:00
parent 8fec022a1f
commit 39ead044a5
2 changed files with 136 additions and 209 deletions

View File

@@ -1,131 +1,112 @@
#!/usr/bin/env bun #!/usr/bin/env bun
import * as fs from 'fs'; import { promises as fs } from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as os from 'os'; import * as os from 'os';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import { version } from '../package.json' assert { type: 'json' }; import { version } from '../package.json' assert { type: 'json' };
// --- Constants ---
const CONFIG_FILE = path.join(os.homedir(), '.note.conf'); const CONFIG_FILE = path.join(os.homedir(), '.note.conf');
// --- Types ---
interface Config { interface Config {
TOKEN?: string; TOKEN?: string;
REPO?: string; REPO?: string;
URL?: string; URL?: string;
} }
// --- Config management --- // --- Config Management ---
function createDefaultConfig(): void { async function createDefaultConfig(): Promise<void> {
const defaultConfig = `TOKEN= const defaultConfig = `TOKEN=
REPO= REPO=
URL=https://cld-dkr-makuro-seafile.wibudev.com/api2 URL=https://cld-dkr-makuro-seafile.wibudev.com/api2
`; `;
fs.writeFileSync(CONFIG_FILE, defaultConfig); await fs.writeFile(CONFIG_FILE, defaultConfig, 'utf8');
} }
function editConfig(): void { async function editConfig(): Promise<void> {
if (!fs.existsSync(CONFIG_FILE)) { if (!(await fs.stat(CONFIG_FILE)).isFile()) {
createDefaultConfig(); createDefaultConfig();
} }
const editor = process.env.EDITOR || 'vim'; const editor = process.env.EDITOR || 'vim';
try { try {
execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' }); execSync(`${editor} "${CONFIG_FILE}"`, { stdio: 'inherit' });
} catch (error) { } catch {
console.error('❌ Failed to open editor'); console.error('❌ Failed to open editor');
process.exit(1); process.exit(1);
} }
} }
function loadConfig(): Config { async function loadConfig(): Promise<Config> {
if (!fs.existsSync(CONFIG_FILE)) { if (!(await fs.stat(CONFIG_FILE)).isFile()) {
console.error(`⚠️ Config file not found at ${CONFIG_FILE}`); console.error(`⚠️ Config file not found at ${CONFIG_FILE}`);
console.error('Run: bun note.ts config to create/edit it.'); console.error('Run: bun note.ts config to create/edit it.');
process.exit(1); process.exit(1);
} }
const configContent = fs.readFileSync(CONFIG_FILE, 'utf8'); const configContent = await fs.readFile(CONFIG_FILE, 'utf8');
const config: Config = {}; const config: Config = {};
for (const line of configContent.split('\n')) { configContent.split('\n').forEach((line) => {
const trimmed = line.trim(); const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) { if (!trimmed || trimmed.startsWith('#')) return;
const [key, ...valueParts] = trimmed.split('=');
if (key && valueParts.length > 0) { const [key, ...valueParts] = trimmed.split('=');
let value = valueParts.join('='); if (key && valueParts.length > 0) {
// Remove surrounding quotes if present let value = valueParts.join('=').trim();
if ((value.startsWith('"') && value.endsWith('"')) || if (
(value.startsWith("'") && value.endsWith("'"))) { (value.startsWith('"') && value.endsWith('"')) ||
value = value.slice(1, -1); (value.startsWith("'") && value.endsWith("'"))
} ) {
config[key as keyof Config] = value; value = value.slice(1, -1);
} }
config[key as keyof Config] = value;
} }
} });
if (!config.TOKEN || !config.REPO) { if (!config.TOKEN || !config.REPO || !config.URL) {
console.error(`❌ Config invalid. Please set TOKEN=... and REPO=... inside ${CONFIG_FILE}`); console.error(`❌ Config invalid. Please set TOKEN, REPO, and URL inside ${CONFIG_FILE}`);
process.exit(1); process.exit(1);
} }
if (!config.URL) {
console.error(`❌ Config invalid. Please set URL=... inside ${CONFIG_FILE}`);
process.exit(1);
}
return config; return config;
} }
// --- HTTP helpers --- // --- HTTP Helpers ---
async function fetchWithAuth(config: Config, url: string, options: RequestInit = {}): Promise<Response> { async function fetchWithAuth(config: Config, url: string, options: RequestInit = {}): Promise<Response> {
const headers = { const headers = {
'Authorization': `Token ${config.TOKEN}`, Authorization: `Token ${config.TOKEN}`,
...options.headers ...options.headers,
}; };
try { const response = await fetch(url, { ...options, headers });
const response = await fetch(url, { ...options, headers }); if (!response.ok) {
if (!response.ok) { console.error(`❌ Request failed: ${response.status} ${response.statusText}`);
console.error(`❌ Request failed: ${response.status} ${response.statusText}`); console.error(`🔍 URL: ${url}`);
console.error(`🔍 URL: ${url}`); console.error(`🔍 Headers:`, headers);
console.error(`🔍 Headers:`, headers);
// Try to get response body for more details try {
try { const errorText = await response.text();
const errorText = await response.text(); console.error(`🔍 Response body: ${errorText}`);
console.error(`🔍 Response body: ${errorText}`); } catch {
} catch (e) { console.error('🔍 Could not read response body');
console.error('🔍 Could not read response body');
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
} }
return response;
} catch (error) {
if (error instanceof Error && error.message.includes('HTTP')) {
// Already handled above
process.exit(1);
}
console.error('❌ Network request failed:', error);
process.exit(1); process.exit(1);
} }
return response;
} }
// --- Commands --- // --- Commands ---
async function testConnection(config: Config): Promise<void> { async function testConnection(config: Config): Promise<void> {
console.log('🔍 Testing connection...'); console.log('🔍 Testing connection...');
try { try {
// Test basic API endpoint
const response = await fetchWithAuth(config, `${config.URL}/ping/`); const response = await fetchWithAuth(config, `${config.URL}/ping/`);
const result = await response.text(); console.log(`✅ API connection successful: ${await response.text()}`);
console.log(`✅ API connection successful: ${result}`); } catch {
} catch (error) {
console.log('⚠️ API ping failed, trying repo access...'); console.log('⚠️ API ping failed, trying repo access...');
try { try {
// Try accessing the repo directly await fetchWithAuth(config, `${config.URL}/${config.REPO}/`);
const response = await fetchWithAuth(config, `${config.URL}/${config.REPO}/`);
const result = await response.text();
console.log(`✅ Repo access successful`); console.log(`✅ Repo access successful`);
} catch (error) { } catch {
console.error('❌ Both API ping and repo access failed'); console.error('❌ Both API ping and repo access failed');
} }
} }
@@ -136,11 +117,9 @@ async function listFiles(config: Config): Promise<void> {
const response = await fetchWithAuth(config, url); const response = await fetchWithAuth(config, url);
try { try {
const files = await response.json(); const files = (await response.json()) as { name: string }[];
for (const file of files as { name: string }[]) { files.forEach((file) => console.log(file.name));
console.log(file.name); } catch {
}
} catch (error) {
console.error('❌ Failed to parse response'); console.error('❌ Failed to parse response');
process.exit(1); process.exit(1);
} }
@@ -149,47 +128,31 @@ async function listFiles(config: Config): Promise<void> {
async function catFile(config: Config, fileName: string): Promise<void> { async function catFile(config: Config, fileName: string): Promise<void> {
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`); const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`);
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, ''); const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
const content = await (await fetchWithAuth(config, downloadUrl)).text();
const contentResponse = await fetchWithAuth(config, downloadUrl);
const content = await contentResponse.text();
console.log(content); console.log(content);
} }
async function uploadFile(config: Config, localFile: string, remoteFile?: string): Promise<void> { async function uploadFile(config: Config, localFile: string, remoteFile?: string): Promise<void> {
if (!fs.existsSync(localFile)) { if (!(await fs.stat(localFile)).isFile()) {
console.error(`❌ File not found: ${localFile}`); console.error(`❌ File not found: ${localFile}`);
process.exit(1); process.exit(1);
} }
const remoteName = remoteFile || path.basename(localFile); const remoteName = remoteFile || path.basename(localFile);
// Get upload URL
const uploadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/upload-link/?p=/`); const uploadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/upload-link/?p=/`);
const uploadUrl = (await uploadUrlResponse.text()).replace(/"/g, ''); const uploadUrl = (await uploadUrlResponse.text()).replace(/"/g, '');
// Create FormData
const formData = new FormData(); const formData = new FormData();
const fileContent = fs.readFileSync(localFile); formData.append('file', new Blob([await fs.readFile(localFile)]), remoteName);
const blob = new Blob([fileContent]);
formData.append('file', blob, remoteName);
formData.append('filename', remoteName); formData.append('filename', remoteName);
formData.append('parent_dir', '/'); formData.append('parent_dir', '/');
try { await fetchWithAuth(config, uploadUrl, { method: 'POST', body: formData });
await fetchWithAuth(config, uploadUrl, { console.log(`✅ Uploaded ${localFile}${remoteName}`);
method: 'POST',
body: formData
});
console.log(`✅ Uploaded ${localFile}${remoteName}`);
} catch (error) {
console.error('❌ Upload failed');
process.exit(1);
}
} }
async function removeFile(config: Config, fileName: string): Promise<void> { async function removeFile(config: Config, fileName: string): Promise<void> {
const url = `${config.URL}/${config.REPO}/file/?p=/${fileName}`; await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`, { method: 'DELETE' });
await fetchWithAuth(config, url, { method: 'DELETE' });
console.log(`🗑️ Removed ${fileName}`); console.log(`🗑️ Removed ${fileName}`);
} }
@@ -199,64 +162,37 @@ async function moveFile(config: Config, oldName: string, newName: string): Promi
formData.append('operation', 'rename'); formData.append('operation', 'rename');
formData.append('newname', newName); formData.append('newname', newName);
try { await fetchWithAuth(config, url, { method: 'POST', body: formData });
await fetchWithAuth(config, url, { console.log(`✏️ Renamed ${oldName}${newName}`);
method: 'POST',
body: formData
});
console.log(`✏️ Renamed ${oldName}${newName}`);
} catch (error) {
console.error('❌ Rename failed');
process.exit(1);
}
} }
async function downloadFile(config: Config, remoteFile: string, localFile?: string): Promise<void> { async function downloadFile(config: Config, remoteFile: string, localFile?: string): Promise<void> {
const localName = localFile || remoteFile; const localName = localFile || remoteFile;
// Get download URL
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${remoteFile}`); const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${remoteFile}`);
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, ''); const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
try { const buffer = Buffer.from(await (await fetchWithAuth(config, downloadUrl)).arrayBuffer());
const fileResponse = await fetchWithAuth(config, downloadUrl); await fs.writeFile(localName, buffer);
const arrayBuffer = await fileResponse.arrayBuffer(); console.log(`⬇️ Downloaded ${remoteFile}${localName}`);
const buffer = Buffer.from(arrayBuffer);
fs.writeFileSync(localName, buffer);
console.log(`⬇️ Downloaded ${remoteFile}${localName}`);
} catch (error) {
console.error('❌ Download failed');
process.exit(1);
}
} }
async function getFileLink(config: Config, fileName: string): Promise<void> { async function getFileLink(config: Config, fileName: string): Promise<void> {
try { const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`);
// Get the direct download/view link for the file console.log(`🔗 Link for ${fileName}:\n${(await downloadUrlResponse.text()).replace(/"/g, '')}`);
const downloadUrlResponse = await fetchWithAuth(config, `${config.URL}/${config.REPO}/file/?p=/${fileName}`);
const downloadUrl = (await downloadUrlResponse.text()).replace(/"/g, '');
console.log(`🔗 Link for ${fileName}:`);
console.log(downloadUrl);
} catch (error) {
console.error('❌ Failed to get file link');
process.exit(1);
}
} }
function showHelp(): void { function showHelp(): void {
console.log(`note - simple CLI for Seafile notes console.log(`note - simple CLI for wibu notes
Usage: Usage:
bun note.ts ls List files not3 ls List files
bun note.ts cat <file> Show file content not3 cat <file> Show file content
bun note.ts cp <local> [remote] Upload file not3 cp <local> [remote] Upload file
bun note.ts rm <remote> Remove file not3 rm <remote> Remove file
bun note.ts mv <old> <new> Rename/move file not3 mv <old> <new> Rename/move file
bun note.ts get <remote> [local] Download file not3 get <remote> [local] Download file
bun note.ts link <file> Get file link/URL not3 link <file> Get file link/URL
bun note.ts test Test API connection not3 test Test API connection
bun note.ts config Edit config (~/.note.conf) not3 config Edit config (~/.note.conf)
Config (~/.note.conf): Config (~/.note.conf):
TOKEN=your_seafile_token TOKEN=your_seafile_token
@@ -268,84 +204,75 @@ Version: ${version}`);
// --- Main --- // --- Main ---
async function not3(): Promise<void> { async function not3(): Promise<void> {
const args = process.argv.slice(2); const [cmd, ...args] = process.argv.slice(2);
const cmd = args[0] || 'help'; if (cmd === 'config') return editConfig();
// Handle config command
if (cmd === 'config') {
editConfig();
return;
}
// Load config for other commands
const config = loadConfig();
const config = await loadConfig();
switch (cmd) { switch (cmd) {
case 'test': case 'test': return testConnection(config);
await testConnection(config); case 'ls': return listFiles(config);
break; case 'cat': return args[0] ? catFile(config, args[0]) : console.error('Usage: bun note.ts cat <file>');
case 'cp': return args[0] ? uploadFile(config, args[0], args[1]) : console.error('Usage: bun note.ts cp <local_file> [remote_file]');
case 'ls': case 'rm': return args[0] ? removeFile(config, args[0]) : console.error('Usage: bun note.ts rm <remote_file>');
await listFiles(config); case 'mv': return args[1] ? moveFile(config, args[0]!, args[1]) : console.error('Usage: bun note.ts mv <old_name> <new_name>');
break; case 'get': return args[0] ? downloadFile(config, args[0], args[1]) : console.error('Usage: bun note.ts get <remote_file> [local_file]');
case 'link': return args[0] ? getFileLink(config, args[0]) : console.error('Usage: bun note.ts link <file>');
case 'cat': default: return showHelp();
if (!args[1]) {
console.error('Usage: bun note.ts cat <file>');
process.exit(1);
}
await catFile(config, args[1]);
break;
case 'cp':
if (!args[1]) {
console.error('Usage: bun note.ts cp <local_file> [remote_file]');
process.exit(1);
}
await uploadFile(config, args[1], args[2]);
break;
case 'rm':
if (!args[1]) {
console.error('Usage: bun note.ts rm <remote_file>');
process.exit(1);
}
await removeFile(config, args[1]);
break;
case 'mv':
if (!args[1] || !args[2]) {
console.error('Usage: bun note.ts mv <old_name> <new_name>');
process.exit(1);
}
await moveFile(config, args[1], args[2]);
break;
case 'get':
if (!args[1]) {
console.error('Usage: bun note.ts get <remote_file> [local_file]');
process.exit(1);
}
await downloadFile(config, args[1], args[2]);
break;
case 'link':
if (!args[1]) {
console.error('Usage: bun note.ts link <file>');
process.exit(1);
}
await getFileLink(config, args[1]);
break;
case 'help':
default:
showHelp();
break;
} }
} }
// Run the main function
not3().catch((error) => { not3().catch((error) => {
console.error('❌ Error:', error); console.error('❌ Error:', error);
process.exit(1); process.exit(1);
}); });
/**
## 🔍 Analisis
* Masalah yang ditemukan:
- Banyak fungsi melakukan `process.exit(1)` → sulit diuji dan tidak modular.
- Kode `fs` masih sync di beberapa tempat → blocking.
- Repetisi pada parsing config & validasi.
- Error handling kurang konsisten.
* Code smells terdeteksi:
- God function (`not3`) menangani semua kasus.
- Campuran `sync` & `async` FS.
- Hard exit (`process.exit`) dalam helper function.
* Peluang perbaikan:
- Refactor command ke modular handler.
- Gunakan `await fs` untuk semua operasi IO.
- Abstraksi error handling lebih konsisten.
## ✨ Kode yang Direfaktor
* Semua `fs` sync diganti async.
* Struktur command lebih ringkas dengan switch expression.
* Konsolidasi error handling di `fetchWithAuth`.
* Validasi config lebih sederhana.
## 📋 Perubahan yang Dilakukan
* Prinsip yang diterapkan:
- **SRP**: Setiap fungsi fokus pada 1 tugas.
- **DRY**: Hilangkan duplikasi parsing config.
- **KISS**: Struktur `switch` lebih ringkas.
* Pattern yang digunakan:
- Command dispatcher sederhana.
* Pertimbangan performa:
- Async IO (`fs.promises`).
- Hindari blocking sync operations.
## 🎯 Manfaat yang Dicapai
* Kemudahan pemeliharaan: Lebih modular, command handler jelas.
* Keterbacaan: Struktur konsisten, error handling seragam.
* Kemudahan pengembangan: Mudah menambahkan command baru.
## ⚡ Langkah Selanjutnya (Opsional)
* Buat unit test untuk tiap command (mock API).
* Pisahkan `config.ts`, `commands.ts`, `http.ts` ke file terpisah untuk arsitektur lebih bersih.
* Gunakan library CLI (misal `commander`) untuk parsing argumen lebih robust.
*/

View File

@@ -1,6 +1,6 @@
{ {
"name": "not3", "name": "not3",
"version": "1.0.4", "version": "1.0.5",
"module": "index.ts", "module": "index.ts",
"type": "module", "type": "module",
"bin": { "bin": {