import '@johnlindquist/kit'
import path from 'node:path'
interface FileInfo {
name: string
path: string
extension: string
}
const getFileInfo = (filePath: string): FileInfo => { const name = path.basename(filePath)
const extension = path.extname(filePath).toLowerCase()
return { name, path: filePath, extension }
}
const organizeByExtension = async (sourceDir: string, destinationRoot: string): Promise<void> => {
try {
const files = await readdir(sourceDir)
for (const file of files) {
const filePath = path.join(sourceDir, file)
const fileInfo = getFileInfo(filePath)
if (await isDir(filePath)) {
continue
}
const destinationDir = path.join(destinationRoot, fileInfo.extension.slice(1) || 'others')
await ensureDir(destinationDir)
const destinationPath = path.join(destinationDir, fileInfo.name)
if (await pathExists(destinationPath)) {
let i = 1
let newDestinationPath = ''
do {
const newName = fileInfo.name.replace(
fileInfo.extension,
`_${i}${fileInfo.extension}`
)
newDestinationPath = path.join(destinationDir, newName)
i++
} while (await pathExists(newDestinationPath))
await move(filePath, newDestinationPath)
} else {
await move(filePath, destinationPath)
}
}
} catch (error) {
console.error('Error organizing by extension:', error)
}
}
const organizeByDate = async (sourceDir: string, destinationRoot: string): Promise<void> => {
try {
const files = await readdir(sourceDir)
for (const file of files) {
const filePath = path.join(sourceDir, file)
if (await isDir(filePath)) {
continue
}
const stats = await stat(filePath)
const date = new Date(stats.mtime)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const destinationDir = path.join(destinationRoot, String(year), month)
await ensureDir(destinationDir)
const destinationPath = path.join(destinationDir, file)
if (await pathExists(destinationPath)) {
let i = 1
let newDestinationPath = ''
const fileInfo = getFileInfo(filePath)
do {
const newName = fileInfo.name.replace(
fileInfo.extension,
`_${i}${fileInfo.extension}`
)
newDestinationPath = path.join(destinationDir, newName)
i++
} while (await pathExists(newDestinationPath))
await move(filePath, newDestinationPath)
} else {
await move(filePath, destinationPath)
}
}
} catch (error) {
console.error('Error organizing by date:', error)
}
}
const sourceDir = await path({
placeholder: 'Select source directory',
onlyDirs: true,
})
const destinationRoot = await path({
placeholder: 'Select destination root directory',
onlyDirs: true,
})
const method = await arg('Organize files by:', ['Extension', 'Date'])
if (method === 'Extension') {
await organizeByExtension(sourceDir, destinationRoot)
} else if (method === 'Date') {
await organizeByDate(sourceDir, destinationRoot)
}