@ -1,56 +1,206 @@
import enquirer from "enquirer"
import enquirer from "enquirer"
import { watch } from "fs"
import { watch , constants as fsConstants } from "fs"
import { access , readFile , rename , stat , writeFile } from "fs/promises"
import { access , readFile , opendir , stat , writeFile } from "fs/promises"
import glob from "fast-glob"
import ini from "ini"
import ini from "ini"
import envPaths from "env-paths"
import envPaths from "env-paths"
import chalk from "chalk"
import chalk from "chalk"
import { isAbsolute , join , normalize , basename } from "path"
import { isAbsolute , join , normalize , basename , sep } from "path"
import { moveFile } from "move-file"
import isValidFilename from "valid-filename"
import makeDir from "make-dir"
import makeDir from "make-dir"
import homeDir from "home-dir"
import homeDir from "home-dir"
import "source-map-support/register"
import defaultData from "./default-data.json"
import packageData from "./package.json"
import buildTimestamp from "consts:buildTimestamp"
import configName from "consts:configName"
const { Toggle , Select , Input } = enquirer
const { Toggle , Select , Input , AutoComplete } = enquirer
const { R _OK , W _OK } = fsConstants
function log ( message ) {
function log ( message ) {
process . stderr . write ( message + "\n" )
process . stderr . write ( message + "\n" )
}
}
async function getDirectoryFromUser ( message , initial ) {
function validateFilenamePart ( part , { allowEmpty = false } = { } ) {
while ( true ) {
if ( typeof part !== "string" ) {
const newDir = normalize ( await new Input ( {
return ` must be a string, but was ${ part === null ? "null" : typeof part } `
message , initial
}
} ) . run ( ) )
if ( part . length === 0 ) {
if ( ! isAbsolute ( newDir ) ) {
if ( allowEmpty ) {
log ( chalk . red ( "Can't use that folder: This path must be absolute. Try again." ) )
return true
continue
} else {
return "must not be empty, but was empty"
}
}
if ( ! isValidFilename ( part + ".save" ) ) {
return ` cannot contain any of the following characters: <>:"/ \\ |?* `
}
return true
}
const DIRECTORY _OK = "OK"
const DIRECTORY _EMPTY = "Path is empty"
const DIRECTORY _NOT _ABSOLUTE = "Path must be absolute"
const DIRECTORY _NOT _VALID = "Path must contain segments which are valid filenames"
const DIRECTORY _EXISTS _NOT _DIRECTORY = "Path exists, but is not a directory"
const DIRECTORY _NOT _EXISTS = "Path does not exist"
const DIRECTORY _NOT _ACCESSIBLE = "Path is a directory, but is not both readable and writable"
function validatePath ( path ) {
if ( typeof path !== "string" || path . length === 0 ) {
return DIRECTORY _EMPTY
} else if ( ! isAbsolute ( path ) ) {
return DIRECTORY _NOT _ABSOLUTE
} else if ( ! path . split ( sep ) . slice ( 1 ) . every ( isValidFilename ) ) {
return DIRECTORY _NOT _VALID
}
return DIRECTORY _OK
}
async function validateDirectory ( path ) {
const pathValidity = validatePath ( path )
if ( pathValidity !== DIRECTORY _OK ) {
return pathValidity
}
}
try {
try {
const statResult = await stat ( newDir )
const statResult = await stat ( path )
if ( ! statResult . isDirectory ( ) ) {
if ( ! statResult . isDirectory ( ) ) {
log ( chalk . red ( "Can't use that folder: This path must be a directory. Try again." ) )
return DIRECTORY _EXISTS _NOT _DIRECTORY
}
}
return newDir
await access ( path , R _OK | W _OK )
} catch ( ex ) {
} catch ( ex ) {
if ( ex . code === "ENOENT" ) {
if ( ex . code === "ENOENT" ) {
return DIRECTORY _NOT _EXISTS
} else if ( ex . code === "EACCES" ) {
return DIRECTORY _NOT _ACCESSIBLE
} else {
throw ex
}
}
return DIRECTORY _OK
}
function validateRegExp ( text ) {
if ( typeof text !== "string" ) {
return ` must be a string, but was ${ text === null ? "null" : typeof text } `
}
try {
new RegExp ( text )
return true
} catch ( ex ) {
return ` must be a valid regular expression, but couldn't construct a RegExp with it: ${ ex } `
}
}
function validateFilenamePartList ( list , { minLength = 0 , allowMissing = false } = { } ) {
if ( typeof list === "undefined" ) {
if ( allowMissing ) {
return true
} else {
return ` must be present, but was absent `
}
}
if ( ! Array . isArray ( list ) ) {
return ` must be an array, but was ${ list === null ? typeof list : "null" } `
}
if ( list . length < minLength ) {
return ` must have at least ${ minLength } ${ minLength === 1 ? "element" : "elements" } , but had ${ list . length } `
}
const firstNonmatching = list . findIndex ( ( item ) => ! ( typeof item === "string" && item . length > 0 && validateFilenamePart ( item ) === true ) )
if ( firstNonmatching !== - 1 ) {
return ` element at index ${ firstNonmatching } ${ validateFilenamePart ( list [ firstNonmatching ] ) } `
}
return true
}
function validateGameData ( data ) {
if ( typeof data !== "object" || data === null ) {
return ` must be an object, but was ${ typeof data } `
}
const fileRegExpError = validateRegExp ( data . fileRegExp )
if ( validateRegExp ( data . fileRegExp ) !== true ) {
return ` fileRegExp ${ fileRegExpError } `
}
const charactersError = validateFilenamePartList ( data . characters , { allowMissing : true } )
if ( charactersError !== true ) {
return ` characters ${ charactersError } `
}
const timesError = validateFilenamePartList ( data . times , { minLength : 1 } )
if ( timesError !== true ) {
return ` times ${ timesError } `
}
const voreRolesError = validateFilenamePartList ( data . voreRoles , { minLength : 1 } )
if ( voreRolesError !== true ) {
return ` voreRoles ${ voreRolesError } `
}
const voreTypesError = validateFilenamePartList ( data . voreTypes , { minLength : 1 } )
if ( voreTypesError !== true ) {
return ` voreTypes ${ voreTypesError } `
}
const voreResultsError = validateFilenamePartList ( data . voreResults , { minLength : 1 } )
if ( voreResultsError !== true ) {
return ` voreResults ${ voreResultsError } `
}
const characterSceneTypesError = validateFilenamePartList ( data . characterSceneTypes , { allowMissing : true } )
if ( characterSceneTypesError !== true ) {
return ` characterSceneTypes ${ characterSceneTypesError } `
}
const otherSceneTypesError = validateFilenamePartList ( data . otherSceneTypes , { allowMissing : true } )
if ( otherSceneTypesError !== true ) {
return ` otherSceneTypes ${ otherSceneTypesError } `
}
return true
}
async function getDirectoryFromUser ( message , initial ) {
let dirState = null
let newDir = initial
while ( dirState !== DIRECTORY _OK ) {
newDir = normalize ( await new Input ( {
message ,
initial : newDir ,
validate : ( text ) => {
const pathErr = validatePath ( text )
if ( pathErr === DIRECTORY _OK ) {
return true
} else {
return pathErr
}
}
} ) . run ( ) )
try {
dirState = await validateDirectory ( newDir )
} catch ( ex ) {
log ( chalk . red ( ` Couldn't check on that folder: ${ chalk . redBright . bold ( ex ) } . Try again. ` ) )
dirState = null
}
if ( dirState === DIRECTORY _NOT _EXISTS ) {
const create = await new Toggle ( {
const create = await new Toggle ( {
message : "That folder doesn't exist. Want me to create it?" ,
message : "That folder doesn't exist. Want me to create it?" ,
enabled : "Create it" ,
enabled : "Yes, c reate it" ,
disabled : "No, I'll enter the path again" ,
disabled : "No, I'll enter the path again" ,
} ) . run ( )
} ) . run ( )
if ( ! create ) {
if ( create ) {
continue
}
try {
try {
await makeDir ( newDir )
await makeDir ( newDir )
return newDir
try {
dirState = await validateDirectory ( newDir )
if ( dirState !== DIRECTORY _OK ) {
log ( chalk . red ( ` Creating the new folder led to an unusable directory: ${ chalk . redBright . bold ( dirState ) } . Try again. ` ) )
}
} catch ( ex ) {
log ( chalk . red ( ` Couldn't check on the new folder: ${ chalk . redBright . bold ( ex ) } . Try again. ` ) )
}
} catch ( ex ) {
} catch ( ex ) {
log ( chalk . red ( ` Couldn't create that folder: ${ chalk . redBright . bold ( ex ) } . Try again. ` ) )
log ( chalk . red ( ` Couldn't create that folder: ${ chalk . redBright . bold ( ex ) } . Try again. ` ) )
}
}
} else {
log ( chalk . red ( ` Couldn't check on that folder: ${ chalk . redBright . bold ( ex ) } . Try again. ` ) )
}
}
} else if ( dirState !== null && dirState !== DIRECTORY _OK ) {
log ( chalk . red ( ` Can't use that folder: ${ dirState } . Try again. ` ) )
}
}
}
}
return newDir
}
}
async function loadPaths ( config , home ) {
async function loadPaths ( config , home ) {
@ -74,26 +224,65 @@ async function loadPaths(config, home) {
}
}
}
}
}
}
if ( ! ( sourceDir && destDir ) ) {
const sourceDirOK = ( await validateDirectory ( sourceDir ) ) === DIRECTORY _OK
log ( chalk . yellow ( ` Configuration at ${ chalk . yellowBright . bold ( configPath ) } is missing or incomplete. Configure now. ` ) )
const destDirOK = ( await validateDirectory ( destDir ) ) === DIRECTORY _OK
if ( ! ( sourceDirOK && destDirOK ) ) {
log ( chalk . yellow ( ` Configuration at ${ chalk . yellowBright . bold ( configPath ) } is missing, incomplete, or damaged. Configuring now. ` ) )
if ( ! sourceDirOK ) {
sourceDir = await getDirectoryFromUser (
sourceDir = await getDirectoryFromUser (
"Where are SMVA saves downloaded to? (e.g., your Downloads folder)" ,
"Where are SMVA saves downloaded to? (e.g., your Downloads folder)" ,
sourceDir || join ( home , "Downloads" ) )
sourceDir || join ( home , "Downloads" ) )
}
if ( ! destDirOK ) {
destDir = await getDirectoryFromUser (
destDir = await getDirectoryFromUser (
"Where do you want to store your organized SMVA saves? (e.g., your Documents folder)" ,
"Where do you want to store your organized SMVA saves? (e.g., your Documents folder)" ,
destDir || join ( home , "Documents" , "SMVA Saves" )
destDir || join ( home , "Documents" , "SMVA Saves" )
)
)
}
try {
await makeDir ( config )
await makeDir ( config )
await writeFile ( configPath , ini . encode ( { paths : { source : sourceDir , dest : destDir } } ) , { encoding : "utf-8" } )
await writeFile ( configPath , ini . encode ( { paths : { source : sourceDir , dest : destDir } } ) , { encoding : "utf-8" } )
log ( chalk . cyan ( ` Wrote configuration to ${ chalk . cyanBright . bold ( configPath ) } ` ) )
log ( chalk . cyan ( ` Wrote configuration to ${ chalk . cyanBright . bold ( configPath ) } ` ) )
} catch ( ex ) {
log ( chalk . red ( ` Could not write configuration to ${ chalk . redBright . bold ( configPath ) } ` ) )
}
}
const dataPath = join ( config , "game-data.json" )
let data = defaultData
try {
data = JSON . parse ( await readFile ( dataPath , { encoding : "utf-8" } ) )
const err = validateGameData ( data )
if ( err === true ) {
log ( chalk . cyan ( ` Read game data from ${ chalk . cyanBright . bold ( dataPath ) } ` ) )
} else {
log ( chalk . red ( ` ${ chalk . redBright . bold ( dataPath ) } had a problem: ${ chalk . redBright . bold ( err ) } ` ) )
log ( chalk . yellow ( ` Using default game data. ` ) )
data = defaultData
}
}
return { sourceDir , destDir }
} catch ( ex ) {
switch ( ex . code ) {
case "ENOENT" :
log ( chalk . yellow ( ` ${ chalk . yellowBright . bold ( dataPath ) } not found. Using default game data. ` ) )
try {
await writeFile ( dataPath , JSON . stringify ( defaultData , null , 4 ) , { encoding : "utf-8" } )
log ( chalk . cyan ( ` Wrote default game data to ${ chalk . cyanBright . bold ( dataPath ) } ` ) )
} catch ( ex ) {
log ( chalk . red ( ` Could not write default game data to ${ chalk . redBright . bold ( dataPath ) } : ${ chalk . redBright . bold ( ex ) } ` ) )
}
break
default :
log ( chalk . red ( ` Could not read game data from ${ chalk . redBright . bold ( dataPath ) } : ${ chalk . redBright . bold ( ex ) } ` ) )
log ( chalk . yellow ( ` Using default game data. ` ) )
}
}
return { sourceDir , destDir , data }
}
}
async function * watchNewSaves ( sourceDir ) {
async function * watchNewSaves ( sourceDir , sourceRegexpString ) {
const sourceRe = /^saint-miluinas-vore-academy-.*\.save$/
const sourceRe = new RegExp ( ` ^ ${ sourceRegexpString } \$ ` )
let resolveNext
let resolveNext
let nextPromise
let nextPromise
let active = true
function makeNewPromise ( ) {
function makeNewPromise ( ) {
nextPromise = new Promise ( ( resolve ) => {
nextPromise = new Promise ( ( resolve ) => {
@ -103,90 +292,144 @@ async function* watchNewSaves(sourceDir) {
}
}
} )
} )
}
}
makeNewPromise ( )
makeNewPromise ( )
watch ( sourceDir , { } , ( eventType , filename ) => {
watch ( sourceDir , { } , ( eventType , filename ) => {
if ( eventType === "rename" && sourceRe . test ( filename ) ) {
if ( eventType === "rename" && sourceRe . test ( filename ) ) {
resolveNext ( join ( sourceDir , filename ) )
resolveNext ( filename )
}
}
} )
} )
log ( chalk . cya n( ` Waiting for new saves to appear in ${ chalk . cya nBright. bold ( sourceDir ) } ` ) )
log ( chalk . gree n( ` Waiting for new saves with filenames like ${ chalk . greenBright . bold ( ` / ${ sourceRegexpString } / ` ) } to appear in ${ chalk . gree nBright. bold ( sourceDir ) } ` ) )
while ( true ) {
while ( true ) {
yield await nextPromise
const next = await nextPromise
if ( next && active ) {
yield next
}
}
}
}
}
async function findExistingSaves ( sourceDir ) {
async function * findExistingSaves ( sourceDir , sourceRegexpString ) {
const sourceGlob = ` ${ glob . escapePath ( sourceDir ) } /saint-miluinas-vore-academy-*.save `
const sourceRe = new RegExp ( ` ^ ${ sourceRegexpString } \$ ` )
return glob ( sourceGlob , { "onlyFiles" : true } )
log ( chalk . green ( ` Scanning for existing saves with filenames like ${ chalk . greenBright . bold ( ` / ${ sourceRegexpString } / ` ) } in ${ chalk . greenBright . bold ( sourceDir ) } ` ) )
const dir = await opendir ( sourceDir )
for await ( const dirent of dir ) {
if ( dirent . isFile ( ) && sourceRe . test ( dirent . name ) ) {
yield dirent . name
}
}
log ( chalk . cyan ( ` Finished scanning for existing saves ` ) )
}
}
async function promptForFilename ( ) {
async function promptForFilename ( {
const saveType = await new Select ( {
times ,
voreTypes ,
voreRoles ,
voreResults ,
characterSceneTypes ,
otherSceneTypes ,
characters
} ) {
const saveType = await new AutoComplete ( {
message : "What type of save is this?" ,
message : "What type of save is this?" ,
choices : [ "Useful Save" , "Vore Scene" , "Skip This Save" ] ,
limit : 10 ,
choices : [ "Useful Save" , "Vore Scene" , ... ( Array . isArray ( characterSceneTypes ) && characterSceneTypes . length > 0 ? characterSceneTypes . map ( ( item ) => ` ${ item } (Character Scene) ` ) : [ ] ) , ... ( Array . isArray ( otherSceneTypes ) && otherSceneTypes . length > 0 ? otherSceneTypes . map ( ( item ) => ` ${ item } (Other Scene) ` ) : [ ] ) , "Skip This Save" ] ,
} ) . run ( )
} ) . run ( )
const dayPrompt = new Select ( {
const timePrompt = times . length > 1 ? new AutoComplete ( {
message : "When is this save from?" ,
message : "When is this save from?" ,
choices : [ "Day 1" , "Day 2" , "Day 3" , "Day 4" , "Day 5" , "Day 6" ]
limit : 10 ,
} )
choices : times
} ) : {
async run ( ) {
return times [ 0 ]
}
}
if ( saveType === "Vore Scene" ) {
if ( saveType === "Vore Scene" ) {
const voreType = await new Select ( {
const voreType = voreTypes . length > 1 ? await new AutoComplete ( {
message : "What type of vore is involved in this save?" ,
message : "What type of vore is involved in this save?" ,
choices : [ "Oral" , "Anal" , "Unbirth" ]
limit : 10 ,
} ) . run ( )
choices : voreTypes
const voreRole = await new Select ( {
} ) . run ( ) : voreTypes [ 0 ]
const voreRole = voreRoles . length > 1 ? await new AutoComplete ( {
message : "What role does the player play in this scene?" ,
message : "What role does the player play in this scene?" ,
choices : [ "Predator" , "Prey" , "Observer" ]
limit : 10 ,
} ) . run ( )
choices : voreRoles
const voreResult = await new Select ( {
} ) . run ( ) : voreRoles [ 0 ]
const voreResult = voreResults . length > 1 ? await new AutoComplete ( {
message : "What is the result of the vore?" ,
message : "What is the result of the vore?" ,
choices : [ "Fatal" , "Always Fatal" , "Non-fatal" ] ,
limit : 10 ,
} ) . run ( )
choices : voreResults ,
const day = await dayPrompt . run ( )
} ) . run ( ) : voreResults [ 0 ]
const vorePartner = await new Input ( {
const time = await timePrompt . run ( )
const vorePartners = Array . isArray ( characters ) && characters . length > 0 ? await new AutoComplete ( {
message : "Who is/are the partner(s) the player is with in this scene?" ,
message : "Who is/are the partner(s) the player is with in this scene?" ,
} ) . run ( )
limit : 10 ,
choices : characters ,
multiple : true ,
} ) . run ( ) : [ ]
const voreVariant = await new Input ( {
const voreVariant = await new Input ( {
message : "What is the variant name/comment for this scene? (leave blank to skip)" ,
message : ` What is the variant name/comment for this scene? ${ vorePartners . length > 0 ? " (leave blank to skip)" : "" } ` ,
validate : ( filename ) => validateFilenamePart ( filename , { allowEmpty : vorePartners . length > 0 } )
} ) . run ( )
} ) . run ( )
return ` ${ voreType } ${ voreRole } - ${ voreResult } - ${ day } ${ vorePartner } ${ voreVariant ? ` ( ${ voreVariant } ) ` : "" } .save `
return ` ${ voreType } ${ voreRole } - ${ voreResult } - ${ time } ${ vorePartners . join ( " + " ) } ${ voreVariant ? vorePartners . length > 0 ? ` ( ${ voreVariant } ) ` : voreVariant : "" } .save `
} else if ( saveType === "Useful Save" ) {
} else if ( saveType === "Useful Save" ) {
const day = await dayPrompt . run ( )
const time = await timePrompt . run ( )
const title = await new Input ( {
message : "What is the title of this useful save?" ,
validate : validateFilenamePart
} ) . run ( )
return ` Useful Saves - ${ time } - ${ title } .save `
} else if ( saveType . endsWith ( " (Character Scene)" ) ) {
const sceneType = saveType . substring ( 0 , saveType . length - " (Character Scene)" . length )
const time = await timePrompt . run ( )
const scenePartners = Array . isArray ( characters ) && characters . length > 0 ? await new AutoComplete ( {
message : "Who is/are the partner(s) the player is with in this scene?" ,
limit : 10 ,
choices : characters ,
multiple : true ,
validate : ( list ) => list . length > 0 ,
} ) . run ( ) : [ ]
const title = await new Input ( {
const title = await new Input ( {
message : "What is the title of this useful save?"
message : ` What is the comment for this ${ sceneType } scene? ` ,
validate : validateFilenamePart
} ) . run ( )
} ) . run ( )
return ` Useful Saves - ${ day } - ${ title } .save `
return ` ${ sceneType } with ${ scenePartners . join ( "+" ) } - ${ time } - ${ title } .save `
} else if ( saveType . endsWith ( " (Other Scene)" ) ) {
const sceneType = saveType . substring ( 0 , saveType . length - " (Other Scene)" . length )
const time = await timePrompt . run ( )
const title = await new Input ( {
message : ` What is the comment for this ${ sceneType } scene? ` ,
validate : validateFilenamePart
} ) . run ( )
return ` ${ sceneType } - ${ time } - ${ title } .save `
} else {
} else {
return null
return null
}
}
}
}
async function shouldDoRename ( destPath ) {
async function askIfOverwrite ( destPath ) {
try {
await access ( destPath )
console . log ( chalk . yellow ( ` A file named ${ chalk . yellowBright . bold ( destPath ) } already exists. ` ) )
console . log ( chalk . yellow ( ` A file named ${ chalk . yellowBright . bold ( destPath ) } already exists. ` ) )
} catch ( ex ) {
const result = await new Select ( {
if ( ex . code === "ENOENT" ) {
message : "What should we do?" ,
return true
choices : [ "Skip it" , "Rename it" , "Overwrite it" ]
} else {
} ) . run ( )
console . log ( chalk . red ( ` The file named ${ chalk . redBright . bold ( destPath ) } could not be accessed: ${ chalk . redBright . bold ( ex ) } ` ) )
}
}
const result = await new Select ( { message : "What should we do?" , choices : [ "Skip it" , "Rename it" , "Overwrite it" ] } ) . run ( ) ;
switch ( result ) {
switch ( result ) {
case "Skip it" :
case "Skip it" :
return false ;
return false
case "Overwrite it" :
case "Overwrite it" :
return true ;
return true
case "Rename it" :
case "Rename it" :
return ( await new Input ( { message : "What would you like to name the file?" , initial : basename ( destPath , ".save" ) } ) . run ( ) ) + ".save"
return ( await new Input ( {
message : "What would you like to name the file?" ,
initial : basename ( destPath , ".save" ) ,
validate : ( name ) => name . length > 0 && isValidFilename ( name ) ? true : "must be a nonempty string not ending in trailing periods or containing any of the characters <>:\"/\\|?*"
} ) . run ( ) ) + ".save"
}
}
}
}
function queueMovingTo ( destDir ) {
function queueMovingTo ( destDir , filenameData ) {
let resolvePromise , rejectPromise
let resolvePromise , rejectPromise
const completionPromise = new Promise ( ( resolve , reject ) => {
const completionPromise = new Promise ( ( resolve , reject ) => {
resolvePromise = resolve
resolvePromise = resolve
@ -194,6 +437,7 @@ function queueMovingTo(destDir) {
} )
} )
const filequeue = [ ]
const filequeue = [ ]
let processingFiles = false
let processingFiles = false
let endAfterCompleting = false
async function processFiles ( ) {
async function processFiles ( ) {
if ( processingFiles ) {
if ( processingFiles ) {
@ -203,7 +447,7 @@ function queueMovingTo(destDir) {
while ( filequeue . length > 0 ) {
while ( filequeue . length > 0 ) {
const nextFile = filequeue [ 0 ]
const nextFile = filequeue [ 0 ]
try {
try {
access ( nextFile )
await access ( nextFile )
} catch ( ex ) {
} catch ( ex ) {
if ( ex . code !== "ENOENT" ) {
if ( ex . code !== "ENOENT" ) {
log ( chalk . red ( ` failed accessing ${ chalk . redBright . bold ( nextFile ) } : ${ chalk . redBright . bold ( ex ) } ` ) )
log ( chalk . red ( ` failed accessing ${ chalk . redBright . bold ( nextFile ) } : ${ chalk . redBright . bold ( ex ) } ` ) )
@ -212,37 +456,52 @@ function queueMovingTo(destDir) {
continue
continue
}
}
log ( chalk . green ( ` For save ${ chalk . greenBright . bold ( nextFile ) } : ` ) )
log ( chalk . green ( ` For save ${ chalk . greenBright . bold ( nextFile ) } : ` ) )
const destFilename = await promptForFilename ( )
const destFilename = await promptForFilename ( filenameData )
if ( ! destFilename ) {
if ( ! destFilename ) {
log ( chalk . yellow ( "Skipped." ) )
log ( chalk . yellow ( "Skipped." ) )
filequeue . shift ( )
filequeue . shift ( )
continue
continue
}
}
let destPath = join ( destDir , destFilename )
let destPath = join ( destDir , destFilename )
let confirmed = false ;
let overwrite = false
while ( ! confirmed ) {
while ( true ) {
const promptResult = await shouldDoRename ( destPath )
try {
await moveFile ( nextFile , destPath , { overwrite } )
log ( chalk . cyan ( ` Moved to ${ chalk . cyanBright . bold ( destPath ) } ` ) )
break
} catch ( ex ) {
if ( ex . message . startsWith ( "The destination file exists:" ) ) {
const promptResult = await askIfOverwrite ( destPath )
if ( typeof promptResult === "string" ) {
if ( typeof promptResult === "string" ) {
destPath = join ( destDir , promptResult )
destPath = join ( destDir , promptResult )
} else if ( ! promptResult ) {
} else if ( promptResult === true ) {
destPath = null
overwrite = true
confirmed = true
} else {
} else {
confirmed = true
break
}
} else {
log ( chalk . red ( ` Something went wrong: ${ chalk . redBright . bold ( ex ) } ` ) )
const giveUp = await new Toggle ( {
message : "Want to keep trying?" ,
disabled : "Yes, try again" ,
enabled : "No, skip this save"
} ) . run ( )
if ( giveUp ) {
break
}
}
}
}
}
if ( ! destPath ) {
log ( chalk . yellow ( "Skipped." ) )
filequeue . shift ( )
continue
}
}
await rename ( nextFile , destPath )
log ( chalk . cyan ( ` Moved to ${ chalk . cyanBright . bold ( destPath ) } ` ) )
filequeue . shift ( )
filequeue . shift ( )
}
}
processingFiles = false
processingFiles = false
if ( endAfterCompleting ) {
resolvePromise ( )
}
}
}
log ( chalk . green ( ` Ready to move renamed saves to ${ chalk . greenBright . bold ( destDir ) } ` ) )
return {
return {
push ( ... files ) {
push ( ... files ) {
if ( ! rejectPromise ) {
if ( ! rejectPromise ) {
@ -253,49 +512,69 @@ function queueMovingTo(destDir) {
filequeue . push ( file )
filequeue . push ( file )
}
}
}
}
processFiles ( ) . catch ( ( ) => {
processFiles ( ) . catch ( ( err ) => {
if ( ! rejectPromise ) {
if ( ! rejectPromise ) {
return
return
}
}
rejectPromise ( )
rejectPromise ( err )
resolvePromise = null
resolvePromise = null
rejectPromise = null
rejectPromise = null
} )
} )
} ,
} ,
complete ( ) {
shutDown ( ) {
if ( ! resolvePromise ) {
if ( ! resolvePromise ) {
throw Error ( "Already stopped the queue" )
return
}
}
if ( processingFiles ) {
endAfterCompleting = true
} else {
resolvePromise ( )
resolvePromise ( )
resolvePromise = null
}
rejectPromise = null
} ,
} ,
completionPromise
completionPromise
}
}
}
}
async function main ( ) {
export async function main ( ) {
const { config } = envPaths ( "SMVA-Indexer" )
log ( chalk . green ( ` ${ packageData . name } ${ chalk . greenBright . bold ( ` v ${ packageData . version } ` ) } - built at ${ chalk . greenBright . bold ( new Date ( buildTimestamp ) . toISOString ( ) ) } ` ) )
const { config } = envPaths ( configName )
const home = homeDir ( )
const home = homeDir ( )
const { sourceDir , destDir } = await loadPaths ( config , home )
const {
const queue = queueMovingTo ( destDir )
sourceDir ,
destDir ,
data : { fileRegExp , ... filenameData }
} = await loadPaths ( config , home )
const queue = queueMovingTo ( destDir , filenameData )
const existingSavesPromise = ( async ( ) => {
const existingSavesPromise = ( async ( ) => {
try {
try {
const existingSaves = await findExistingSaves ( sourceDir )
for await ( const oldSave of findExistingSaves ( sourceDir , fileRegExp ) ) {
log ( chalk . cyan ( ` found ${ chalk . cyanBright . bold ( existingSaves . length ) } existing saves ` ) )
queue . push ( join ( sourceDir , oldSave ) )
queue . push ( ... existingSaves )
}
} catch ( ex ) {
} catch ( ex ) {
log ( chalk . red ( ` failed searching for existing saves: ${ chalk . redBright . bold ( ex ) } ` ) )
log ( chalk . red ( ` failed searching for existing saves: ${ chalk . redBright . bold ( ex ) } ` ) )
}
}
} ) ( )
} ) ( )
const newSavesPromise = ( async ( ) => {
const newSavesPromise = ( async ( ) => {
for await ( const newSave of watchNewSaves ( sourceDir ) ) {
try {
queue . push ( newSave )
for await ( const newSave of watchNewSaves ( sourceDir , fileRegExp ) ) {
queue . push ( join ( sourceDir , newSave ) )
}
} catch ( ex ) {
log ( chalk . red ( ` failed waiting for new saves: ${ chalk . redBright . bold ( ex ) } ` ) )
}
}
} ) ( )
} ) ( )
await Promise . all ( [ newSavesPromise , existingSavesPromise , queue . completionPromise ] )
Promise . allSettled ( [ newSavesPromise , existingSavesPromise ] ) . finally ( ( ) => queue . shutDown ( ) )
try {
await queue . completionPromise
} catch ( err ) {
console . log ( chalk . redBright . bold ( err ) )
process . exit ( 1 )
}
process . exit ( 0 )
}
}
main ( )
main . packageName = packageData . name
main . version = packageData . version
main . buildTimestamp = packageData . buildTimestamp