Skip to content

Commit

Permalink
Merge pull request #135 from FourteenBrush/main
Browse files Browse the repository at this point in the history
Cleanup
  • Loading branch information
mfnalex authored Feb 16, 2024
2 parents b697eb7 + 860737e commit fac8d28
Show file tree
Hide file tree
Showing 19 changed files with 123 additions and 170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class BasicsCommandManager(private val serverCommandMap: SimpleCommandMap) {
(simpleCommandMap_knownCommands?.get(serverCommandMap) as? MutableMap<String, Command>)?.let { knownCommands ->
knownCommands.entries.removeIf { it.value == command }
}
} catch (e: Exception) {
} catch (_: Exception) {
}
command.disableExecutor()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,109 +27,104 @@ class BasicsCommand internal constructor(
coreConfig: CoreConfig,
val coreMessages: CoreMessages,
val messageFactory: MessageFactory,
) :
Command(info.name) {
private val logger = BasicsLoggerFactory.getCoreLogger(BasicsCommand::class)
) : Command(info.name) {
private val logger = BasicsLoggerFactory.getCoreLogger(BasicsCommand::class)

init {
val permString = info.permission.name
permission = if (coreConfig.hideCommandsWhenNoPermission) permString else null
description = info.description ?: ""
usage = info.usage
permissionMessage = info.permissionMessage.tagParsed("permission", permString).toLegacyString()
init {
val permString = info.permission.name
permission = if (coreConfig.hideCommandsWhenNoPermission) permString else null
description = info.description ?: ""
usage = info.usage
permissionMessage = info.permissionMessage.tagParsed("permission", permString).toLegacyString()
}

override fun execute(
sender: CommandSender,
commandLabel: String,
origArgs: Array<out String>,
): Boolean {
if (!sender.hasPermission(info.permission)) {
coreMessages.noPermission
.apply { if (sender is Player) concerns(sender) }
.tagParsed("permission", info.permission.name)
.sendToSender(sender)
return true
}

override fun execute(
sender: CommandSender,
commandLabel: String,
origArgs: Array<out String>,
): Boolean {
if (!sender.hasPermission(info.permission)) {
coreMessages.noPermission
.apply { if (sender is Player) concerns(sender) }
.tagParsed("permission", info.permission.name)
.sendToSender(sender)
return true
}
val args = origArgs.toMutableList()

val args = origArgs.toMutableList()
val context =
RawCommandContext(
sender = sender,
command = this,
label = commandLabel,
args = args,
location = if (sender is Entity) sender.location else null,
)

val context =
RawCommandContext(
sender = sender,
command = this,
label = commandLabel,
args = args,
location = if (sender is Entity) sender.location else null,
)
if (executor == null) {
coreMessages.commandModuleDisabled.sendToSender(sender)
return true
}

if (executor == null) {
coreMessages.commandModuleDisabled.sendToSender(sender)
return true
}
val returned: CommandResult?
try {
returned = executor!!.execute(context)

val returned: CommandResult?
try {
returned = executor!!.execute(context)

try {
returned?.process(context)
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error processing returned command result for ${info.name}", e)
}

return true
} catch (e: BasicsCommandException) {
try {
e.commandResult.process(context)
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error processing thrown command result for ${info.name}", e)
}
return true
} catch (e: UnsupportedServerSoftwareException) {
// Also want to catch NoSuchMethod and NoSuchField exception here
coreMessages.unsupportedServerSoftware(e.feature).sendToSender(sender)
return true
} catch (e: Throwable) {
coreMessages.errorExecutingCommand(sender, e).sendToSender(sender)
logger.log(Level.SEVERE, "Error executing command ${info.name}", e)
return true
returned?.process(context)
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error processing returned command result for ${info.name}", e)
}
} catch (e: BasicsCommandException) {
try {
e.commandResult.process(context)
} catch (e: Exception) {
logger.log(Level.SEVERE, "Error processing thrown command result for ${info.name}", e)
}
} catch (e: UnsupportedServerSoftwareException) {
// Also want to catch NoSuchMethod and NoSuchField exception here
coreMessages.unsupportedServerSoftware(e.feature).sendToSender(sender)
} catch (e: Throwable) {
coreMessages.errorExecutingCommand(sender, e).sendToSender(sender)
logger.log(Level.SEVERE, "Error executing command ${info.name}", e)
}
return true
}

internal fun replaceCommand(command: BasicsCommand) {
this.executor = command.executor
this.info = command.info
}
internal fun replaceCommand(command: BasicsCommand) {
this.executor = command.executor
this.info = command.info
}

override fun tabComplete(
sender: CommandSender,
alias: String,
args: Array<out String>,
location: Location?,
): List<String> {
if (!sender.hasPermission(info.permission)) return mutableListOf()
override fun tabComplete(
sender: CommandSender,
alias: String,
args: Array<out String>,
location: Location?,
): List<String> {
if (!sender.hasPermission(info.permission)) return mutableListOf()

val context =
RawCommandContext(
sender = sender,
command = this,
label = alias,
args = args.toMutableList(),
location = location,
)
if (tabCompleter == null) return mutableListOf()
val result = tabCompleter!!.tabComplete(context)
return result ?: super.tabComplete(sender, alias, args, location)
}
val context =
RawCommandContext(
sender = sender,
command = this,
label = alias,
args = args.toMutableList(),
location = location,
)
if (tabCompleter == null) return mutableListOf()
val result = tabCompleter!!.tabComplete(context)
return result ?: super.tabComplete(sender, alias, args, location)
}

/**
* Disable this command's executor by setting it to null. Disabled commands will always return true and
* print a message to the sender.
*
*/
fun disableExecutor() {
executor = null
tabCompleter = null
}
/**
* Disable this command's executor by setting it to null. Disabled commands will always return true and
* print a message to the sender.
*
*/
fun disableExecutor() {
executor = null
tabCompleter = null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ class ParsedCommandBuilderFactory(
name = name,
permission = permission,
)
builder.block() // Apply the DSL configurations
return builder // return .build() ?
// Apply the DSL configurations
// return .build() ?
return builder.apply(block)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ class RawCommandBuilder(
}

fun register(): BasicsCommand {
val command = build()
commandManager.registerCommand(command)
return command
return build().also(commandManager::registerCommand)
}

private fun build(): BasicsCommand {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ class ArgumentPath<T : CommandContext>(
}

init {
if (arguments.any { it.first == "sender" }) {
throw IllegalArgumentException("Argument name 'sender' is reserved")
}
require(arguments.none { it.first == "sender" }) { "Argument name 'sender' is reserved" }
}

fun matches(
Expand Down Expand Up @@ -100,7 +98,7 @@ class ArgumentPath<T : CommandContext>(
// Count length of combined arguments before this one
var myStartIndex = commandArguments.subList(0, argIndex).sumOf { it.length }
val myLength = commandArguments[argIndex].length
var myEndIndex = myStartIndex + myLength
val myEndIndex = myStartIndex + myLength

if (myEndIndex > givenArgs.size) {
return Either.Right(null)
Expand Down Expand Up @@ -153,8 +151,7 @@ class ArgumentPath<T : CommandContext>(
return ParseResult.Failure(listOf(Basics.messages.commandNotFromConsole))
}

val parsedArgs = mutableMapOf<String, Any?>()
parsedArgs["sender"] = sender
val parsedArgs = mutableMapOf<String, Any?>("sender" to sender)
val errors = mutableListOf<Message>()

for ((index, argumentPair) in arguments.withIndex()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,10 @@ class ParsedCommandExecutor<T : CommandContext>(
}

init {

for (path in paths) {
if (path.ownExecutor == null && executor == null) {
throw IllegalArgumentException(
"Attempting to create a ParsedCommandExecutor with a path that has no executor and no default " +
"executor was provided. Path: $path",
)
require(path.ownExecutor != null || executor != null) {
"Attempting to create a ParsedCommandExecutor with a path that has no executor and no default " +
"executor was provided. Path: $path"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import org.bukkit.entity.Player
import kotlin.reflect.KClass

abstract class SenderType<T : CommandSender>(val requiredType: KClass<T>) {
override fun toString(): String {
return requiredType.simpleName ?: "Unknown"
}
override fun toString() = requiredType.simpleName ?: "Unknown"
}

object PlayerSender : SenderType<Player>(Player::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ class GenericContextParsedCommandBuilder<T : CommandContext>(
permission = permission,
) {
fun GenericContextParsedCommandBuilder<T>.path(block: GenericArgumentPathBuilder<T>.() -> Unit): ArgumentPath<T> {
val builder = GenericArgumentPathBuilder<T>()
builder.block()
val built = builder.build()
this.argumentPaths.add(built)
return built
val builder = GenericArgumentPathBuilder<T>().apply(block)
return builder.build().also(this.argumentPaths::add)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ class MapContextParsedCommandBuilder(
permission = permission,
) {
fun MapContextParsedCommandBuilder.path(block: MapArgumentPathBuilder.() -> Unit): ArgumentPath<MapContext> {
val builder = MapArgumentPathBuilder()
builder.block()
val built = builder.build()
this.argumentPaths.add(built)
return built
val builder = MapArgumentPathBuilder().apply(block)
return builder.build().also(this.argumentPaths::add)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ open class ParsedCommandBuilder<T : CommandContext>(
}

fun register(): BasicsCommand {
val command = build()
commandManager.registerCommand(command)
return command
return build().also(commandManager::registerCommand)
}

fun build(): BasicsCommand {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ open class SavedConfig(context: ConfigInstantiationContext) : YamlConfiguration(
/**
* Saves this configuration to the file.
*/
fun save() {
save(file)
}
fun save() = save(file)

override fun load(file: File) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,31 +52,20 @@ data class Message(
}

fun sendToPlayers(players: Collection<Player>) {
players.forEach {
sendToPlayer(it)
}
players.forEach(this::sendToPlayer)
}

fun concerns(player: Player?): Message {
this.concerns = player
return this
}
fun concerns(player: Player?) = apply { this.concerns = player }

/**
* Applies the given transform to each line of the message
*
* @param transform Transform to apply
* @return The message with the transform applied
*/
fun map(transform: (String) -> String): Message {
lines = lines.map(transform)
return this
}
fun map(transform: (String) -> String) = apply { lines = lines.map(transform) }

private fun tags(tags: Collection<TagResolver>): Message {
customTagResolvers.addAll(tags)
return this
}
private fun tags(tags: Collection<TagResolver>) = apply { customTagResolvers.addAll(tags) }

fun tags(`object`: MessageTagProvider): Message {
`object`.getMessageTags().forEach {
Expand Down
Loading

0 comments on commit fac8d28

Please sign in to comment.