Storage was replaced by FileSystem

This commit is contained in:
Robert Vokac 2024-10-12 09:09:28 +02:00
parent 21aff3602f
commit ac7eb2e78b
Signed by: robertvokac
GPG Key ID: FB9CE8E20AADA55F
33 changed files with 564 additions and 539 deletions

View File

@ -25,7 +25,7 @@ import java.util.List;
*
* @author robertvokac
*/
public interface FileHandle {
public interface File {
FileType type();
@ -37,7 +37,7 @@ public interface FileHandle {
String nameWithoutExtension();
List<FileHandle> list();
List<File> list();
default boolean isDirectory() {
return type() == FileType.DIRECTORY;
@ -47,11 +47,11 @@ public interface FileHandle {
return type() == FileType.FILE;
}
FileHandle child(String name);
File child(String name);
FileHandle sibling(String name);
File sibling(String name);
FileHandle parent();
File parent();
boolean mkdir();
@ -65,15 +65,15 @@ public interface FileHandle {
boolean emptyDirectory();
boolean copyTo(FileHandle destination);
boolean copyTo(File destination);
boolean moveTo(FileHandle destination);
boolean moveTo(File destination);
long length();
FileHandle tempFile(String prefix);
File tempFile(String prefix);
FileHandle tempDirectory(String prefix);
File tempDirectory(String prefix);
int depth();
@ -89,5 +89,5 @@ public interface FileHandle {
void flush();
Storage getStorage();
FileSystem getFileSystem();
}

View File

@ -22,19 +22,19 @@ package com.pixelgamelibrary.api.files;
import com.pixelgamelibrary.api.PixelException;
/**
* StorageException is a custom exception class that extends {@link PixelException}.
* It represents exceptions that occur within the storage system of the Pixel Game Library.
* FileException is a custom exception class that extends {@link PixelException}.
* It represents exceptions that occur within the file system of the Pixel Game Library.
*
* @author robertvokac
*/
public class StorageException extends PixelException {
public class FileException extends PixelException {
/**
* Constructs a new StorageException with the specified detail message.
* Constructs a new FileException with the specified detail message.
*
* @param string the detail message for this exception.
*/
public StorageException(String string) {
public FileException(String string) {
super(string);
}

View File

@ -27,15 +27,15 @@ import java.util.List;
*
* @author robertvokac
*/
public class FileHandleImpl implements FileHandle {
public class FileImpl implements File {
private final Storage storage;
private final FileSystem fs;
private final String path;
private String name;
public FileHandleImpl(Storage storage, String path) {
this.storage = storage;
this.path = path.equals(".") ? storage.printWorkingDirectory() : path;
public FileImpl(FileSystem fsIn, String path) {
this.fs = fsIn;
this.path = path.equals(".") ? fsIn.printWorkingDirectory() : path;
{
if (path.equals("/")) {
name = path;
@ -48,7 +48,7 @@ public class FileHandleImpl implements FileHandle {
@Override
public FileType type() {
return storage.type(path);
return fs.type(path);
}
@Override
@ -78,36 +78,36 @@ public class FileHandleImpl implements FileHandle {
}
@Override
public List<FileHandle> list() {
List<String> list = storage.list(path);
List<FileHandle> files = new ArrayList<>();
public List<File> list() {
List<String> list = fs.list(path);
List<File> files = new ArrayList<>();
for(String s:list) {
files.add(new FileHandleImpl(storage, s));
files.add(new FileImpl(fs, s));
}
return files;
}
@Override
public FileHandle child(String name) {
return new FileHandleImpl(storage, path + "/" + name);
public File child(String name) {
return new FileImpl(fs, path + "/" + name);
}
@Override
public FileHandle sibling(String siblingName) {
public File sibling(String siblingName) {
int nameLength = name.length();
String f = path.substring(0, path.length() - nameLength - 1) + "/" + siblingName;
return new FileHandleImpl(storage, f);
return new FileImpl(fs, f);
}
@Override
public FileHandle parent() {
return new FileHandleImpl(storage, path.substring(0, path.length() - name.length() - 1));
public File parent() {
return new FileImpl(fs, path.substring(0, path.length() - name.length() - 1));
}
@Override
public boolean mkdir() {
return storage.createDirectory(path).isEmpty();
return fs.createDirectory(path).isEmpty();
}
@Override
@ -117,17 +117,17 @@ public class FileHandleImpl implements FileHandle {
@Override
public boolean exists() {
return storage.exists(path);
return fs.exists(path);
}
@Override
public boolean delete() {
return storage.remove(path);
return fs.remove(path);
}
@Override
public boolean deleteDirectory() {
return storage.removeDirectory(path);
return fs.removeDirectory(path);
}
@Override
@ -136,13 +136,13 @@ public class FileHandleImpl implements FileHandle {
}
@Override
public boolean copyTo(FileHandle destination) {
return storage.copy(path, destination.path()).isEmpty();
public boolean copyTo(File destination) {
return fs.copy(path, destination.path()).isEmpty();
}
@Override
public boolean moveTo(FileHandle destination) {
return storage.move(path, destination.path()).isEmpty();
public boolean moveTo(File destination) {
return fs.move(path, destination.path()).isEmpty();
}
@Override
@ -150,7 +150,7 @@ public class FileHandleImpl implements FileHandle {
if(isDirectory()) {
return 0;
}
RegularFileType rft = storage.getRegularFileType(path);
RegularFileType rft = fs.getRegularFileType(path);
switch(rft){
case TEXT: return readString().length();
case BINARY: return readBytes().length;
@ -159,11 +159,11 @@ public class FileHandleImpl implements FileHandle {
}
@Override
public FileHandle tempFile(String prefix) {
public File tempFile(String prefix) {
createTmpDirectoryIfDoesNotYetExist();
String r = createRandomName();
storage.touch(r);
return new FileHandleImpl(storage, "/tmp/"+r);
fs.touch(r);
return new FileImpl(fs, "/tmp/"+r);
}
private String createRandomName() {
@ -174,51 +174,51 @@ public class FileHandleImpl implements FileHandle {
}
private void createTmpDirectoryIfDoesNotYetExist() {
if(!storage.exists("/tmp")) {
storage.createDirectory("/tmp");
if(!fs.exists("/tmp")) {
fs.createDirectory("/tmp");
}
}
@Override
public FileHandle tempDirectory(String prefix) {
public File tempDirectory(String prefix) {
createTmpDirectoryIfDoesNotYetExist();
String r = createRandomName();
storage.createDirectory(r);
return new FileHandleImpl(storage, "/tmp/"+r);
fs.createDirectory(r);
return new FileImpl(fs, "/tmp/"+r);
}
@Override
public int depth() {
return storage.depth(path);
return fs.depth(path);
}
@Override
public boolean writeString(String text) {
return storage.writeString(path, text).isEmpty();
return fs.writeString(path, text).isEmpty();
}
@Override
public boolean appendString(String text
) {
String textCurrent = readString();
return storage.writeString(path, textCurrent + text).isEmpty();
return fs.writeString(path, textCurrent + text).isEmpty();
}
@Override
public String readString() {
return storage.readString(path);
return fs.readString(path);
}
@Override
public boolean writeBytes(byte[] data
) {
return storage.writeBytes(path, data).isEmpty();
return fs.writeBytes(path, data).isEmpty();
}
@Override
public byte[] readBytes() {
return storage.readBytes(path);
return fs.readBytes(path);
}
@Override
@ -227,7 +227,7 @@ public class FileHandleImpl implements FileHandle {
}
@Override
public Storage getStorage() {
public FileSystem getFileSystem() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}

View File

@ -23,18 +23,18 @@ import com.pixelgamelibrary.api.Platform;
import java.util.List;
/**
* This interface provides the methods to interact with the underlying storage
* This interface provides the methods to interact with the underlying file system
* system. It supports basic file system operations such as navigating
* directories, creating files and directories, and reading/writing data.
*
* @author robertvokac
*/
public interface Storage {
public interface FileSystem {
public String SLASH = "/";
/**
* Returns the platform associated with this storage.
* Returns the platform associated with this file system.
*
* @return the platform object.
*/
@ -55,11 +55,11 @@ public interface Storage {
* @return a result message or an empty string if successful.
*/
default String changeDirectory() {
Storage.this.changeDirectory("/");
FileSystem.this.changeDirectory("/");
createDirectory("home");
Storage.this.changeDirectory("home");
FileSystem.this.changeDirectory("home");
createDirectory(getUserName());
Storage.this.changeDirectory(getUserName());
FileSystem.this.changeDirectory(getUserName());
return "";
}
@ -242,19 +242,19 @@ public interface Storage {
/**
* Returns a debug string with information about the current state of the
* storage.
* file system.
*
* @return a debug string.
*/
public String debug();
/**
* Flushes any pending writes to the storage.
* Flushes any pending writes to the file system.
*/
public void flush();
/**
* Returns the username associated with this storage.
* Returns the username associated with this file system.
*
* @return the username.
*/
@ -263,7 +263,7 @@ public interface Storage {
}
/**
* If the size of this storage is limited, returns the number of bytes it is
* If the size of this file system is limited, returns the number of bytes it is
* limited to. Otherwise, returns 0.
*
* @return the size limit in bytes, or 0 if there is no limit.
@ -273,16 +273,16 @@ public interface Storage {
}
/**
* The default username for the storage.
* The default username for the file system.
*/
static final String USER = "user";
default FileHandle file(String path) {
default File file(String path) {
path = convertToAbsolutePathIfNeeded(path);
return new FileHandleImpl(this, path);
return new FileImpl(this, path);
}
default FileHandle file() {
default File file() {
return file(printWorkingDirectory());
}
@ -322,7 +322,7 @@ public interface Storage {
}
/**
* Saves and returns the current state of the storage.
* Saves and returns the current state of the file system.
*
* @param methodName
* @return
@ -330,7 +330,7 @@ public interface Storage {
byte[] backup(String methodName);
/**
* Replaces the current content of the storage.
* Replaces the current content of the file system.
* @param methodName
* @param data
*/
@ -339,12 +339,12 @@ public interface Storage {
boolean isReadonly();
/**
* Returns the maximum size in count of bytes of the storage. If the maximum
* size is not defined for this storage, then 0 is returned. default long
* Returns the maximum size in count of bytes of the file system. If the maximum
* size is not defined for this file system, then 0 is returned. default long
* getMaxSize() { return 0; }
*
* /**
* Deletes all the content in the storage.
* Deletes all the content in the file system.
*/
void clear();
@ -352,5 +352,5 @@ public interface Storage {
long size();
StorageType getStorageType();
FileSystemType getFileSystemType();
}

View File

@ -23,7 +23,7 @@ package com.pixelgamelibrary.api.files;
*
* @author robertvokac
*/
public enum StorageType {
public enum FileSystemType {
ASSETS,
LOCAL,
EXTERNAL,

View File

@ -23,48 +23,48 @@ import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.Platform;
import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.RegularFileType;
import com.pixelgamelibrary.api.files.StorageException;
import com.pixelgamelibrary.api.files.Storage;
import com.pixelgamelibrary.api.files.StorageType;
import com.pixelgamelibrary.api.files.FileException;
import com.pixelgamelibrary.api.files.FileSystemType;
import java.util.List;
import java.util.stream.Collectors;
import com.pixelgamelibrary.api.files.FileSystem;
/**
* Implementation of the Storage interface for managing a map-based file system.
* Implementation of the FileSystem interface for managing a map-based file system.
* Provides methods to interact with files and directories stored in a map.
*
* @author robertvokac
*/
public class MapStorage implements Storage {
public class MapFileSystem implements FileSystem {
private final SimpleMap map;
private final MapStorageCompression mapStorageCompression;
private final MapFileSystemCompression mapFileSystemCompression;
/**
* Constructs a MapStorage instance with the specified map and default
* Constructs a MapFileSystem instance with the specified map and default
* compression.
*
* @param mapIn the map to be used for storage
* @param mapIn the map to be used for file system
*/
public MapStorage(SimpleMap mapIn) {
this(mapIn, MapStorageCompression.LZMA);
public MapFileSystem(SimpleMap mapIn) {
this(mapIn, MapFileSystemCompression.LZMA);
}
/**
* Constructs a MapStorage instance with the specified map and compression.
* Constructs a MapFileSystem instance with the specified map and compression.
*
* @param mapIn the map to be used for storage
* @param mapStorageCompressionIn the compression method to be used
* @param mapIn the map to be used for file system
* @param mapFileSystemCompressionIn the compression method to be used
*/
public MapStorage(SimpleMap mapIn, MapStorageCompression mapStorageCompressionIn) {
public MapFileSystem(SimpleMap mapIn, MapFileSystemCompression mapFileSystemCompressionIn) {
this.map = mapIn;
this.mapStorageCompression = mapStorageCompressionIn;
this.mapFileSystemCompression = mapFileSystemCompressionIn;
if (map.contains("system.compression")) {
if (!map.getString("system.compression").equals(this.mapStorageCompression.name())) {
throw new StorageException("Fatal error, compression method passed to the constructor is different, than the compression method in the map (key system.compression).");
if (!map.getString("system.compression").equals(this.mapFileSystemCompression.name())) {
throw new FileException("Fatal error, compression method passed to the constructor is different, than the compression method in the map (key system.compression).");
}
} else {
map.putString("system.compression", mapStorageCompression.name());
map.putString("system.compression", mapFileSystemCompression.name());
}
createDirectory("/"); // Initialize the root directory
}
@ -141,14 +141,14 @@ public class MapStorage implements Storage {
*
* @param path the path to get the parent of
* @return the parent path
* @throws StorageException if the path is null or empty
* @throws FileException if the path is null or empty
*/
private static String getParentPath(String path) {
if (path == null) {
throw new StorageException("Path is null");
throw new FileException("Path is null");
}
if (path.trim().isEmpty()) {
throw new StorageException("Path is empty");
throw new FileException("Path is empty");
}
if (path.equals("/")) {
@ -247,10 +247,10 @@ public class MapStorage implements Storage {
*/
private String moveOrCp(String source, String target, boolean move, boolean cp) {
if (move && cp) {
throw new StorageException("move == true && cp == true");
throw new FileException("move == true && cp == true");
}
if (!move && !cp) {
throw new StorageException("move != true && cp != true");
throw new FileException("move != true && cp != true");
}
String absolutePathSource = convertToAbsolutePathIfNeeded(source);
String absolutePathTarget = convertToAbsolutePathIfNeeded(target);
@ -318,8 +318,8 @@ public class MapStorage implements Storage {
}
text = text.substring(BINARYFILE.length());
byte[] data = Pixel.utils().decodeBase64AsByteArray(text);
if (this.mapStorageCompression != MapStorageCompression.NONE) {
data = Pixel.utils().decompress(data, mapStorageCompression.name());
if (this.mapFileSystemCompression != MapFileSystemCompression.NONE) {
data = Pixel.utils().decompress(data, mapFileSystemCompression.name());
}
return data;
}
@ -331,8 +331,8 @@ public class MapStorage implements Storage {
@Override
public String writeBytes(String name, byte[] data) {
if (this.mapStorageCompression != MapStorageCompression.NONE) {
data = Pixel.utils().compress(data, mapStorageCompression.name());
if (this.mapFileSystemCompression != MapFileSystemCompression.NONE) {
data = Pixel.utils().compress(data, mapFileSystemCompression.name());
}
return writeString(name, BINARYFILE + Pixel.utils().encodeToBase64(data));
}
@ -440,7 +440,7 @@ public class MapStorage implements Storage {
}
@Override
public StorageType getStorageType() {
public FileSystemType getFileSystemType() {
throw new UnsupportedOperationException("Not supported yet."); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
}

View File

@ -23,6 +23,6 @@ package com.pixelgamelibrary.api.files.map;
*
* @author robertvokac
*/
public enum MapStorageCompression {
public enum MapFileSystemCompression {
NONE, LZMA;
}

View File

@ -21,7 +21,7 @@
package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.StorageException;
import com.pixelgamelibrary.api.files.FileException;
import static com.pixelgamelibrary.api.files.FileType.DIRECTORY;
import static com.pixelgamelibrary.api.files.FileType.FILE;
@ -36,22 +36,22 @@ public class MapFileType {
/**
* Determines the MapFileType based on the value associated with the specified key in the map.
* Throws a StorageException if the key is not found or if the value does not match any known type.
* Throws a FileException if the key is not found or if the value does not match any known type.
*
* @param key the key whose associated value determines the file type
* @param map the map from which to retrieve the value
* @return the MapFileType corresponding to the value in the map
* @throws StorageException if the key is not present in the map or if the value does not match FILE or DIRECTORY
* @throws FileException if the key is not present in the map or if the value does not match FILE or DIRECTORY
*/
public static FileType ofKey(String key, SimpleMap map) {
// Check if the map contains the specified key
if (!map.contains(key)) {
throw new StorageException("Map does not contain key: " + key);
throw new FileException("Map does not contain key: " + key);
}
// Retrieve the value associated with the key
String value = map.getString(key);
if(value == null) {
throw new StorageException("Value is null for key: " + key);
throw new FileException("Value is null for key: " + key);
}
// Determine the MapFileType based on the value
if (value.startsWith(FILE.name())) {
@ -61,6 +61,6 @@ public class MapFileType {
return DIRECTORY;
}
// Throw an exception if the value does not match known types
throw new StorageException("Unsupported MapFileType for key in the map: " + key);
throw new FileException("Unsupported MapFileType for key in the map: " + key);
}
}

View File

@ -23,21 +23,21 @@ package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.Platform;
/**
* Implementation of Storage that uses an in-memory map for storing data.
* Extends the MapStorage class to utilize a SimpleJavaMap for internal storage.
* Implementation of FileSystem that uses an in-memory map for storing data.
* Extends the MapFileSystem class to utilize a SimpleJavaMap for internal file system.
*
* This class is used when you need a temporary storage solution that
* This class is used when you need a temporary file system solution that
* does not persist data beyond the runtime of the application.
*
* @author robertvokac
*/
public class MemoryStorage extends MapStorage {
public class MemoryFileSystem extends MapFileSystem {
/**
* Constructs a MemoryStorage instance using a SimpleJavaMap.
* Initializes the parent MapStorage with an in-memory map implementation.
* Constructs a MemoryFileSystem instance using a SimpleJavaMap.
* Initializes the parent MapFileSystem with an in-memory map implementation.
*/
public MemoryStorage() {
public MemoryFileSystem() {
super(new SimpleJavaMap());
}

View File

@ -27,7 +27,7 @@ import java.util.Map;
import java.util.stream.Collectors;
/**
* An implementation of SimpleMap using a HashMap for internal storage.
* An implementation of SimpleMap using a HashMap for internal file system.
* This class provides basic operations for storing and retrieving key-value pairs.
* It implements the SimpleMap interface.
*
@ -48,7 +48,7 @@ public class SimpleJavaMap implements SimpleMap {
/**
* Constructs a SimpleJavaMap instance with a provided map.
*
* @param mapIn Initial map to use for storage
* @param mapIn Initial map to use for file system
*/
public SimpleJavaMap(Map<String, String> mapIn) {
this.map = mapIn;

View File

@ -17,23 +17,23 @@
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
import java.util.function.Function;
/**
* The {@code BaseStorageCommand} class provides a basic implementation of the {@link StorageCommand} interface.
* It defines a command that can be executed within a storage command-line context using a function
* The {@code BaseShellCommand} class provides a basic implementation of the {@link ShellCommand} interface.
* It defines a command that can be executed within a file system command-line context using a function
* that processes the command and its arguments.
*
* @author robertvokac
*/
public class BaseStorageCommand implements StorageCommand {
public class BaseShellCommand implements ShellCommand {
/**
* The command-line interface this command is associated with.
*/
private StorageCommandLine storageCommandLine = null;
private ShellCommandLine shellCommandLine = null;
/**
* The name of the command.
@ -43,41 +43,41 @@ public class BaseStorageCommand implements StorageCommand {
/**
* The function that will be applied to execute the command with its arguments.
*/
private final Function<String, StorageCommandResult> function;
private final Function<String, ShellCommandResult> function;
/**
* Constructs a new {@code BaseStorageCommand} with the specified command-line interface, name, and execution function.
* Constructs a new {@code BaseShellCommand} with the specified command-line interface, name, and execution function.
*
* @param storageCommandLineIn the command-line interface associated with this command.
* @param shellCommandLineIn the command-line interface associated with this command.
* @param nameIn the name of the command.
* @param functionIn the function that defines the command's behavior when executed.
*/
public BaseStorageCommand(
StorageCommandLine storageCommandLineIn, String nameIn, Function<String, StorageCommandResult> functionIn
public BaseShellCommand(
ShellCommandLine shellCommandLineIn, String nameIn, Function<String, ShellCommandResult> functionIn
) {
setStorageCommandLine(storageCommandLineIn);
setShellCommandLine(shellCommandLineIn);
this.name = nameIn;
this.function = functionIn;
}
/**
* Sets the {@link StorageCommandLine} for this command.
* Sets the {@link ShellCommandLine} for this command.
*
* @param storageCommandLineIn the command-line interface to set.
* @param shellCommandLineIn the command-line interface to set.
*/
@Override
public final void setStorageCommandLine(StorageCommandLine storageCommandLineIn) {
storageCommandLine = storageCommandLineIn;
public final void setShellCommandLine(ShellCommandLine shellCommandLineIn) {
shellCommandLine = shellCommandLineIn;
}
/**
* Returns the {@link StorageCommandLine} associated with this command.
* Returns the {@link ShellCommandLine} associated with this command.
*
* @return the command-line interface.
*/
@Override
public final StorageCommandLine getStorageCommandLine() {
return storageCommandLine;
public final ShellCommandLine getShellCommandLine() {
return shellCommandLine;
}
/**
@ -97,7 +97,7 @@ public class BaseStorageCommand implements StorageCommand {
* @return the result of executing the command.
*/
@Override
public StorageCommandResult execute(String commandWithArguments) {
public ShellCommandResult execute(String commandWithArguments) {
return function.apply(commandWithArguments);
}

View File

@ -17,16 +17,16 @@
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
/**
* The {@code StorageCommand} interface defines the contract for commands that can be executed within
* a storage command-line environment. It provides methods for getting the command's name, executing
* The {@code ShellCommand} interface defines the contract for commands that can be executed within
* a file system command-line environment. It provides methods for getting the command's name, executing
* the command with arguments, and managing the command-line context.
*
* @author robertvokac
*/
public interface StorageCommand {
public interface ShellCommand {
/**
* Returns the name of the command.
@ -39,30 +39,30 @@ public interface StorageCommand {
* Executes the command with the specified arguments and returns the result.
*
* @param arguments the arguments to be passed to the command.
* @return the result of executing the command as a {@link StorageCommandResult}.
* @return the result of executing the command as a {@link ShellCommandResult}.
*/
StorageCommandResult execute(String arguments);
ShellCommandResult execute(String arguments);
/**
* Returns the {@link StorageCommandLine} associated with this command.
* Returns the {@link ShellCommandLine} associated with this command.
*
* @return the command-line interface associated with this command.
*/
StorageCommandLine getStorageCommandLine();
ShellCommandLine getShellCommandLine();
/**
* Sets the {@link StorageCommandLine} for this command.
* Sets the {@link ShellCommandLine} for this command.
*
* @param storageCommandLine the command-line interface to set.
* @param shellCommandLine the command-line interface to set.
*/
void setStorageCommandLine(StorageCommandLine storageCommandLine);
void setShellCommandLine(ShellCommandLine shellCommandLine);
/**
* Creates and returns a new, empty {@link StorageCommandResult}.
* Creates and returns a new, empty {@link ShellCommandResult}.
*
* @return a new {@link StorageCommandResult} instance.
* @return a new {@link ShellCommandResult} instance.
*/
static StorageCommandResult emptyNewResult() {
return new StorageCommandResult();
static ShellCommandResult emptyNewResult() {
return new ShellCommandResult();
}
}

View File

@ -18,9 +18,8 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.Storage;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
@ -29,18 +28,19 @@ import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.pixelgamelibrary.api.files.FileSystem;
/**
* The StorageCommandLine class represents a command-line interface for interacting with storage.
* It provides methods to execute various commands that manipulate or retrieve information from the storage.
* The ShellCommandLine class represents a command-line interface for interacting with file system.
* It provides methods to execute various commands that manipulate or retrieve information from the file system.
*
* @author robertvokac
*/
public class StorageCommandLine {
public class ShellCommandLine {
private String user; // User for the command line
private String hostname; // Hostname for the command line
private Storage storage; // Storage object for interacting with files
private FileSystem fs; // File system object for interacting with files
private boolean exited = false; // Indicates if the command line session has been exited
long startNanoTime = System.nanoTime(); // Start time of the session in nanoseconds
@ -50,7 +50,7 @@ public class StorageCommandLine {
* @return the command line prompt string
*/
public String getCommandLineStart() {
return user + "@" + hostname + ":" + storage.printWorkingDirectory() + "$ ";
return user + "@" + hostname + ":" + fs.printWorkingDirectory() + "$ ";
}
/**
@ -72,17 +72,17 @@ public class StorageCommandLine {
}
/**
* Constructs a StorageCommandLine instance with the specified user, hostname, and storage.
* Constructs a ShellCommandLine instance with the specified user, hostname, and file system.
* Initializes commands for the command line interface.
*
* @param userIn the user for the command line
* @param hostnameIn the hostname for the command line
* @param storageIn the storage object for interacting with files
* @param fsIn the file system object for interacting with files
*/
public StorageCommandLine(String userIn, String hostnameIn, Storage storageIn) {
public ShellCommandLine(String userIn, String hostnameIn, FileSystem fsIn) {
this.user = userIn;
this.hostname = hostnameIn;
this.storage = storageIn;
this.fs = fsIn;
// Initialize commands
addCommand("date", arguments -> provideOutput(result -> result.setOutput(new Date().toString())));
@ -105,7 +105,7 @@ public class StorageCommandLine {
: "")
)));
addCommand("ls", arguments -> provideOutput(result -> result.setOutput(storage
addCommand("ls", arguments -> provideOutput(result -> result.setOutput(fsIn
.list()
.stream()
.map(l -> {
@ -114,12 +114,12 @@ public class StorageCommandLine {
})
.collect(Collectors.joining("\n")))));
addCommand("pwd", arguments -> provideOutput(result -> result.setOutput(storage.printWorkingDirectory())));
addCommand("depth", arguments -> provideOutput(result -> result.setOutput(storage.depth())));
addCommand("pwd", arguments -> provideOutput(result -> result.setOutput(fsIn.printWorkingDirectory())));
addCommand("depth", arguments -> provideOutput(result -> result.setOutput(fsIn.depth())));
addCommand("mkdir", arguments -> provideOutput(result
-> {
String string = storage.createDirectories(extractArguments(arguments));
String string = fsIn.createDirectories(extractArguments(arguments));
if (string.isEmpty()) {
result.setOutput("New directory was successfully created");
} else {
@ -127,8 +127,8 @@ public class StorageCommandLine {
}
}));
// Set the StorageCommandLine instance for each command
commands.keySet().stream().map(k -> commands.get(k)).forEach(c -> c.setStorageCommandLine(this));
// Set the ShellCommandLine instance for each command
commands.keySet().stream().map(k -> commands.get(k)).forEach(c -> c.setShellCommandLine(this));
}
/**
@ -149,8 +149,8 @@ public class StorageCommandLine {
* @param consumer the function to modify the result
* @return the modified result
*/
private StorageCommandResult provideOutput(Consumer<StorageCommandResult> consumer) {
StorageCommandResult result = StorageCommand.emptyNewResult();
private ShellCommandResult provideOutput(Consumer<ShellCommandResult> consumer) {
ShellCommandResult result = ShellCommand.emptyNewResult();
consumer.accept(result);
return result;
}
@ -161,12 +161,12 @@ public class StorageCommandLine {
* @param nameIn the name of the command
* @param functionIn the function to execute for the command
*/
private void addCommand(String nameIn, Function<String, StorageCommandResult> functionIn) {
StorageCommand storageCommand = new BaseStorageCommand(this, nameIn, functionIn);
commands.put(storageCommand.getName(), storageCommand);
private void addCommand(String nameIn, Function<String, ShellCommandResult> functionIn) {
ShellCommand shellCommand = new BaseShellCommand(this, nameIn, functionIn);
commands.put(shellCommand.getName(), shellCommand);
}
private final Map<String, StorageCommand> commands = new HashMap<>();
private final Map<String, ShellCommand> commands = new HashMap<>();
public String getUser() {
return user;
@ -176,8 +176,8 @@ public class StorageCommandLine {
return hostname;
}
public Storage getStorage() {
return storage;
public FileSystem getFileSystem() {
return fs;
}
public boolean isExited() {
@ -190,23 +190,23 @@ public class StorageCommandLine {
* @param commandWithArguments the command and its arguments
* @return the result of the command execution
*/
public StorageCommandResult execute(String commandWithArguments) {
public ShellCommandResult execute(String commandWithArguments) {
String[] arguments = commandWithArguments.split(" ");
String command = arguments.length == 0 ? "" : arguments[0];
StorageCommand storageCommand = commands.get(command);
if (storageCommand != null) {
return storageCommand.execute(commandWithArguments.substring(command.length()));
ShellCommand shellCommand = commands.get(command);
if (shellCommand != null) {
return shellCommand.execute(commandWithArguments.substring(command.length()));
}
int argumentCount = arguments.length - 1;
Optional<String> argument1 = Optional.ofNullable(argumentCount >= 1 ? arguments[1] : null);
Optional<String> argument2 = Optional.ofNullable(argumentCount >= 2 ? arguments[2] : null);
StorageCommandResult finalResult = new StorageCommandResult();
ShellCommandResult finalResult = new ShellCommandResult();
switch (command) {
case "touch":
String r = storage.touch(argument1.get());
String r = fs.touch(argument1.get());
if (r.isEmpty()) {
finalResult.setOutput("New file was successfully created");
} else {
@ -214,7 +214,7 @@ public class StorageCommandLine {
}
break;
case "readtext":
String rr = storage.readString(argument1.get());
String rr = fs.readString(argument1.get());
if (rr != null) {
finalResult.setOutput("Text file was successfully loaded" + "\n\n" + rr);
} else {
@ -222,7 +222,7 @@ public class StorageCommandLine {
}
break;
case "savetext":
String result = storage.writeString(argument1.get(), argument2.get());
String result = fs.writeString(argument1.get(), argument2.get());
if (result.isEmpty()) {
finalResult.setOutput("Text file was successfully saved");
} else {
@ -230,7 +230,7 @@ public class StorageCommandLine {
}
break;
case "cd":
String rrr = argument1.isEmpty() ? storage.changeDirectory() : storage.changeDirectory(argument1.get());
String rrr = argument1.isEmpty() ? fs.changeDirectory() : fs.changeDirectory(argument1.get());
if (rrr.isEmpty()) {
finalResult.setOutput("Changing working directory was successfully created");
} else {
@ -238,7 +238,7 @@ public class StorageCommandLine {
}
break;
case "debug":
finalResult.setOutput(storage.debug());
finalResult.setOutput(fs.debug());
break;
case "exit":
exited = true;

View File

@ -18,34 +18,34 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
/**
* The StorageCommandLineScanner class provides a command-line interface for interacting with
* the StorageCommandLine instance. It reads user input and executes commands in a loop until
* The ShellCommandLineScanner class provides a command-line interface for interacting with
* the ShellCommandLine instance. It reads user input and executes commands in a loop until
* the exit command is issued.
*
* @author robertvokac
*/
public class StorageCommandLineScanner {
public class ShellCommandLineScanner {
/**
* Constructs a StorageCommandLineScanner instance that continuously reads input from the
* Constructs a ShellCommandLineScanner instance that continuously reads input from the
* user and executes commands until the exit command is issued.
*
* @param storageCommandLine the StorageCommandLine instance to interact with
* @param shellCommandLine the ShellCommandLine instance to interact with
* @param scanner the Scanner object for reading user input
*/
public StorageCommandLineScanner(StorageCommandLine storageCommandLine, CommandLineScanner scanner) {
public ShellCommandLineScanner(ShellCommandLine shellCommandLine, ShellScanner scanner) {
while (true) {
// Print the command line prompt
System.out.print(storageCommandLine.getCommandLineStart());
System.out.print(shellCommandLine.getCommandLineStart());
// Read user input
String argument = scanner.nextLine();
// Execute the command and get the result
StorageCommandResult result = storageCommandLine.execute(argument);
ShellCommandResult result = shellCommandLine.execute(argument);
// Print error or output based on the result
if (result.isError()) {
printError(result.getOutput());
@ -53,7 +53,7 @@ public class StorageCommandLineScanner {
print(result.getOutput());
}
// Exit if the command line session is marked as exited
if (storageCommandLine.isExited()) {
if (shellCommandLine.isExited()) {
break;
}
}

View File

@ -18,20 +18,20 @@
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
/**
* The StorageCommandResult class encapsulates the result of executing a storage command.
* The ShellCommandResult class encapsulates the result of executing a file system command.
* It holds the output of the command and a flag indicating whether an error occurred.
*
* @author robertvokac
*/
public class StorageCommandResult {
public class ShellCommandResult {
/**
* Default constructor that initializes an empty result.
*/
public StorageCommandResult() {
public ShellCommandResult() {
this("");
}
@ -40,7 +40,7 @@ public class StorageCommandResult {
*
* @param output the output of the command
*/
public StorageCommandResult(String output) {
public ShellCommandResult(String output) {
this(output, false);
}
@ -50,7 +50,7 @@ public class StorageCommandResult {
* @param output the output of the command
* @param error true if an error occurred, false otherwise
*/
public StorageCommandResult(String output, boolean error) {
public ShellCommandResult(String output, boolean error) {
this.output = output;
this.error = error;
}

View File

@ -17,7 +17,7 @@
// <https://www.gnu.org/licenses/> or write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
/**
* The {@code CommandLineScanner} interface defines a contract for scanning input from a command line.
@ -25,7 +25,7 @@ package com.pixelgamelibrary.api.files.command;
*
* @author robertvokac
*/
public interface CommandLineScanner {
public interface ShellScanner {
/**
* Reads the next line of input from the command line.

View File

@ -19,7 +19,7 @@
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.File;
/**
*
@ -35,24 +35,24 @@ public interface BitmapFontFactory {
return create(FLIP_DEFAULT);
}
BitmapFont create(FileHandle fontFile, TextureRegion region, boolean flip);
BitmapFont create(File fontFile, TextureRegion region, boolean flip);
default BitmapFont create(FileHandle fontFile, TextureRegion region) {
default BitmapFont create(File fontFile, TextureRegion region) {
return create(fontFile, region, FLIP_DEFAULT);
}
BitmapFont create(FileHandle fontFile, boolean flip);
BitmapFont create(File fontFile, boolean flip);
default BitmapFont create(FileHandle fontFile) {
default BitmapFont create(File fontFile) {
return create(fontFile, FLIP_DEFAULT);
}
// Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.fnt"), Pixel.files().assets("com/badlogic/gdx/utils/lsans-15.png"),
// false, true
// );
BitmapFont create(FileHandle fontFile, FileHandle imageFile, boolean flip);
BitmapFont create(File fontFile, File imageFile, boolean flip);
default BitmapFont create(FileHandle fontFile, FileHandle imageFile) {
default BitmapFont create(File fontFile, File imageFile) {
return create(fontFile, imageFile, FLIP_DEFAULT);
}

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.File;
/**
*
@ -28,6 +28,6 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/
public interface PixMapFactory {
Pixmap create(int width, int height);
Pixmap create(FileHandle fileHandle);
Pixmap create(File fileHandle);
}

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.graphics;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.File;
/**
*
@ -28,7 +28,7 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/
public interface TextureFactory {
Texture create(String assetPath);
Texture create(FileHandle fileHandle);
Texture create(File fileHandle);
Texture create(Pixmap pixmap);
Texture create(int width, int height);
}

View File

@ -21,7 +21,7 @@ package com.pixelgamelibrary.api.interfaces;
import com.pixelgamelibrary.api.audio.Music;
import com.pixelgamelibrary.api.audio.Sound;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.File;
/**
*
@ -29,6 +29,6 @@ import com.pixelgamelibrary.api.files.FileHandle;
*/
public interface Audio {
//Add MIDI support - todo
Sound newSound(FileHandle fileHandle);
Music newMusic(FileHandle fileHandle);
Sound newSound(File fileHandle);
Music newMusic(File fileHandle);
}

View File

@ -19,12 +19,18 @@
///////////////////////////////////////////////////////////////////////////////////////////////
package com.pixelgamelibrary.api.interfaces;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.Storage;
import com.pixelgamelibrary.api.files.StorageException;
import com.pixelgamelibrary.api.files.StorageType;
import static com.pixelgamelibrary.api.files.StorageType.ASSETS;
import static com.pixelgamelibrary.api.files.StorageType.EXTERNAL;
import com.pixelgamelibrary.api.files.FileException;
import com.pixelgamelibrary.api.files.FileSystemType;
import static com.pixelgamelibrary.api.files.FileSystemType.ASSETS;
import static com.pixelgamelibrary.api.files.FileSystemType.EXTERNAL;
import com.pixelgamelibrary.api.files.FileSystem;
import com.pixelgamelibrary.api.files.File;
import static com.pixelgamelibrary.api.files.FileSystemType.ABSOLUTE;
import static com.pixelgamelibrary.api.files.FileSystemType.ASSETS;
import static com.pixelgamelibrary.api.files.FileSystemType.EXTERNAL;
import static com.pixelgamelibrary.api.files.FileSystemType.LOCAL;
import static com.pixelgamelibrary.api.files.FileSystemType.RELATIVE;
import static com.pixelgamelibrary.api.files.FileSystemType.TMP;
/**
*
@ -32,57 +38,76 @@ import static com.pixelgamelibrary.api.files.StorageType.EXTERNAL;
*/
public interface Files {
Storage assetsStorage();
FileSystem assetsFileSystem();
Storage localStorage();
FileSystem localFileSystem();
Storage externalStorage();
FileSystem externalFileSystem();
Storage relativeStorage();
FileSystem relativeFileSystem();
Storage absoluteStorage();
FileSystem absoluteFileSystem();
Storage tmpStorage();
FileSystem tmpFileSystem();
default FileHandle assets(String path) {
return assetsStorage().file(path);
default File assets(String path) {
return assetsFileSystem().file(path);
}
default FileHandle local(String path) {
return localStorage().file(path);
default File local(String path) {
return localFileSystem().file(path);
}
default FileHandle external(String path) {
return externalStorage().file(path);
default File external(String path) {
return externalFileSystem().file(path);
}
default FileHandle relative(String path) {
return relativeStorage().file(path);
default File relative(String path) {
return relativeFileSystem().file(path);
}
default FileHandle absolute(String path) {
return absoluteStorage().file(path);
default File absolute(String path) {
return absoluteFileSystem().file(path);
}
default FileHandle tmp(String path) {
return tmpStorage().file(path);
default File tmp(String path) {
return tmpFileSystem().file(path);
}
default FileHandle file(java.lang.String path, StorageType type) {
default FileSystem fileSystem(FileSystemType type) {
switch (type) {
case ASSETS:
return assetsStorage().file(path);
return assetsFileSystem();
case LOCAL:
return localStorage().file(path);
return localFileSystem();
case EXTERNAL:
return externalStorage().file(path);
return externalFileSystem();
case RELATIVE:
return relativeStorage().file(path);
return relativeFileSystem();
case ABSOLUTE:
return absoluteStorage().file(path);
return absoluteFileSystem();
case TMP:
return tmpStorage().file(path);
return tmpFileSystem();
default:
throw new StorageException("Unsupported StorageType: " + type);
throw new FileException("Unsupported FileSystemType: " + type);
}
}
default File file(java.lang.String path, FileSystemType type) {
//return fileSystem(type).file(path);
switch (type) {
case ASSETS:
return assetsFileSystem().file(path);
case LOCAL:
return localFileSystem().file(path);
case EXTERNAL:
return externalFileSystem().file(path);
case RELATIVE:
return relativeFileSystem().file(path);
case ABSOLUTE:
return absoluteFileSystem().file(path);
case TMP:
return tmpFileSystem().file(path);
default:
throw new FileException("Unsupported FileSystemType: " + type);
}
}
boolean isExternalStorageAvailable();

View File

@ -30,7 +30,7 @@ import com.pixelgamelibrary.api.graphics.SpriteBatchFactory;
import com.pixelgamelibrary.api.graphics.Texture;
import com.pixelgamelibrary.api.graphics.TextureFactory;
import com.pixelgamelibrary.api.graphics.TextureRegion;
import com.pixelgamelibrary.api.files.FileHandle;
import com.pixelgamelibrary.api.files.File;
/**
*
@ -69,7 +69,7 @@ public interface Graphics {
return getTextureFactory().create(assetPath);
}
default Texture newTexture(FileHandle fileHandle) {
default Texture newTexture(File fileHandle) {
return getTextureFactory().create(fileHandle);
}
@ -97,23 +97,23 @@ public interface Graphics {
return newBitmapFontFactory().create(flip);
}
default BitmapFont newBitmapFont(FileHandle fontFile, TextureRegion region) {
default BitmapFont newBitmapFont(File fontFile, TextureRegion region) {
return newBitmapFontFactory().create(fontFile, region);
}
default BitmapFont newBitmapFont(FileHandle fontFile, TextureRegion region, boolean flip) {
default BitmapFont newBitmapFont(File fontFile, TextureRegion region, boolean flip) {
return newBitmapFontFactory().create(fontFile, region, flip);
}
default BitmapFont newBitmapFont(FileHandle fontFile) {
default BitmapFont newBitmapFont(File fontFile) {
return newBitmapFontFactory().create(fontFile);
}
default BitmapFont newBitmapFont(FileHandle fontFile, boolean flip) {
default BitmapFont newBitmapFont(File fontFile, boolean flip) {
return newBitmapFontFactory().create(fontFile, flip);
}
default BitmapFont newBitmapFont(FileHandle fontFile, FileHandle imageFile, boolean flip) {
default BitmapFont newBitmapFont(File fontFile, File imageFile, boolean flip) {
return newBitmapFontFactory().create(fontFile, imageFile, flip);
}

View File

@ -20,7 +20,7 @@
package com.pixelgamelibrary.api.utils;
import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.files.StorageException;
import com.pixelgamelibrary.api.files.FileException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
@ -106,7 +106,7 @@ public class AssetsTxt {
public List<String> list(String pathToDirectory, boolean directoryType, boolean fileType) {
// System.out.println("Calling: AssetsTxt.list( " + pathToDirectory + " ...)");
if (!directoryType && !fileType) {
throw new StorageException("Invalid arguments, both arguments are false: directoryType, fileType");
throw new FileException("Invalid arguments, both arguments are false: directoryType, fileType");
}
if (pathToDirectory.equals(".")) {
@ -126,7 +126,7 @@ public class AssetsTxt {
return result;
}
if (!directoriesSet.contains(pathToDirectory)) {
throw new StorageException("There is no such directory in assets: " + pathToDirectory);
throw new FileException("There is no such directory in assets: " + pathToDirectory);
}
var directoryArray = pathToDirectory.split("/");

View File

@ -1,10 +1,8 @@
package com.pixelgamelibrary.api.files;
import com.pixelgamelibrary.api.files.Storage;
import com.pixelgamelibrary.api.files.FileHandleImpl;
import com.pixelgamelibrary.api.files.FileImpl;
import com.pixelgamelibrary.api.files.RegularFileType;
import com.pixelgamelibrary.api.files.FileType;
import com.pixelgamelibrary.api.files.FileHandle;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@ -13,22 +11,24 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.FileSystem;
import com.pixelgamelibrary.api.files.File;
public class FileHandleImplTest {
public class FileImplTest {
private Storage mockStorage;
private FileHandleImpl fileHandle;
private FileSystem mockFileSystem;
private FileImpl fileHandle;
@BeforeEach
public void setUp() {
mockStorage = mock(Storage.class);
fileHandle = new FileHandleImpl(mockStorage, "/example/path/file.txt");
mockFileSystem = mock(FileSystem.class);
fileHandle = new FileImpl(mockFileSystem, "/example/path/file.txt");
}
@Test
public void testType() {
// Arrange
when(mockStorage.type("/example/path/file.txt")).thenReturn(FileType.FILE);
when(mockFileSystem.type("/example/path/file.txt")).thenReturn(FileType.FILE);
// Act
FileType result = fileHandle.type();
@ -60,10 +60,10 @@ public class FileHandleImplTest {
@Test
public void testList() {
// Arrange
when(mockStorage.list("/example/path/file.txt")).thenReturn(Arrays.asList("child1", "child2"));
when(mockFileSystem.list("/example/path/file.txt")).thenReturn(Arrays.asList("child1", "child2"));
// Act
List<FileHandle> files = fileHandle.list();
List<File> files = fileHandle.list();
// Assert
assertEquals(2, files.size());
@ -74,7 +74,7 @@ public class FileHandleImplTest {
@Test
public void testChild() {
// Act
FileHandle child = fileHandle.child("child.txt");
File child = fileHandle.child("child.txt");
// Assert
assertEquals("/example/path/file.txt/child.txt", child.path());
@ -83,7 +83,7 @@ public class FileHandleImplTest {
@Test
public void testSibling() {
// Act
FileHandle sibling = fileHandle.sibling("sibling.txt");
File sibling = fileHandle.sibling("sibling.txt");
// Assert
assertEquals("/example/path/sibling.txt", sibling.path());
@ -92,7 +92,7 @@ public class FileHandleImplTest {
@Test
public void testParent() {
// Act
FileHandle parent = fileHandle.parent();
File parent = fileHandle.parent();
// Assert
assertEquals("/example/path", parent.path());
@ -101,7 +101,7 @@ public class FileHandleImplTest {
@Test
public void testMkdir() {
// Arrange
when(mockStorage.createDirectory("/example/path/file.txt")).thenReturn("");
when(mockFileSystem.createDirectory("/example/path/file.txt")).thenReturn("");
// Act
boolean result = fileHandle.mkdir();
@ -113,7 +113,7 @@ public class FileHandleImplTest {
@Test
public void testExists() {
// Arrange
when(mockStorage.exists("/example/path/file.txt")).thenReturn(true);
when(mockFileSystem.exists("/example/path/file.txt")).thenReturn(true);
// Act
boolean result = fileHandle.exists();
@ -125,7 +125,7 @@ public class FileHandleImplTest {
@Test
public void testDelete() {
// Arrange
when(mockStorage.remove("/example/path/file.txt")).thenReturn(true);
when(mockFileSystem.remove("/example/path/file.txt")).thenReturn(true);
// Act
boolean result = fileHandle.delete();
@ -137,8 +137,8 @@ public class FileHandleImplTest {
@Test
public void testCopyTo() {
// Arrange
FileHandleImpl destination = new FileHandleImpl(mockStorage, "/destination/path");
when(mockStorage.copy("/example/path/file.txt", "/destination/path")).thenReturn("");
FileImpl destination = new FileImpl(mockFileSystem, "/destination/path");
when(mockFileSystem.copy("/example/path/file.txt", "/destination/path")).thenReturn("");
// Act
boolean result = fileHandle.copyTo(destination);
@ -150,8 +150,8 @@ public class FileHandleImplTest {
@Test
public void testMoveTo() {
// Arrange
FileHandleImpl destination = new FileHandleImpl(mockStorage, "/destination/path");
when(mockStorage.move("/example/path/file.txt", "/destination/path")).thenReturn("");
FileImpl destination = new FileImpl(mockFileSystem, "/destination/path");
when(mockFileSystem.move("/example/path/file.txt", "/destination/path")).thenReturn("");
// Act
boolean result = fileHandle.moveTo(destination);
@ -163,8 +163,8 @@ public class FileHandleImplTest {
@Test
public void testLength() {
// Arrange
when(mockStorage.getRegularFileType("/example/path/file.txt")).thenReturn(RegularFileType.TEXT);
when(mockStorage.readString("/example/path/file.txt")).thenReturn("Hello, World!");
when(mockFileSystem.getRegularFileType("/example/path/file.txt")).thenReturn(RegularFileType.TEXT);
when(mockFileSystem.readString("/example/path/file.txt")).thenReturn("Hello, World!");
// Act
long length = fileHandle.length();

View File

@ -1,58 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.BaseStorageCommand;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BaseStorageCommandTest {
private StorageCommandLine mockCommandLine;
private StorageCommandResult mockCommandResult;
private Function<String, StorageCommandResult> mockFunction;
private BaseStorageCommand command;
@BeforeEach
void setUp() {
mockCommandLine = mock(StorageCommandLine.class);
mockCommandResult = mock(StorageCommandResult.class);
mockFunction = mock(Function.class);
// When the function is applied, return the mock result
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseStorageCommand with mocks
command = new BaseStorageCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", command.getName());
}
@Test
void testGetStorageCommandLine() {
assertEquals(mockCommandLine, command.getStorageCommandLine());
}
@Test
void testExecute() {
StorageCommandResult result = command.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testSetStorageCommandLine() {
StorageCommandLine newCommandLine = mock(StorageCommandLine.class);
command.setStorageCommandLine(newCommandLine);
assertEquals(newCommandLine, command.getStorageCommandLine());
}
}

View File

@ -1,64 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLineScanner;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.CommandLineScanner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
class StorageCommandLineScannerTest {
@Mock
private StorageCommandLine mockStorageCommandLine; // Mocking StorageCommandLine
@Mock
private CommandLineScanner mockCommandLineScanner; // Mocking CommandLineScanner
private StorageCommandLineScanner storageCommandLineScanner; // Manually creating the instance
@BeforeEach
void setUp() {
// Initialize mock objects before each test
MockitoAnnotations.openMocks(this);
}
@Test
void testExecuteSimpleCommand() {
// Arrange
when(mockStorageCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("someCommand");
StorageCommandResult mockResult = new StorageCommandResult("Command Executed");
when(mockStorageCommandLine.execute("someCommand")).thenReturn(mockResult);
when(mockStorageCommandLine.isExited()).thenReturn(true);
// Manually create the instance of StorageCommandLineScanner with mocks
storageCommandLineScanner = new StorageCommandLineScanner(mockStorageCommandLine, mockCommandLineScanner);
// Assert: Verify that the expected methods were called
verify(mockStorageCommandLine).getCommandLineStart();
verify(mockStorageCommandLine).execute("someCommand");
}
@Test
void testErrorOutput() {
// Arrange
when(mockStorageCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("invalidCommand");
StorageCommandResult errorResult = new StorageCommandResult("Error occurred", true);
when(mockStorageCommandLine.execute("invalidCommand")).thenReturn(errorResult);
when(mockStorageCommandLine.isExited()).thenReturn(true);
// Manually create the instance of StorageCommandLineScanner with mocks
storageCommandLineScanner = new StorageCommandLineScanner(mockStorageCommandLine, mockCommandLineScanner);
// Assert: Verify the error output
verify(mockStorageCommandLine).execute("invalidCommand");
assertTrue(errorResult.isError(), "The result should indicate an error");
}
}

View File

@ -1,65 +0,0 @@
package com.pixelgamelibrary.api.files.command;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.command.BaseStorageCommand;
import com.pixelgamelibrary.api.files.command.StorageCommand;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class StorageCommandTest {
private StorageCommand mockCommand;
private StorageCommandLine mockCommandLine;
private StorageCommandResult mockCommandResult;
private Function<String, StorageCommandResult> mockFunction;
@BeforeEach
void setUp() {
mockCommandLine = mock(StorageCommandLine.class);
mockCommandResult = mock(StorageCommandResult.class);
mockFunction = mock(Function.class);
// Mock the behavior of execute method
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseStorageCommand with mocks
mockCommand = new BaseStorageCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", mockCommand.getName());
}
@Test
void testGetStorageCommandLine() {
assertEquals(mockCommandLine, mockCommand.getStorageCommandLine());
}
@Test
void testSetStorageCommandLine() {
StorageCommandLine newCommandLine = mock(StorageCommandLine.class);
mockCommand.setStorageCommandLine(newCommandLine);
assertEquals(newCommandLine, mockCommand.getStorageCommandLine());
}
@Test
void testExecute() {
StorageCommandResult result = mockCommand.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testEmptyNewResult() {
StorageCommandResult result = StorageCommand.emptyNewResult();
assertNotNull(result);
assertTrue(result instanceof StorageCommandResult);
}
}

View File

@ -1,6 +1,6 @@
package com.pixelgamelibrary.api.files.map;
import com.pixelgamelibrary.api.files.map.MapStorage;
import com.pixelgamelibrary.api.files.map.MapFileSystem;
import com.pixelgamelibrary.api.files.map.SimpleMap;
import com.pixelgamelibrary.api.Pixel;
import com.pixelgamelibrary.api.Platform;
@ -27,11 +27,11 @@ import com.pixelgamelibrary.api.app.ClipBoard;
import com.pixelgamelibrary.api.app.LogLevel;
import com.pixelgamelibrary.api.app.Preferences;
// Tests for MapStorage class
public class MapStorageTest {
// Tests for MapFileSystem class
public class MapFileSystemTest {
private SimpleMap mockMap;
private MapStorage mapStorage;
private MapFileSystem fs;
@org.junit.jupiter.api.BeforeAll public static void setupStart() {
@ -201,7 +201,7 @@ public class MapStorageTest {
@BeforeEach
public void setup() {
mockMap = Mockito.mock(SimpleMap.class); // Mocking the SimpleMap class
mapStorage = new MapStorage(mockMap); // Initialize MapStorage with the mocked map
fs = new MapFileSystem(mockMap); // Initialize MapFileSystem with the mocked map
}
@Test
@ -209,7 +209,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Simulate no directory exists
when(mockMap.contains("/newDir")).thenReturn(false); // Simulate no directory exists
String result = mapStorage.createDirectory("/newDir");
String result = fs.createDirectory("/newDir");
assertEquals("", result); // Success should return an empty string
verify(mockMap).putString("/newDir", "DIRECTORY::::::::");
@ -220,7 +220,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Root irectory already exists
when(mockMap.contains("/newDir")).thenReturn(true); // Directory already exists
String result = mapStorage.createDirectory("/newDir");
String result = fs.createDirectory("/newDir");
assertEquals("Cannot create new directory, because path already exists: /newDir", result);
}
@ -232,7 +232,7 @@ public class MapStorageTest {
when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::");
when(mockMap.getString("/newDir")).thenReturn("DIRECTORY::::::::");
String result = mapStorage.changeDirectory("/newDir");
String result = fs.changeDirectory("/newDir");
assertEquals("", result); // Success should return an empty string
}
@ -241,7 +241,7 @@ public class MapStorageTest {
public void testCdPathDoesNotExist() {
when(mockMap.contains("/nonExistent")).thenReturn(false);
String result = mapStorage.changeDirectory("/nonExistent");
String result = fs.changeDirectory("/nonExistent");
assertEquals("Path does not exist: /nonExistent", result);
}
@ -251,7 +251,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // Root exists
when(mockMap.getString("/")).thenReturn("DIRECTORY::::::::");
String result = mapStorage.touch("/newFile.txt", "Test content");
String result = fs.touch("/newFile.txt", "Test content");
assertEquals("", result); // Success should return an empty string
verify(mockMap).putString("/newFile.txt", "FILE::::::::Test content");
@ -262,7 +262,7 @@ public class MapStorageTest {
when(mockMap.contains("/")).thenReturn(true); // File already exists
when(mockMap.contains("/newFile.txt")).thenReturn(true); // File already exists
String result = mapStorage.touch("/newFile.txt", "Test content");
String result = fs.touch("/newFile.txt", "Test content");
assertEquals("Cannot create new file, because path already exists: /newFile.txt", result);
}
@ -272,7 +272,7 @@ public class MapStorageTest {
when(mockMap.contains("/file.txt")).thenReturn(true);
when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World");
String content = mapStorage.readString("/file.txt");
String content = fs.readString("/file.txt");
assertEquals("Hello World", content);
}
@ -281,7 +281,7 @@ public class MapStorageTest {
public void testReadTextFileDoesNotExist() {
when(mockMap.contains("/file.txt")).thenReturn(false);
String content = mapStorage.readString("/file.txt");
String content = fs.readString("/file.txt");
assertNull(content);
}
@ -291,7 +291,7 @@ public class MapStorageTest {
when(mockMap.contains("/file.txt")).thenReturn(true);
when(mockMap.getString("/file.txt")).thenReturn("FILE::::::::Hello World");
boolean result = mapStorage.remove("/file.txt");
boolean result = fs.remove("/file.txt");
assertTrue(result); // File successfully removed
verify(mockMap).remove("/file.txt");
@ -301,23 +301,23 @@ public class MapStorageTest {
public void testRmFileDoesNotExist() {
when(mockMap.contains("/file.txt")).thenReturn(false);
boolean result = mapStorage.remove("/file.txt");
boolean result = fs.remove("/file.txt");
assertFalse(result); // File does not exist, so removal fails
}
@Test
public void testDepth() {
assertEquals(0, mapStorage.depth("/"));
assertEquals(1, mapStorage.depth("/dir"));
assertEquals(2, mapStorage.depth("/dir/subdir"));
assertEquals(0, fs.depth("/"));
assertEquals(1, fs.depth("/dir"));
assertEquals(2, fs.depth("/dir/subdir"));
}
@Test
public void testLs() {
when(mockMap.keyList()).thenReturn(List.of("/dir/file1", "/dir/file2", "/dir/subdir/file3"));
List<String> files = mapStorage.list("/dir");
List<String> files = fs.list("/dir");
assertEquals(2, files.size());
assertTrue(files.contains("/dir/file1"));

View File

@ -0,0 +1,58 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import com.pixelgamelibrary.api.files.shell.BaseShellCommand;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class BaseShellCommandTest {
private ShellCommandLine mockCommandLine;
private ShellCommandResult mockCommandResult;
private Function<String, ShellCommandResult> mockFunction;
private BaseShellCommand command;
@BeforeEach
void setUp() {
mockCommandLine = mock(ShellCommandLine.class);
mockCommandResult = mock(ShellCommandResult.class);
mockFunction = mock(Function.class);
// When the function is applied, return the mock result
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseShellCommand with mocks
command = new BaseShellCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", command.getName());
}
@Test
void testGetShellCommandLine() {
assertEquals(mockCommandLine, command.getShellCommandLine());
}
@Test
void testExecute() {
ShellCommandResult result = command.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testSetShellCommandLine() {
ShellCommandLine newCommandLine = mock(ShellCommandLine.class);
command.setShellCommandLine(newCommandLine);
assertEquals(newCommandLine, command.getShellCommandLine());
}
}

View File

@ -0,0 +1,64 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLineScanner;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import com.pixelgamelibrary.api.files.shell.ShellScanner;
class ShellCommandLineScannerTest {
@Mock
private ShellCommandLine mockShellCommandLine; // Mocking ShellCommandLine
@Mock
private ShellScanner mockCommandLineScanner; // Mocking CommandLineScanner
private ShellCommandLineScanner shellCommandLineScanner; // Manually creating the instance
@BeforeEach
void setUp() {
// Initialize mock objects before each test
MockitoAnnotations.openMocks(this);
}
@Test
void testExecuteSimpleCommand() {
// Arrange
when(mockShellCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("someCommand");
ShellCommandResult mockResult = new ShellCommandResult("Command Executed");
when(mockShellCommandLine.execute("someCommand")).thenReturn(mockResult);
when(mockShellCommandLine.isExited()).thenReturn(true);
// Manually create the instance of ShellCommandLineScanner with mocks
shellCommandLineScanner = new ShellCommandLineScanner(mockShellCommandLine, mockCommandLineScanner);
// Assert: Verify that the expected methods were called
verify(mockShellCommandLine).getCommandLineStart();
verify(mockShellCommandLine).execute("someCommand");
}
@Test
void testErrorOutput() {
// Arrange
when(mockShellCommandLine.getCommandLineStart()).thenReturn(">");
when(mockCommandLineScanner.nextLine()).thenReturn("invalidCommand");
ShellCommandResult errorResult = new ShellCommandResult("Error occurred", true);
when(mockShellCommandLine.execute("invalidCommand")).thenReturn(errorResult);
when(mockShellCommandLine.isExited()).thenReturn(true);
// Manually create the instance of ShellCommandLineScanner with mocks
shellCommandLineScanner = new ShellCommandLineScanner(mockShellCommandLine, mockCommandLineScanner);
// Assert: Verify the error output
verify(mockShellCommandLine).execute("invalidCommand");
assertTrue(errorResult.isError(), "The result should indicate an error");
}
}

View File

@ -1,8 +1,7 @@
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.command.StorageCommandLine;
import com.pixelgamelibrary.api.files.Storage;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import java.util.Arrays;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -12,18 +11,19 @@ import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.FileSystem;
class StorageCommandLineTest {
class ShellCommandLineTest {
private StorageCommandLine commandLine;
private Storage mockStorage;
private ShellCommandLine commandLine;
private FileSystem mockFileSystem;
@BeforeEach
void setUp() {
mockStorage = mock(Storage.class);
when(mockStorage.printWorkingDirectory()).thenReturn("/mock/path");
when(mockStorage.list()).thenReturn(Arrays.asList("file1.txt", "file2.txt"));
commandLine = new StorageCommandLine("user", "hostname", mockStorage);
mockFileSystem = mock(FileSystem.class);
when(mockFileSystem.printWorkingDirectory()).thenReturn("/mock/path");
when(mockFileSystem.list()).thenReturn(Arrays.asList("file1.txt", "file2.txt"));
commandLine = new ShellCommandLine("user", "hostname", mockFileSystem);
}
@Test
@ -39,13 +39,13 @@ class StorageCommandLineTest {
@Test
void testExecuteDateCommand() {
StorageCommandResult result = commandLine.execute("date");
ShellCommandResult result = commandLine.execute("date");
assertEquals(new Date().toString(), result.getOutput().trim());
}
@Test
void testExecuteWhoamiCommand() {
StorageCommandResult result = commandLine.execute("whoami");
ShellCommandResult result = commandLine.execute("whoami");
assertEquals("user", result.getOutput().trim());
}
@ -55,100 +55,100 @@ class StorageCommandLineTest {
String expectedOutput = new Date().toString().substring(11, 19) + " up "
+ (System.nanoTime() - commandLine.startNanoTime) / 1000000000L / 60L
+ " minutes, 1 user";
StorageCommandResult result = commandLine.execute("uptime");
ShellCommandResult result = commandLine.execute("uptime");
assertEquals(expectedOutput, result.getOutput().trim());
}
@Test
void testExecuteHostnameCommand() {
StorageCommandResult result = commandLine.execute("hostname");
ShellCommandResult result = commandLine.execute("hostname");
assertEquals("hostname", result.getOutput().trim());
}
@Test
void testExecuteTestCommand() {
StorageCommandResult result = commandLine.execute("test arg1");
ShellCommandResult result = commandLine.execute("test arg1");
assertEquals("arg1", result.getOutput().trim());
}
@Test
void testExecuteUnameCommand() {
StorageCommandResult result = commandLine.execute("uname -a");
ShellCommandResult result = commandLine.execute("uname -a");
assertEquals("LinuxBashCommandLinePartialEmulation hostname 0.0.0 ("
+ new Date().toString() + ")", result.getOutput().trim());
}
@Test
void testExecuteLsCommand() {
StorageCommandResult result = commandLine.execute("ls");
ShellCommandResult result = commandLine.execute("ls");
assertEquals("file1.txt\nfile2.txt", result.getOutput().trim());
}
@Test
void testExecutePwdCommand() {
StorageCommandResult result = commandLine.execute("pwd");
ShellCommandResult result = commandLine.execute("pwd");
assertEquals("/mock/path", result.getOutput().trim());
}
@Test
void testExecuteDepthCommand() {
when(mockStorage.depth()).thenReturn(4);
StorageCommandResult result = commandLine.execute("depth");
when(mockFileSystem.depth()).thenReturn(4);
ShellCommandResult result = commandLine.execute("depth");
assertEquals(4, Integer.valueOf(result.getOutput().trim()));
}
@Test
void testExecuteMkdirCommand() {
when(mockStorage.createDirectories(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("mkdir newDir");
when(mockFileSystem.createDirectories(any())).thenReturn("");
ShellCommandResult result = commandLine.execute("mkdir newDir");
assertEquals("New directory was successfully created", result.getOutput().trim());
}
@Test
void testExecuteCdCommand() {
when(mockStorage.changeDirectory(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("cd newDir");
when(mockFileSystem.changeDirectory(any())).thenReturn("");
ShellCommandResult result = commandLine.execute("cd newDir");
assertEquals("Changing working directory was successfully created", result.getOutput().trim());
}
@Test
void testExecuteTouchCommand() {
when(mockStorage.touch(any())).thenReturn("");
StorageCommandResult result = commandLine.execute("touch newFile.txt");
when(mockFileSystem.touch(any())).thenReturn("");
ShellCommandResult result = commandLine.execute("touch newFile.txt");
assertEquals("New file was successfully created", result.getOutput().trim());
}
@Test
void testExecuteReadtextCommand() {
when(mockStorage.readString(any())).thenReturn("file content");
StorageCommandResult result = commandLine.execute("readtext file.txt");
when(mockFileSystem.readString(any())).thenReturn("file content");
ShellCommandResult result = commandLine.execute("readtext file.txt");
assertEquals("Text file was successfully loaded\n\nfile content", result.getOutput().trim());
}
@Test
void testExecuteSavetextCommand() {
when(mockStorage.writeString(any(), any())).thenReturn("");
StorageCommandResult result = commandLine.execute("savetext file.txt content");
when(mockFileSystem.writeString(any(), any())).thenReturn("");
ShellCommandResult result = commandLine.execute("savetext file.txt content");
assertEquals("Text file was successfully saved", result.getOutput().trim());
}
@Test
void testExecuteDebugCommand() {
when(mockStorage.debug()).thenReturn("debug info");
StorageCommandResult result = commandLine.execute("debug");
when(mockFileSystem.debug()).thenReturn("debug info");
ShellCommandResult result = commandLine.execute("debug");
assertEquals("debug info", result.getOutput().trim());
}
@Test
void testExecuteExitCommand() {
StorageCommandResult result = commandLine.execute("exit");
ShellCommandResult result = commandLine.execute("exit");
assertTrue(commandLine.isExited());
assertEquals("Exited", result.getOutput().trim());
}
@Test
void testExecuteUnsupportedCommand() {
StorageCommandResult result = commandLine.execute("unsupported");
ShellCommandResult result = commandLine.execute("unsupported");
assertEquals("Unsupported command: unsupported", result.getOutput().trim());
}
}

View File

@ -1,15 +1,15 @@
package com.pixelgamelibrary.api.files.command;
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.command.StorageCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StorageCommandResultTest {
class ShellCommandResultTest {
@Test
void testDefaultConstructor() {
// Test default constructor which initializes an empty result
StorageCommandResult result = new StorageCommandResult();
ShellCommandResult result = new ShellCommandResult();
assertNotNull(result.getOutput(), "Output should not be null");
assertEquals("", result.getOutput(), "Default output should be empty");
@ -20,7 +20,7 @@ class StorageCommandResultTest {
void testConstructorWithOutput() {
// Test constructor that initializes with an output string
String expectedOutput = "Test Output";
StorageCommandResult result = new StorageCommandResult(expectedOutput);
ShellCommandResult result = new ShellCommandResult(expectedOutput);
assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string");
assertFalse(result.isError(), "Result should not indicate an error by default");
@ -30,7 +30,7 @@ class StorageCommandResultTest {
void testConstructorWithOutputAndErrorFlag() {
// Test constructor that initializes with output and error flag
String expectedOutput = "Error Output";
StorageCommandResult result = new StorageCommandResult(expectedOutput, true);
ShellCommandResult result = new ShellCommandResult(expectedOutput, true);
assertEquals(expectedOutput, result.getOutput(), "Output should match the provided string");
assertTrue(result.isError(), "Error flag should be set to true");
@ -39,7 +39,7 @@ class StorageCommandResultTest {
@Test
void testSetOutputString() {
// Test setting the output using a string
StorageCommandResult result = new StorageCommandResult();
ShellCommandResult result = new ShellCommandResult();
String expectedOutput = "New Output";
result.setOutput(expectedOutput);
@ -49,7 +49,7 @@ class StorageCommandResultTest {
@Test
void testSetOutputInt() {
// Test setting the output using an integer
StorageCommandResult result = new StorageCommandResult();
ShellCommandResult result = new ShellCommandResult();
int expectedOutput = 12345;
result.setOutput(expectedOutput);
@ -59,7 +59,7 @@ class StorageCommandResultTest {
@Test
void testSetErrorOutput() {
// Test setting an error output and marking the result as an error
StorageCommandResult result = new StorageCommandResult();
ShellCommandResult result = new ShellCommandResult();
String errorOutput = "Error occurred";
result.setErrorOutput(errorOutput);
@ -70,7 +70,7 @@ class StorageCommandResultTest {
@Test
void testSetErrorFlag() {
// Test setting the error flag directly
StorageCommandResult result = new StorageCommandResult();
ShellCommandResult result = new ShellCommandResult();
result.setError(true);
assertTrue(result.isError(), "Error flag should be set to true");

View File

@ -0,0 +1,65 @@
package com.pixelgamelibrary.api.files.shell;
import com.pixelgamelibrary.api.files.shell.ShellCommandResult;
import com.pixelgamelibrary.api.files.shell.ShellCommandLine;
import com.pixelgamelibrary.api.files.shell.BaseShellCommand;
import java.util.function.Function;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import com.pixelgamelibrary.api.files.shell.ShellCommand;
class ShellCommandTest {
private ShellCommand mockCommand;
private ShellCommandLine mockCommandLine;
private ShellCommandResult mockCommandResult;
private Function<String, ShellCommandResult> mockFunction;
@BeforeEach
void setUp() {
mockCommandLine = mock(ShellCommandLine.class);
mockCommandResult = mock(ShellCommandResult.class);
mockFunction = mock(Function.class);
// Mock the behavior of execute method
when(mockFunction.apply(anyString())).thenReturn(mockCommandResult);
// Create an instance of BaseShellCommand with mocks
mockCommand = new BaseShellCommand(mockCommandLine, "testCommand", mockFunction);
}
@Test
void testGetName() {
assertEquals("testCommand", mockCommand.getName());
}
@Test
void testGetShellCommandLine() {
assertEquals(mockCommandLine, mockCommand.getShellCommandLine());
}
@Test
void testSetShellCommandLine() {
ShellCommandLine newCommandLine = mock(ShellCommandLine.class);
mockCommand.setShellCommandLine(newCommandLine);
assertEquals(newCommandLine, mockCommand.getShellCommandLine());
}
@Test
void testExecute() {
ShellCommandResult result = mockCommand.execute("testCommand arg1");
assertEquals(mockCommandResult, result);
verify(mockFunction).apply("testCommand arg1");
}
@Test
void testEmptyNewResult() {
ShellCommandResult result = ShellCommand.emptyNewResult();
assertNotNull(result);
assertTrue(result instanceof ShellCommandResult);
}
}