import { Item } from '../fs/Item' import type { SimpleStream } from '../utils/SimpleStream' import { Program } from './Program' export class Mv extends Program { constructor() { super() } async Exec(_: SimpleStream, stdout: SimpleStream, workdir: Item, args: string[]): Promise { if (args.length < 3) { stdout.emit("mv: error: missing the first and/or second path arguments\n") return 1 } let item1: Item let item2: Item let destIsDir = false // figure out if the items are files or directories try { item1 = await Item.openDir(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)) } catch { item1 = await Item.open(Item.NormalizePath(args[1].startsWith('/') ? args[1] : `${workdir.GetPath()}/${args[1]}`)) } try { item2 = await Item.open(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`)) } catch { item2 = await Item.openDir(Item.NormalizePath(args[2].startsWith('/') ? args[2] : `${workdir.GetPath()}/${args[2]}`)) destIsDir = true } if (!await item1.Exists()) { stdout.emit(`mv: error: source item ${item1.GetPath()} does not exist.\n`) return 2 } if (await item2.Exists() && !destIsDir) { stdout.emit(`mv: error: destination item ${item2.GetPath()} already exists.\n`) return 2 } // either move the file into a destination directory or move it to a new path if (destIsDir) { const destChild = await Item.open(Item.NormalizePath(`${item2.GetPath()}/${item1.GetName()}`)) await item1.Copy(destChild) stdout.emit(`-> moved ${item1.GetPath()} -> ${destChild.GetPath()}\n`) } else { await item2.Create() await item1.Copy(item2) stdout.emit(`-> moved ${item1.GetPath()} -> ${item2.GetPath()}\n`) } await item1.Delete() return 0 } }