♻️ Reformat + Update .editorconfig

This commit is contained in:
Alexander Söderberg 2020-10-06 22:48:30 +02:00 committed by Alexander Söderberg
parent 8bdec87a74
commit 2aac3980d5
169 changed files with 4261 additions and 2448 deletions

View file

@ -1,55 +1,85 @@
root = true
[*] [*]
charset = utf-8 charset = utf-8
end_of_line = lf end_of_line = lf
indent_size = 4 indent_size = 4
indent_style = space indent_style = space
insert_final_newline = true insert_final_newline = true
max_line_length = 120 max_line_length = 130
tab_width = 4 tab_width = 4
ij_continuation_indent_size = 8 ij_continuation_indent_size = 8
ij_formatter_off_tag = @formatter:off ij_formatter_off_tag = @formatter:off
ij_formatter_on_tag = @formatter:on ij_formatter_on_tag = @formatter:on
ij_formatter_tags_enabled = true ij_formatter_tags_enabled = false
ij_smart_tabs = false ij_smart_tabs = false
ij_visual_guides = 130 ij_wrap_on_typing = true
ij_wrap_on_typing = false
[*.conf]
indent_size = 2
tab_width = 2
ij_continuation_indent_size = 2
ij_hocon_keep_blank_lines_before_right_brace = 2
ij_hocon_keep_indents_on_empty_lines = false
ij_hocon_keep_line_breaks = true
ij_hocon_space_after_colon = true
ij_hocon_space_after_comma = true
ij_hocon_space_before_colon = true
ij_hocon_space_before_comma = false
ij_hocon_spaces_within_braces = false
ij_hocon_spaces_within_brackets = false
ij_hocon_spaces_within_method_call_parentheses = false
[*.css]
ij_css_align_closing_brace_with_properties = false
ij_css_blank_lines_around_nested_selector = 1
ij_css_blank_lines_between_blocks = 1
ij_css_brace_placement = end_of_line
ij_css_enforce_quotes_on_format = false
ij_css_hex_color_long_format = false
ij_css_hex_color_lower_case = false
ij_css_hex_color_short_format = false
ij_css_hex_color_upper_case = false
ij_css_keep_blank_lines_in_code = 2
ij_css_keep_indents_on_empty_lines = false
ij_css_keep_single_line_blocks = false
ij_css_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow
ij_css_space_after_colon = true
ij_css_space_before_opening_brace = true
ij_css_use_double_quotes = true
ij_css_value_alignment = do_not_align
[*.java] [*.java]
max_line_length = 130
ij_java_align_consecutive_assignments = false ij_java_align_consecutive_assignments = false
ij_java_align_consecutive_variable_declarations = false ij_java_align_consecutive_variable_declarations = false
ij_java_align_group_field_declarations = false ij_java_align_group_field_declarations = false
ij_java_align_multiline_annotation_parameters = true ij_java_align_multiline_annotation_parameters = false
ij_java_align_multiline_array_initializer_expression = true ij_java_align_multiline_array_initializer_expression = false
ij_java_align_multiline_assignment = false ij_java_align_multiline_assignment = false
ij_java_align_multiline_binary_operation = false ij_java_align_multiline_binary_operation = false
ij_java_align_multiline_chained_methods = true ij_java_align_multiline_chained_methods = false
ij_java_align_multiline_extends_list = false ij_java_align_multiline_extends_list = false
ij_java_align_multiline_for = true ij_java_align_multiline_for = true
ij_java_align_multiline_method_parentheses = false ij_java_align_multiline_method_parentheses = false
ij_java_align_multiline_parameters = true ij_java_align_multiline_parameters = true
ij_java_align_multiline_parameters_in_calls = true ij_java_align_multiline_parameters_in_calls = false
ij_java_align_multiline_parenthesized_expression = false ij_java_align_multiline_parenthesized_expression = false
ij_java_align_multiline_records = true ij_java_align_multiline_records = true
ij_java_align_multiline_resources = true ij_java_align_multiline_resources = true
ij_java_align_multiline_ternary_operation = true ij_java_align_multiline_ternary_operation = false
ij_java_align_multiline_text_blocks = false ij_java_align_multiline_text_blocks = false
ij_java_align_multiline_throws_list = false ij_java_align_multiline_throws_list = false
ij_java_align_subsequent_simple_methods = false ij_java_align_subsequent_simple_methods = false
ij_java_align_throws_keyword = false ij_java_align_throws_keyword = false
ij_java_annotation_parameter_wrap = off ij_java_annotation_parameter_wrap = off
ij_java_array_initializer_new_line_after_left_brace = true ij_java_array_initializer_new_line_after_left_brace = false
ij_java_array_initializer_right_brace_on_new_line = true ij_java_array_initializer_right_brace_on_new_line = false
ij_java_array_initializer_wrap = on_every_item ij_java_array_initializer_wrap = off
ij_java_assert_statement_colon_on_next_line = false ij_java_assert_statement_colon_on_next_line = false
ij_java_assert_statement_wrap = off ij_java_assert_statement_wrap = off
ij_java_assignment_wrap = off ij_java_assignment_wrap = off
ij_java_binary_operation_sign_on_next_line = false ij_java_binary_operation_sign_on_next_line = false
ij_java_binary_operation_wrap = off ij_java_binary_operation_wrap = off
ij_java_blank_lines_after_anonymous_class_header = 0 ij_java_blank_lines_after_anonymous_class_header = 0
ij_java_blank_lines_after_class_header = 0 ij_java_blank_lines_after_class_header = 1
ij_java_blank_lines_after_imports = 1 ij_java_blank_lines_after_imports = 1
ij_java_blank_lines_after_package = 1 ij_java_blank_lines_after_package = 1
ij_java_blank_lines_around_class = 1 ij_java_blank_lines_around_class = 1
@ -58,23 +88,23 @@ ij_java_blank_lines_around_field_in_interface = 0
ij_java_blank_lines_around_initializer = 1 ij_java_blank_lines_around_initializer = 1
ij_java_blank_lines_around_method = 1 ij_java_blank_lines_around_method = 1
ij_java_blank_lines_around_method_in_interface = 1 ij_java_blank_lines_around_method_in_interface = 1
ij_java_blank_lines_before_class_end = 0 ij_java_blank_lines_before_class_end = 1
ij_java_blank_lines_before_imports = 1 ij_java_blank_lines_before_imports = 1
ij_java_blank_lines_before_method_body = 0 ij_java_blank_lines_before_method_body = 0
ij_java_blank_lines_before_package = 0 ij_java_blank_lines_before_package = 0
ij_java_block_brace_style = end_of_line ij_java_block_brace_style = end_of_line
ij_java_block_comment_at_first_column = true ij_java_block_comment_at_first_column = true
ij_java_call_parameters_new_line_after_left_paren = false ij_java_call_parameters_new_line_after_left_paren = true
ij_java_call_parameters_right_paren_on_new_line = false ij_java_call_parameters_right_paren_on_new_line = true
ij_java_call_parameters_wrap = normal ij_java_call_parameters_wrap = on_every_item
ij_java_case_statement_on_separate_line = true ij_java_case_statement_on_separate_line = true
ij_java_catch_on_new_line = false ij_java_catch_on_new_line = false
ij_java_class_annotation_wrap = split_into_lines ij_java_class_annotation_wrap = split_into_lines
ij_java_class_brace_style = end_of_line ij_java_class_brace_style = end_of_line
ij_java_class_count_to_use_import_on_demand = 9999999 ij_java_class_count_to_use_import_on_demand = 100000
ij_java_class_names_in_javadoc = 1 ij_java_class_names_in_javadoc = 1
ij_java_do_not_indent_top_level_class_members = false ij_java_do_not_indent_top_level_class_members = false
ij_java_do_not_wrap_after_single_annotation = true ij_java_do_not_wrap_after_single_annotation = false
ij_java_do_while_brace_force = always ij_java_do_while_brace_force = always
ij_java_doc_add_blank_line_after_description = true ij_java_doc_add_blank_line_after_description = true
ij_java_doc_add_blank_line_after_param_comments = false ij_java_doc_add_blank_line_after_param_comments = false
@ -85,12 +115,12 @@ ij_java_doc_align_param_comments = true
ij_java_doc_do_not_wrap_if_one_line = false ij_java_doc_do_not_wrap_if_one_line = false
ij_java_doc_enable_formatting = true ij_java_doc_enable_formatting = true
ij_java_doc_enable_leading_asterisks = true ij_java_doc_enable_leading_asterisks = true
ij_java_doc_indent_on_continuation = false ij_java_doc_indent_on_continuation = true
ij_java_doc_keep_empty_lines = true ij_java_doc_keep_empty_lines = true
ij_java_doc_keep_empty_parameter_tag = true ij_java_doc_keep_empty_parameter_tag = true
ij_java_doc_keep_empty_return_tag = true ij_java_doc_keep_empty_return_tag = true
ij_java_doc_keep_empty_throws_tag = true ij_java_doc_keep_empty_throws_tag = true
ij_java_doc_keep_invalid_tags = true ij_java_doc_keep_invalid_tags = false
ij_java_doc_param_description_on_new_line = false ij_java_doc_param_description_on_new_line = false
ij_java_doc_preserve_line_breaks = false ij_java_doc_preserve_line_breaks = false
ij_java_doc_use_throws_not_exception_tag = true ij_java_doc_use_throws_not_exception_tag = true
@ -133,18 +163,18 @@ ij_java_line_comment_at_first_column = true
ij_java_method_annotation_wrap = split_into_lines ij_java_method_annotation_wrap = split_into_lines
ij_java_method_brace_style = end_of_line ij_java_method_brace_style = end_of_line
ij_java_method_call_chain_wrap = on_every_item ij_java_method_call_chain_wrap = on_every_item
ij_java_method_parameters_new_line_after_left_paren = false ij_java_method_parameters_new_line_after_left_paren = true
ij_java_method_parameters_right_paren_on_new_line = false ij_java_method_parameters_right_paren_on_new_line = true
ij_java_method_parameters_wrap = on_every_item ij_java_method_parameters_wrap = on_every_item
ij_java_modifier_list_wrap = false ij_java_modifier_list_wrap = false
ij_java_names_count_to_use_import_on_demand = 9999999 ij_java_names_count_to_use_import_on_demand = 100000
ij_java_new_line_after_lparen_in_record_header = false ij_java_new_line_after_lparen_in_record_header = false
ij_java_parameter_annotation_wrap = on_every_item ij_java_parameter_annotation_wrap = off
ij_java_parentheses_expression_new_line_after_left_paren = false ij_java_parentheses_expression_new_line_after_left_paren = false
ij_java_parentheses_expression_right_paren_on_new_line = false ij_java_parentheses_expression_right_paren_on_new_line = false
ij_java_place_assignment_sign_on_next_line = false ij_java_place_assignment_sign_on_next_line = false
ij_java_prefer_longer_names = true ij_java_prefer_longer_names = false
ij_java_prefer_parameters_wrap = false ij_java_prefer_parameters_wrap = true
ij_java_record_components_wrap = normal ij_java_record_components_wrap = normal
ij_java_repeat_synchronized = true ij_java_repeat_synchronized = true
ij_java_replace_instanceof_and_cast = false ij_java_replace_instanceof_and_cast = false
@ -230,7 +260,7 @@ ij_java_spaces_within_try_parentheses = false
ij_java_spaces_within_while_parentheses = false ij_java_spaces_within_while_parentheses = false
ij_java_special_else_if_treatment = true ij_java_special_else_if_treatment = true
ij_java_subclass_name_suffix = Impl ij_java_subclass_name_suffix = Impl
ij_java_ternary_operation_signs_on_next_line = false ij_java_ternary_operation_signs_on_next_line = true
ij_java_ternary_operation_wrap = on_every_item ij_java_ternary_operation_wrap = on_every_item
ij_java_test_name_suffix = Test ij_java_test_name_suffix = Test
ij_java_throws_keyword_wrap = off ij_java_throws_keyword_wrap = off
@ -239,10 +269,745 @@ ij_java_use_external_annotations = false
ij_java_use_fq_class_names = false ij_java_use_fq_class_names = false
ij_java_use_relative_indents = false ij_java_use_relative_indents = false
ij_java_use_single_class_imports = true ij_java_use_single_class_imports = true
ij_java_variable_annotation_wrap = on_every_item ij_java_variable_annotation_wrap = off
ij_java_visibility = public ij_java_visibility = public
ij_java_while_brace_force = always ij_java_while_brace_force = always
ij_java_while_on_new_line = false ij_java_while_on_new_line = false
ij_java_wrap_comments = false ij_java_wrap_comments = false
ij_java_wrap_first_method_in_call_chain = false ij_java_wrap_first_method_in_call_chain = true
ij_java_wrap_long_lines = false ij_java_wrap_long_lines = false
[*.nbtt]
max_line_length = 150
ij_continuation_indent_size = 4
ij_nbtt_keep_indents_on_empty_lines = false
ij_nbtt_space_after_colon = true
ij_nbtt_space_after_comma = true
ij_nbtt_space_before_colon = true
ij_nbtt_space_before_comma = false
ij_nbtt_spaces_within_brackets = false
ij_nbtt_spaces_within_parentheses = false
[*.properties]
ij_properties_align_group_field_declarations = false
ij_properties_keep_blank_lines = false
ij_properties_key_value_delimiter = equals
ij_properties_spaces_around_key_value_delimiter = false
[*.sass]
indent_size = 2
ij_sass_align_closing_brace_with_properties = false
ij_sass_blank_lines_around_nested_selector = 1
ij_sass_blank_lines_between_blocks = 1
ij_sass_brace_placement = 0
ij_sass_enforce_quotes_on_format = false
ij_sass_hex_color_long_format = false
ij_sass_hex_color_lower_case = false
ij_sass_hex_color_short_format = false
ij_sass_hex_color_upper_case = false
ij_sass_keep_blank_lines_in_code = 2
ij_sass_keep_indents_on_empty_lines = false
ij_sass_keep_single_line_blocks = false
ij_sass_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow
ij_sass_space_after_colon = true
ij_sass_space_before_opening_brace = true
ij_sass_use_double_quotes = true
ij_sass_value_alignment = 0
[*.scss]
indent_size = 2
ij_scss_align_closing_brace_with_properties = false
ij_scss_blank_lines_around_nested_selector = 1
ij_scss_blank_lines_between_blocks = 1
ij_scss_brace_placement = 0
ij_scss_enforce_quotes_on_format = false
ij_scss_hex_color_long_format = false
ij_scss_hex_color_lower_case = false
ij_scss_hex_color_short_format = false
ij_scss_hex_color_upper_case = false
ij_scss_keep_blank_lines_in_code = 2
ij_scss_keep_indents_on_empty_lines = false
ij_scss_keep_single_line_blocks = false
ij_scss_properties_order = font, font-family, font-size, font-weight, font-style, font-variant, font-size-adjust, font-stretch, line-height, position, z-index, top, right, bottom, left, display, visibility, float, clear, overflow, overflow-x, overflow-y, clip, zoom, align-content, align-items, align-self, flex, flex-flow, flex-basis, flex-direction, flex-grow, flex-shrink, flex-wrap, justify-content, order, box-sizing, width, min-width, max-width, height, min-height, max-height, margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, table-layout, empty-cells, caption-side, border-spacing, border-collapse, list-style, list-style-position, list-style-type, list-style-image, content, quotes, counter-reset, counter-increment, resize, cursor, user-select, nav-index, nav-up, nav-right, nav-down, nav-left, transition, transition-delay, transition-timing-function, transition-duration, transition-property, transform, transform-origin, animation, animation-name, animation-duration, animation-play-state, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, text-align, text-align-last, vertical-align, white-space, text-decoration, text-emphasis, text-emphasis-color, text-emphasis-style, text-emphasis-position, text-indent, text-justify, letter-spacing, word-spacing, text-outline, text-transform, text-wrap, text-overflow, text-overflow-ellipsis, text-overflow-mode, word-wrap, word-break, tab-size, hyphens, pointer-events, opacity, color, border, border-width, border-style, border-color, border-top, border-top-width, border-top-style, border-top-color, border-right, border-right-width, border-right-style, border-right-color, border-bottom, border-bottom-width, border-bottom-style, border-bottom-color, border-left, border-left-width, border-left-style, border-left-color, border-radius, border-top-left-radius, border-top-right-radius, border-bottom-right-radius, border-bottom-left-radius, border-image, border-image-source, border-image-slice, border-image-width, border-image-outset, border-image-repeat, outline, outline-width, outline-style, outline-color, outline-offset, background, background-color, background-image, background-repeat, background-attachment, background-position, background-position-x, background-position-y, background-clip, background-origin, background-size, box-decoration-break, box-shadow, text-shadow
ij_scss_space_after_colon = true
ij_scss_space_before_opening_brace = true
ij_scss_use_double_quotes = true
ij_scss_value_alignment = 0
[.editorconfig]
ij_editorconfig_align_group_field_declarations = false
ij_editorconfig_space_after_colon = false
ij_editorconfig_space_after_comma = true
ij_editorconfig_space_before_colon = false
ij_editorconfig_space_before_comma = false
ij_editorconfig_spaces_around_assignment_operators = true
[{*.ant, *.fxml, *.jhm, *.jnlp, *.jrxml, *.pom, *.rng, *.tld, *.wsdl, *.xml, *.xsd, *.xsl, *.xslt, *.xul}]
ij_xml_align_attributes = true
ij_xml_align_text = false
ij_xml_attribute_wrap = normal
ij_xml_block_comment_at_first_column = true
ij_xml_keep_blank_lines = 2
ij_xml_keep_indents_on_empty_lines = false
ij_xml_keep_line_breaks = true
ij_xml_keep_line_breaks_in_text = true
ij_xml_keep_whitespaces = false
ij_xml_keep_whitespaces_around_cdata = preserve
ij_xml_keep_whitespaces_inside_cdata = false
ij_xml_line_comment_at_first_column = true
ij_xml_space_after_tag_name = false
ij_xml_space_around_equals_in_attribute = false
ij_xml_space_inside_empty_tag = false
ij_xml_text_wrap = normal
[{*.ats, *.ts}]
ij_continuation_indent_size = 4
ij_typescript_align_imports = false
ij_typescript_align_multiline_array_initializer_expression = false
ij_typescript_align_multiline_binary_operation = false
ij_typescript_align_multiline_chained_methods = false
ij_typescript_align_multiline_extends_list = false
ij_typescript_align_multiline_for = true
ij_typescript_align_multiline_parameters = true
ij_typescript_align_multiline_parameters_in_calls = false
ij_typescript_align_multiline_ternary_operation = false
ij_typescript_align_object_properties = 0
ij_typescript_align_union_types = false
ij_typescript_align_var_statements = 0
ij_typescript_array_initializer_new_line_after_left_brace = false
ij_typescript_array_initializer_right_brace_on_new_line = false
ij_typescript_array_initializer_wrap = off
ij_typescript_assignment_wrap = off
ij_typescript_binary_operation_sign_on_next_line = false
ij_typescript_binary_operation_wrap = off
ij_typescript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/**
ij_typescript_blank_lines_after_imports = 1
ij_typescript_blank_lines_around_class = 1
ij_typescript_blank_lines_around_field = 0
ij_typescript_blank_lines_around_field_in_interface = 0
ij_typescript_blank_lines_around_function = 1
ij_typescript_blank_lines_around_method = 1
ij_typescript_blank_lines_around_method_in_interface = 1
ij_typescript_block_brace_style = end_of_line
ij_typescript_call_parameters_new_line_after_left_paren = false
ij_typescript_call_parameters_right_paren_on_new_line = false
ij_typescript_call_parameters_wrap = off
ij_typescript_catch_on_new_line = false
ij_typescript_chained_call_dot_on_new_line = true
ij_typescript_class_brace_style = end_of_line
ij_typescript_comma_on_new_line = false
ij_typescript_do_while_brace_force = never
ij_typescript_else_on_new_line = false
ij_typescript_enforce_trailing_comma = keep
ij_typescript_extends_keyword_wrap = off
ij_typescript_extends_list_wrap = off
ij_typescript_field_prefix = _
ij_typescript_file_name_style = relaxed
ij_typescript_finally_on_new_line = false
ij_typescript_for_brace_force = never
ij_typescript_for_statement_new_line_after_left_paren = false
ij_typescript_for_statement_right_paren_on_new_line = false
ij_typescript_for_statement_wrap = off
ij_typescript_force_quote_style = false
ij_typescript_force_semicolon_style = false
ij_typescript_function_expression_brace_style = end_of_line
ij_typescript_if_brace_force = never
ij_typescript_import_merge_members = global
ij_typescript_import_prefer_absolute_path = global
ij_typescript_import_sort_members = true
ij_typescript_import_sort_module_name = false
ij_typescript_import_use_node_resolution = true
ij_typescript_imports_wrap = on_every_item
ij_typescript_indent_case_from_switch = true
ij_typescript_indent_chained_calls = true
ij_typescript_indent_package_children = 0
ij_typescript_jsdoc_include_types = false
ij_typescript_jsx_attribute_value = braces
ij_typescript_keep_blank_lines_in_code = 2
ij_typescript_keep_first_column_comment = true
ij_typescript_keep_indents_on_empty_lines = false
ij_typescript_keep_line_breaks = true
ij_typescript_keep_simple_blocks_in_one_line = false
ij_typescript_keep_simple_methods_in_one_line = false
ij_typescript_line_comment_add_space = true
ij_typescript_line_comment_at_first_column = false
ij_typescript_method_brace_style = end_of_line
ij_typescript_method_call_chain_wrap = off
ij_typescript_method_parameters_new_line_after_left_paren = false
ij_typescript_method_parameters_right_paren_on_new_line = false
ij_typescript_method_parameters_wrap = off
ij_typescript_object_literal_wrap = on_every_item
ij_typescript_parentheses_expression_new_line_after_left_paren = false
ij_typescript_parentheses_expression_right_paren_on_new_line = false
ij_typescript_place_assignment_sign_on_next_line = false
ij_typescript_prefer_as_type_cast = false
ij_typescript_prefer_explicit_types_function_expression_returns = false
ij_typescript_prefer_explicit_types_function_returns = false
ij_typescript_prefer_explicit_types_vars_fields = false
ij_typescript_prefer_parameters_wrap = false
ij_typescript_reformat_c_style_comments = false
ij_typescript_space_after_colon = true
ij_typescript_space_after_comma = true
ij_typescript_space_after_dots_in_rest_parameter = false
ij_typescript_space_after_generator_mult = true
ij_typescript_space_after_property_colon = true
ij_typescript_space_after_quest = true
ij_typescript_space_after_type_colon = true
ij_typescript_space_after_unary_not = false
ij_typescript_space_before_async_arrow_lparen = true
ij_typescript_space_before_catch_keyword = true
ij_typescript_space_before_catch_left_brace = true
ij_typescript_space_before_catch_parentheses = true
ij_typescript_space_before_class_lbrace = true
ij_typescript_space_before_class_left_brace = true
ij_typescript_space_before_colon = true
ij_typescript_space_before_comma = false
ij_typescript_space_before_do_left_brace = true
ij_typescript_space_before_else_keyword = true
ij_typescript_space_before_else_left_brace = true
ij_typescript_space_before_finally_keyword = true
ij_typescript_space_before_finally_left_brace = true
ij_typescript_space_before_for_left_brace = true
ij_typescript_space_before_for_parentheses = true
ij_typescript_space_before_for_semicolon = false
ij_typescript_space_before_function_left_parenth = true
ij_typescript_space_before_generator_mult = false
ij_typescript_space_before_if_left_brace = true
ij_typescript_space_before_if_parentheses = true
ij_typescript_space_before_method_call_parentheses = false
ij_typescript_space_before_method_left_brace = true
ij_typescript_space_before_method_parentheses = false
ij_typescript_space_before_property_colon = false
ij_typescript_space_before_quest = true
ij_typescript_space_before_switch_left_brace = true
ij_typescript_space_before_switch_parentheses = true
ij_typescript_space_before_try_left_brace = true
ij_typescript_space_before_type_colon = false
ij_typescript_space_before_unary_not = false
ij_typescript_space_before_while_keyword = true
ij_typescript_space_before_while_left_brace = true
ij_typescript_space_before_while_parentheses = true
ij_typescript_spaces_around_additive_operators = true
ij_typescript_spaces_around_arrow_function_operator = true
ij_typescript_spaces_around_assignment_operators = true
ij_typescript_spaces_around_bitwise_operators = true
ij_typescript_spaces_around_equality_operators = true
ij_typescript_spaces_around_logical_operators = true
ij_typescript_spaces_around_multiplicative_operators = true
ij_typescript_spaces_around_relational_operators = true
ij_typescript_spaces_around_shift_operators = true
ij_typescript_spaces_around_unary_operator = false
ij_typescript_spaces_within_array_initializer_brackets = false
ij_typescript_spaces_within_brackets = false
ij_typescript_spaces_within_catch_parentheses = false
ij_typescript_spaces_within_for_parentheses = false
ij_typescript_spaces_within_if_parentheses = false
ij_typescript_spaces_within_imports = false
ij_typescript_spaces_within_interpolation_expressions = false
ij_typescript_spaces_within_method_call_parentheses = false
ij_typescript_spaces_within_method_parentheses = false
ij_typescript_spaces_within_object_literal_braces = false
ij_typescript_spaces_within_object_type_braces = true
ij_typescript_spaces_within_parentheses = false
ij_typescript_spaces_within_switch_parentheses = false
ij_typescript_spaces_within_type_assertion = false
ij_typescript_spaces_within_union_types = true
ij_typescript_spaces_within_while_parentheses = false
ij_typescript_special_else_if_treatment = true
ij_typescript_ternary_operation_signs_on_next_line = false
ij_typescript_ternary_operation_wrap = off
ij_typescript_union_types_wrap = on_every_item
ij_typescript_use_chained_calls_group_indents = false
ij_typescript_use_double_quotes = true
ij_typescript_use_explicit_js_extension = global
ij_typescript_use_path_mapping = always
ij_typescript_use_public_modifier = false
ij_typescript_use_semicolon_after_statement = true
ij_typescript_var_declaration_wrap = normal
ij_typescript_while_brace_force = never
ij_typescript_while_on_new_line = false
ij_typescript_wrap_comments = false
[{*.bash, *.sh, *.zsh}]
indent_size = 2
tab_width = 2
ij_shell_binary_ops_start_line = false
ij_shell_keep_column_alignment_padding = false
ij_shell_minify_program = false
ij_shell_redirect_followed_by_space = false
ij_shell_switch_cases_indented = false
[{*.cjs, *.js}]
ij_continuation_indent_size = 4
ij_javascript_align_imports = false
ij_javascript_align_multiline_array_initializer_expression = false
ij_javascript_align_multiline_binary_operation = false
ij_javascript_align_multiline_chained_methods = false
ij_javascript_align_multiline_extends_list = false
ij_javascript_align_multiline_for = true
ij_javascript_align_multiline_parameters = true
ij_javascript_align_multiline_parameters_in_calls = false
ij_javascript_align_multiline_ternary_operation = false
ij_javascript_align_object_properties = 0
ij_javascript_align_union_types = false
ij_javascript_align_var_statements = 0
ij_javascript_array_initializer_new_line_after_left_brace = false
ij_javascript_array_initializer_right_brace_on_new_line = false
ij_javascript_array_initializer_wrap = off
ij_javascript_assignment_wrap = off
ij_javascript_binary_operation_sign_on_next_line = false
ij_javascript_binary_operation_wrap = off
ij_javascript_blacklist_imports = rxjs/Rx, node_modules/**, **/node_modules/**, @angular/material, @angular/material/typings/**
ij_javascript_blank_lines_after_imports = 1
ij_javascript_blank_lines_around_class = 1
ij_javascript_blank_lines_around_field = 0
ij_javascript_blank_lines_around_function = 1
ij_javascript_blank_lines_around_method = 1
ij_javascript_block_brace_style = end_of_line
ij_javascript_call_parameters_new_line_after_left_paren = false
ij_javascript_call_parameters_right_paren_on_new_line = false
ij_javascript_call_parameters_wrap = off
ij_javascript_catch_on_new_line = false
ij_javascript_chained_call_dot_on_new_line = true
ij_javascript_class_brace_style = end_of_line
ij_javascript_comma_on_new_line = false
ij_javascript_do_while_brace_force = never
ij_javascript_else_on_new_line = false
ij_javascript_enforce_trailing_comma = keep
ij_javascript_extends_keyword_wrap = off
ij_javascript_extends_list_wrap = off
ij_javascript_field_prefix = _
ij_javascript_file_name_style = relaxed
ij_javascript_finally_on_new_line = false
ij_javascript_for_brace_force = never
ij_javascript_for_statement_new_line_after_left_paren = false
ij_javascript_for_statement_right_paren_on_new_line = false
ij_javascript_for_statement_wrap = off
ij_javascript_force_quote_style = false
ij_javascript_force_semicolon_style = false
ij_javascript_function_expression_brace_style = end_of_line
ij_javascript_if_brace_force = never
ij_javascript_import_merge_members = global
ij_javascript_import_prefer_absolute_path = global
ij_javascript_import_sort_members = true
ij_javascript_import_sort_module_name = false
ij_javascript_import_use_node_resolution = true
ij_javascript_imports_wrap = on_every_item
ij_javascript_indent_case_from_switch = true
ij_javascript_indent_chained_calls = true
ij_javascript_indent_package_children = 0
ij_javascript_jsx_attribute_value = braces
ij_javascript_keep_blank_lines_in_code = 2
ij_javascript_keep_first_column_comment = true
ij_javascript_keep_indents_on_empty_lines = false
ij_javascript_keep_line_breaks = true
ij_javascript_keep_simple_blocks_in_one_line = false
ij_javascript_keep_simple_methods_in_one_line = false
ij_javascript_line_comment_add_space = true
ij_javascript_line_comment_at_first_column = false
ij_javascript_method_brace_style = end_of_line
ij_javascript_method_call_chain_wrap = off
ij_javascript_method_parameters_new_line_after_left_paren = false
ij_javascript_method_parameters_right_paren_on_new_line = false
ij_javascript_method_parameters_wrap = off
ij_javascript_object_literal_wrap = on_every_item
ij_javascript_parentheses_expression_new_line_after_left_paren = false
ij_javascript_parentheses_expression_right_paren_on_new_line = false
ij_javascript_place_assignment_sign_on_next_line = false
ij_javascript_prefer_as_type_cast = false
ij_javascript_prefer_explicit_types_function_expression_returns = false
ij_javascript_prefer_explicit_types_function_returns = false
ij_javascript_prefer_explicit_types_vars_fields = false
ij_javascript_prefer_parameters_wrap = false
ij_javascript_reformat_c_style_comments = false
ij_javascript_space_after_colon = true
ij_javascript_space_after_comma = true
ij_javascript_space_after_dots_in_rest_parameter = false
ij_javascript_space_after_generator_mult = true
ij_javascript_space_after_property_colon = true
ij_javascript_space_after_quest = true
ij_javascript_space_after_type_colon = true
ij_javascript_space_after_unary_not = false
ij_javascript_space_before_async_arrow_lparen = true
ij_javascript_space_before_catch_keyword = true
ij_javascript_space_before_catch_left_brace = true
ij_javascript_space_before_catch_parentheses = true
ij_javascript_space_before_class_lbrace = true
ij_javascript_space_before_class_left_brace = true
ij_javascript_space_before_colon = true
ij_javascript_space_before_comma = false
ij_javascript_space_before_do_left_brace = true
ij_javascript_space_before_else_keyword = true
ij_javascript_space_before_else_left_brace = true
ij_javascript_space_before_finally_keyword = true
ij_javascript_space_before_finally_left_brace = true
ij_javascript_space_before_for_left_brace = true
ij_javascript_space_before_for_parentheses = true
ij_javascript_space_before_for_semicolon = false
ij_javascript_space_before_function_left_parenth = true
ij_javascript_space_before_generator_mult = false
ij_javascript_space_before_if_left_brace = true
ij_javascript_space_before_if_parentheses = true
ij_javascript_space_before_method_call_parentheses = false
ij_javascript_space_before_method_left_brace = true
ij_javascript_space_before_method_parentheses = false
ij_javascript_space_before_property_colon = false
ij_javascript_space_before_quest = true
ij_javascript_space_before_switch_left_brace = true
ij_javascript_space_before_switch_parentheses = true
ij_javascript_space_before_try_left_brace = true
ij_javascript_space_before_type_colon = false
ij_javascript_space_before_unary_not = false
ij_javascript_space_before_while_keyword = true
ij_javascript_space_before_while_left_brace = true
ij_javascript_space_before_while_parentheses = true
ij_javascript_spaces_around_additive_operators = true
ij_javascript_spaces_around_arrow_function_operator = true
ij_javascript_spaces_around_assignment_operators = true
ij_javascript_spaces_around_bitwise_operators = true
ij_javascript_spaces_around_equality_operators = true
ij_javascript_spaces_around_logical_operators = true
ij_javascript_spaces_around_multiplicative_operators = true
ij_javascript_spaces_around_relational_operators = true
ij_javascript_spaces_around_shift_operators = true
ij_javascript_spaces_around_unary_operator = false
ij_javascript_spaces_within_array_initializer_brackets = false
ij_javascript_spaces_within_brackets = false
ij_javascript_spaces_within_catch_parentheses = false
ij_javascript_spaces_within_for_parentheses = false
ij_javascript_spaces_within_if_parentheses = false
ij_javascript_spaces_within_imports = false
ij_javascript_spaces_within_interpolation_expressions = false
ij_javascript_spaces_within_method_call_parentheses = false
ij_javascript_spaces_within_method_parentheses = false
ij_javascript_spaces_within_object_literal_braces = false
ij_javascript_spaces_within_object_type_braces = true
ij_javascript_spaces_within_parentheses = false
ij_javascript_spaces_within_switch_parentheses = false
ij_javascript_spaces_within_type_assertion = false
ij_javascript_spaces_within_union_types = true
ij_javascript_spaces_within_while_parentheses = false
ij_javascript_special_else_if_treatment = true
ij_javascript_ternary_operation_signs_on_next_line = false
ij_javascript_ternary_operation_wrap = off
ij_javascript_union_types_wrap = on_every_item
ij_javascript_use_chained_calls_group_indents = false
ij_javascript_use_double_quotes = true
ij_javascript_use_explicit_js_extension = global
ij_javascript_use_path_mapping = always
ij_javascript_use_public_modifier = false
ij_javascript_use_semicolon_after_statement = true
ij_javascript_var_declaration_wrap = normal
ij_javascript_while_brace_force = never
ij_javascript_while_on_new_line = false
ij_javascript_wrap_comments = false
[{*.ft, *.vm, *.vsl}]
ij_vtl_keep_indents_on_empty_lines = false
[{*.gant, *.gradle, *.groovy, *.gy}]
ij_groovy_align_group_field_declarations = false
ij_groovy_align_multiline_array_initializer_expression = false
ij_groovy_align_multiline_assignment = false
ij_groovy_align_multiline_binary_operation = false
ij_groovy_align_multiline_chained_methods = false
ij_groovy_align_multiline_extends_list = false
ij_groovy_align_multiline_for = true
ij_groovy_align_multiline_list_or_map = true
ij_groovy_align_multiline_method_parentheses = false
ij_groovy_align_multiline_parameters = true
ij_groovy_align_multiline_parameters_in_calls = false
ij_groovy_align_multiline_resources = true
ij_groovy_align_multiline_ternary_operation = false
ij_groovy_align_multiline_throws_list = false
ij_groovy_align_named_args_in_map = true
ij_groovy_align_throws_keyword = false
ij_groovy_array_initializer_new_line_after_left_brace = false
ij_groovy_array_initializer_right_brace_on_new_line = false
ij_groovy_array_initializer_wrap = off
ij_groovy_assert_statement_wrap = off
ij_groovy_assignment_wrap = off
ij_groovy_binary_operation_wrap = off
ij_groovy_blank_lines_after_class_header = 0
ij_groovy_blank_lines_after_imports = 1
ij_groovy_blank_lines_after_package = 1
ij_groovy_blank_lines_around_class = 1
ij_groovy_blank_lines_around_field = 0
ij_groovy_blank_lines_around_field_in_interface = 0
ij_groovy_blank_lines_around_method = 1
ij_groovy_blank_lines_around_method_in_interface = 1
ij_groovy_blank_lines_before_imports = 1
ij_groovy_blank_lines_before_method_body = 0
ij_groovy_blank_lines_before_package = 0
ij_groovy_block_brace_style = end_of_line
ij_groovy_block_comment_at_first_column = true
ij_groovy_call_parameters_new_line_after_left_paren = false
ij_groovy_call_parameters_right_paren_on_new_line = false
ij_groovy_call_parameters_wrap = off
ij_groovy_catch_on_new_line = false
ij_groovy_class_annotation_wrap = split_into_lines
ij_groovy_class_brace_style = end_of_line
ij_groovy_class_count_to_use_import_on_demand = 5
ij_groovy_do_while_brace_force = never
ij_groovy_else_on_new_line = false
ij_groovy_enum_constants_wrap = off
ij_groovy_extends_keyword_wrap = off
ij_groovy_extends_list_wrap = off
ij_groovy_field_annotation_wrap = split_into_lines
ij_groovy_finally_on_new_line = false
ij_groovy_for_brace_force = never
ij_groovy_for_statement_new_line_after_left_paren = false
ij_groovy_for_statement_right_paren_on_new_line = false
ij_groovy_for_statement_wrap = off
ij_groovy_if_brace_force = never
ij_groovy_import_annotation_wrap = 2
ij_groovy_imports_layout = *, |, javax.**, java.**, |, $*
ij_groovy_indent_case_from_switch = true
ij_groovy_indent_label_blocks = true
ij_groovy_insert_inner_class_imports = false
ij_groovy_keep_blank_lines_before_right_brace = 2
ij_groovy_keep_blank_lines_in_code = 2
ij_groovy_keep_blank_lines_in_declarations = 2
ij_groovy_keep_control_statement_in_one_line = true
ij_groovy_keep_first_column_comment = true
ij_groovy_keep_indents_on_empty_lines = false
ij_groovy_keep_line_breaks = true
ij_groovy_keep_multiple_expressions_in_one_line = false
ij_groovy_keep_simple_blocks_in_one_line = false
ij_groovy_keep_simple_classes_in_one_line = true
ij_groovy_keep_simple_lambdas_in_one_line = true
ij_groovy_keep_simple_methods_in_one_line = true
ij_groovy_label_indent_absolute = false
ij_groovy_label_indent_size = 0
ij_groovy_lambda_brace_style = end_of_line
ij_groovy_layout_static_imports_separately = true
ij_groovy_line_comment_add_space = false
ij_groovy_line_comment_at_first_column = true
ij_groovy_method_annotation_wrap = split_into_lines
ij_groovy_method_brace_style = end_of_line
ij_groovy_method_call_chain_wrap = off
ij_groovy_method_parameters_new_line_after_left_paren = false
ij_groovy_method_parameters_right_paren_on_new_line = false
ij_groovy_method_parameters_wrap = off
ij_groovy_modifier_list_wrap = false
ij_groovy_names_count_to_use_import_on_demand = 3
ij_groovy_parameter_annotation_wrap = off
ij_groovy_parentheses_expression_new_line_after_left_paren = false
ij_groovy_parentheses_expression_right_paren_on_new_line = false
ij_groovy_prefer_parameters_wrap = false
ij_groovy_resource_list_new_line_after_left_paren = false
ij_groovy_resource_list_right_paren_on_new_line = false
ij_groovy_resource_list_wrap = off
ij_groovy_space_after_assert_separator = true
ij_groovy_space_after_colon = true
ij_groovy_space_after_comma = true
ij_groovy_space_after_comma_in_type_arguments = true
ij_groovy_space_after_for_semicolon = true
ij_groovy_space_after_quest = true
ij_groovy_space_after_type_cast = true
ij_groovy_space_before_annotation_parameter_list = false
ij_groovy_space_before_array_initializer_left_brace = false
ij_groovy_space_before_assert_separator = false
ij_groovy_space_before_catch_keyword = true
ij_groovy_space_before_catch_left_brace = true
ij_groovy_space_before_catch_parentheses = true
ij_groovy_space_before_class_left_brace = true
ij_groovy_space_before_closure_left_brace = true
ij_groovy_space_before_colon = true
ij_groovy_space_before_comma = false
ij_groovy_space_before_do_left_brace = true
ij_groovy_space_before_else_keyword = true
ij_groovy_space_before_else_left_brace = true
ij_groovy_space_before_finally_keyword = true
ij_groovy_space_before_finally_left_brace = true
ij_groovy_space_before_for_left_brace = true
ij_groovy_space_before_for_parentheses = true
ij_groovy_space_before_for_semicolon = false
ij_groovy_space_before_if_left_brace = true
ij_groovy_space_before_if_parentheses = true
ij_groovy_space_before_method_call_parentheses = false
ij_groovy_space_before_method_left_brace = true
ij_groovy_space_before_method_parentheses = false
ij_groovy_space_before_quest = true
ij_groovy_space_before_switch_left_brace = true
ij_groovy_space_before_switch_parentheses = true
ij_groovy_space_before_synchronized_left_brace = true
ij_groovy_space_before_synchronized_parentheses = true
ij_groovy_space_before_try_left_brace = true
ij_groovy_space_before_try_parentheses = true
ij_groovy_space_before_while_keyword = true
ij_groovy_space_before_while_left_brace = true
ij_groovy_space_before_while_parentheses = true
ij_groovy_space_in_named_argument = true
ij_groovy_space_in_named_argument_before_colon = false
ij_groovy_space_within_empty_array_initializer_braces = false
ij_groovy_space_within_empty_method_call_parentheses = false
ij_groovy_spaces_around_additive_operators = true
ij_groovy_spaces_around_assignment_operators = true
ij_groovy_spaces_around_bitwise_operators = true
ij_groovy_spaces_around_equality_operators = true
ij_groovy_spaces_around_lambda_arrow = true
ij_groovy_spaces_around_logical_operators = true
ij_groovy_spaces_around_multiplicative_operators = true
ij_groovy_spaces_around_regex_operators = true
ij_groovy_spaces_around_relational_operators = true
ij_groovy_spaces_around_shift_operators = true
ij_groovy_spaces_within_annotation_parentheses = false
ij_groovy_spaces_within_array_initializer_braces = false
ij_groovy_spaces_within_braces = true
ij_groovy_spaces_within_brackets = false
ij_groovy_spaces_within_cast_parentheses = false
ij_groovy_spaces_within_catch_parentheses = false
ij_groovy_spaces_within_for_parentheses = false
ij_groovy_spaces_within_gstring_injection_braces = false
ij_groovy_spaces_within_if_parentheses = false
ij_groovy_spaces_within_list_or_map = false
ij_groovy_spaces_within_method_call_parentheses = false
ij_groovy_spaces_within_method_parentheses = false
ij_groovy_spaces_within_parentheses = false
ij_groovy_spaces_within_switch_parentheses = false
ij_groovy_spaces_within_synchronized_parentheses = false
ij_groovy_spaces_within_try_parentheses = false
ij_groovy_spaces_within_tuple_expression = false
ij_groovy_spaces_within_while_parentheses = false
ij_groovy_special_else_if_treatment = true
ij_groovy_ternary_operation_wrap = off
ij_groovy_throws_keyword_wrap = off
ij_groovy_throws_list_wrap = off
ij_groovy_use_flying_geese_braces = false
ij_groovy_use_fq_class_names = false
ij_groovy_use_fq_class_names_in_javadoc = true
ij_groovy_use_relative_indents = false
ij_groovy_use_single_class_imports = true
ij_groovy_variable_annotation_wrap = off
ij_groovy_while_brace_force = never
ij_groovy_while_on_new_line = false
ij_groovy_wrap_long_lines = false
[{*.gradle.kts, *.kt, *.kts, *.main.kts}]
ij_kotlin_align_in_columns_case_branch = false
ij_kotlin_align_multiline_binary_operation = false
ij_kotlin_align_multiline_extends_list = false
ij_kotlin_align_multiline_method_parentheses = false
ij_kotlin_align_multiline_parameters = true
ij_kotlin_align_multiline_parameters_in_calls = false
ij_kotlin_allow_trailing_comma = false
ij_kotlin_allow_trailing_comma_on_call_site = false
ij_kotlin_assignment_wrap = off
ij_kotlin_blank_lines_after_class_header = 0
ij_kotlin_blank_lines_around_block_when_branches = 0
ij_kotlin_blank_lines_before_declaration_with_comment_or_annotation_on_separate_line = 1
ij_kotlin_block_comment_at_first_column = true
ij_kotlin_call_parameters_new_line_after_left_paren = false
ij_kotlin_call_parameters_right_paren_on_new_line = false
ij_kotlin_call_parameters_wrap = off
ij_kotlin_catch_on_new_line = false
ij_kotlin_class_annotation_wrap = split_into_lines
ij_kotlin_continuation_indent_for_chained_calls = true
ij_kotlin_continuation_indent_for_expression_bodies = true
ij_kotlin_continuation_indent_in_argument_lists = true
ij_kotlin_continuation_indent_in_elvis = true
ij_kotlin_continuation_indent_in_if_conditions = true
ij_kotlin_continuation_indent_in_parameter_lists = true
ij_kotlin_continuation_indent_in_supertype_lists = true
ij_kotlin_else_on_new_line = false
ij_kotlin_enum_constants_wrap = off
ij_kotlin_extends_list_wrap = off
ij_kotlin_field_annotation_wrap = split_into_lines
ij_kotlin_finally_on_new_line = false
ij_kotlin_if_rparen_on_new_line = false
ij_kotlin_import_nested_classes = false
ij_kotlin_insert_whitespaces_in_simple_one_line_method = true
ij_kotlin_keep_blank_lines_before_right_brace = 2
ij_kotlin_keep_blank_lines_in_code = 2
ij_kotlin_keep_blank_lines_in_declarations = 2
ij_kotlin_keep_first_column_comment = true
ij_kotlin_keep_indents_on_empty_lines = false
ij_kotlin_keep_line_breaks = true
ij_kotlin_lbrace_on_next_line = false
ij_kotlin_line_comment_add_space = false
ij_kotlin_line_comment_at_first_column = true
ij_kotlin_method_annotation_wrap = split_into_lines
ij_kotlin_method_call_chain_wrap = off
ij_kotlin_method_parameters_new_line_after_left_paren = false
ij_kotlin_method_parameters_right_paren_on_new_line = false
ij_kotlin_method_parameters_wrap = off
ij_kotlin_name_count_to_use_star_import = 5
ij_kotlin_name_count_to_use_star_import_for_members = 3
ij_kotlin_parameter_annotation_wrap = off
ij_kotlin_space_after_comma = true
ij_kotlin_space_after_extend_colon = true
ij_kotlin_space_after_type_colon = true
ij_kotlin_space_before_catch_parentheses = true
ij_kotlin_space_before_comma = false
ij_kotlin_space_before_extend_colon = true
ij_kotlin_space_before_for_parentheses = true
ij_kotlin_space_before_if_parentheses = true
ij_kotlin_space_before_lambda_arrow = true
ij_kotlin_space_before_type_colon = false
ij_kotlin_space_before_when_parentheses = true
ij_kotlin_space_before_while_parentheses = true
ij_kotlin_spaces_around_additive_operators = true
ij_kotlin_spaces_around_assignment_operators = true
ij_kotlin_spaces_around_equality_operators = true
ij_kotlin_spaces_around_function_type_arrow = true
ij_kotlin_spaces_around_logical_operators = true
ij_kotlin_spaces_around_multiplicative_operators = true
ij_kotlin_spaces_around_range = false
ij_kotlin_spaces_around_relational_operators = true
ij_kotlin_spaces_around_unary_operator = false
ij_kotlin_spaces_around_when_arrow = true
ij_kotlin_variable_annotation_wrap = off
ij_kotlin_while_on_new_line = false
ij_kotlin_wrap_elvis_expressions = 1
ij_kotlin_wrap_expression_body_functions = 0
ij_kotlin_wrap_first_method_in_call_chain = false
[{*.har, *.jsb2, *.jsb3, *.json, .babelrc, .eslintrc, .stylelintrc, bowerrc, jest.config, mcmod.info}]
indent_size = 2
ij_json_keep_blank_lines_in_code = 0
ij_json_keep_indents_on_empty_lines = false
ij_json_keep_line_breaks = true
ij_json_space_after_colon = true
ij_json_space_after_comma = true
ij_json_space_before_colon = true
ij_json_space_before_comma = false
ij_json_spaces_within_braces = false
ij_json_spaces_within_brackets = false
ij_json_wrap_long_lines = false
[{*.htm, *.html, *.sht, *.shtm, *.shtml}]
ij_html_add_new_line_before_tags = body, div, p, form, h1, h2, h3
ij_html_align_attributes = true
ij_html_align_text = false
ij_html_attribute_wrap = normal
ij_html_block_comment_at_first_column = true
ij_html_do_not_align_children_of_min_lines = 0
ij_html_do_not_break_if_inline_tags = title, h1, h2, h3, h4, h5, h6, p
ij_html_do_not_indent_children_of_tags = html, body, thead, tbody, tfoot
ij_html_enforce_quotes = false
ij_html_inline_tags = a, abbr, acronym, b, basefont, bdo, big, br, cite, cite, code, dfn, em, font, i, img, input, kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, var
ij_html_keep_blank_lines = 2
ij_html_keep_indents_on_empty_lines = false
ij_html_keep_line_breaks = true
ij_html_keep_line_breaks_in_text = true
ij_html_keep_whitespaces = false
ij_html_keep_whitespaces_inside = span, pre, textarea
ij_html_line_comment_at_first_column = true
ij_html_new_line_after_last_attribute = never
ij_html_new_line_before_first_attribute = never
ij_html_quote_style = double
ij_html_remove_new_line_before_tags = br
ij_html_space_after_tag_name = false
ij_html_space_around_equality_in_attribute = false
ij_html_space_inside_empty_tag = false
ij_html_text_wrap = normal
ij_html_uniform_ident = false
[{*.yaml, *.yml}]
indent_size = 2
ij_yaml_keep_indents_on_empty_lines = false
ij_yaml_keep_line_breaks = true
ij_yaml_space_before_colon = true
ij_yaml_spaces_within_braces = true
ij_yaml_spaces_within_brackets = true

2
.github/FUNDING.yml vendored
View file

@ -9,4 +9,4 @@ community_bridge: # Replace with a single Community Bridge project-name e.g., cl
liberapay: # Replace with a single Liberapay username liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username otechie: # Replace with a single Otechie username
custom: ['https://paypal.me/Sauilitired']# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] custom: [ 'https://paypal.me/Sauilitired' ]# Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

View file

@ -171,9 +171,11 @@ subprojects {
} }
signing { signing {
required { project.hasProperty('signing.keyId') && (gradle.taskGraph.hasTask(':publish') required {
project.hasProperty('signing.keyId') && (gradle.taskGraph.hasTask(':publish')
|| gradle.taskGraph.hasTask(':publishToSonatype') || gradle.taskGraph.hasTask(':publishToSonatype')
|| gradle.taskGraph.hasTask(':publishToMavenLocal')) } || gradle.taskGraph.hasTask(':publishToMavenLocal'))
}
sign publishing.publications.mavenJava sign publishing.publications.mavenJava
} }

View file

@ -30,13 +30,13 @@ import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.flags.CommandFlag; import cloud.commandframework.arguments.flags.CommandFlag;
import cloud.commandframework.arguments.parser.ArgumentParser; import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.arguments.parser.ParserParameter; import cloud.commandframework.arguments.parser.ParserParameter;
import cloud.commandframework.arguments.parser.ParserParameters;
import cloud.commandframework.arguments.parser.StandardParameters; import cloud.commandframework.arguments.parser.StandardParameters;
import cloud.commandframework.execution.CommandExecutionHandler; import cloud.commandframework.execution.CommandExecutionHandler;
import cloud.commandframework.extra.confirmation.CommandConfirmationManager; import cloud.commandframework.extra.confirmation.CommandConfirmationManager;
import cloud.commandframework.meta.CommandMeta; import cloud.commandframework.meta.CommandMeta;
import cloud.commandframework.meta.SimpleCommandMeta; import cloud.commandframework.meta.SimpleCommandMeta;
import io.leangen.geantyref.TypeToken; import io.leangen.geantyref.TypeToken;
import cloud.commandframework.arguments.parser.ParserParameters;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -77,9 +77,11 @@ public final class AnnotationParser<C> {
* {@link ParserParameter}. Mappers for the * {@link ParserParameter}. Mappers for the
* parser parameters can be registered using {@link #registerAnnotationMapper(Class, Function)} * parser parameters can be registered using {@link #registerAnnotationMapper(Class, Function)}
*/ */
public AnnotationParser(final @NonNull CommandManager<C> manager, public AnnotationParser(
final @NonNull CommandManager<C> manager,
final @NonNull Class<C> commandSenderClass, final @NonNull Class<C> commandSenderClass,
final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper) { final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper
) {
this.commandSenderClass = commandSenderClass; this.commandSenderClass = commandSenderClass;
this.manager = manager; this.manager = manager;
this.metaFactory = new MetaFactory(this, metaMapper); this.metaFactory = new MetaFactory(this, metaMapper);
@ -96,9 +98,11 @@ public final class AnnotationParser<C> {
* @param mapper Mapping function * @param mapper Mapping function
* @param <A> Annotation type * @param <A> Annotation type
*/ */
public <A extends Annotation> void registerAnnotationMapper(final @NonNull Class<A> annotation, public <A extends Annotation> void registerAnnotationMapper(
final @NonNull Class<A> annotation,
final @NonNull Function<@NonNull A, final @NonNull Function<@NonNull A,
@NonNull ParserParameters> mapper) { @NonNull ParserParameters> mapper
) {
this.annotationMappers.put(annotation, mapper); this.annotationMappers.put(annotation, mapper);
} }
@ -122,8 +126,10 @@ public final class AnnotationParser<C> {
method.setAccessible(true); method.setAccessible(true);
} }
if (method.getReturnType() != Void.TYPE) { if (method.getReturnType() != Void.TYPE) {
throw new IllegalArgumentException(String.format("@CommandMethod annotated method '%s' has non-void return type", throw new IllegalArgumentException(String.format(
method.getName())); "@CommandMethod annotated method '%s' has non-void return type",
method.getName()
));
} }
commandMethodPairs.add(new CommandMethodPair(method, commandMethod)); commandMethodPairs.add(new CommandMethodPair(method, commandMethod));
} }
@ -139,7 +145,8 @@ public final class AnnotationParser<C> {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private @NonNull Collection<@NonNull Command<C>> construct( private @NonNull Collection<@NonNull Command<C>> construct(
final @NonNull Object instance, final @NonNull Object instance,
final @NonNull Collection<@NonNull CommandMethodPair> methodPairs) { final @NonNull Collection<@NonNull CommandMethodPair> methodPairs
) {
final Collection<Command<C>> commands = new ArrayList<>(); final Collection<Command<C>> commands = new ArrayList<>();
for (final CommandMethodPair commandMethodPair : methodPairs) { for (final CommandMethodPair commandMethodPair : methodPairs) {
final CommandMethod commandMethod = commandMethodPair.getCommandMethod(); final CommandMethod commandMethod = commandMethodPair.getCommandMethod();
@ -155,18 +162,22 @@ public final class AnnotationParser<C> {
} }
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
Command.Builder builder = manager.commandBuilder(commandToken, Command.Builder builder = manager.commandBuilder(
commandToken,
tokens.get(commandToken).getMinor(), tokens.get(commandToken).getMinor(),
metaBuilder.build()); metaBuilder.build()
);
final Collection<ArgumentParameterPair> arguments = this.argumentExtractor.apply(method); final Collection<ArgumentParameterPair> arguments = this.argumentExtractor.apply(method);
final Collection<CommandFlag<?>> flags = this.flagExtractor.apply(method); final Collection<CommandFlag<?>> flags = this.flagExtractor.apply(method);
final Map<String, CommandArgument<C, ?>> commandArguments = new HashMap<>(); final Map<String, CommandArgument<C, ?>> commandArguments = new HashMap<>();
final Map<CommandArgument<C, ?>, String> argumentDescriptions = new HashMap<>(); final Map<CommandArgument<C, ?>, String> argumentDescriptions = new HashMap<>();
/* Go through all annotated parameters and build up the argument tree */ /* Go through all annotated parameters and build up the argument tree */
for (final ArgumentParameterPair argumentPair : arguments) { for (final ArgumentParameterPair argumentPair : arguments) {
final CommandArgument<C, ?> argument = this.buildArgument(method, final CommandArgument<C, ?> argument = this.buildArgument(
method,
tokens.get(argumentPair.getArgument().value()), tokens.get(argumentPair.getArgument().value()),
argumentPair); argumentPair
);
commandArguments.put(argument.getName(), argument); commandArguments.put(argument.getName(), argument);
argumentDescriptions.put(argument, argumentPair.getArgument().description()); argumentDescriptions.put(argument, argumentPair.getArgument().description());
} }
@ -209,9 +220,9 @@ public final class AnnotationParser<C> {
} }
if (commandMethod.requiredSender() != Object.class) { if (commandMethod.requiredSender() != Object.class) {
builder = builder.withSenderType(commandMethod.requiredSender()); builder = builder.senderType(commandMethod.requiredSender());
} else if (senderType != null) { } else if (senderType != null) {
builder = builder.withSenderType(senderType); builder = builder.senderType(senderType);
} }
try { try {
/* Construct the handler */ /* Construct the handler */
@ -251,9 +262,11 @@ public final class AnnotationParser<C> {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private @NonNull CommandArgument<C, ?> buildArgument(final @NonNull Method method, private @NonNull CommandArgument<C, ?> buildArgument(
final @NonNull Method method,
final @Nullable SyntaxFragment syntaxFragment, final @Nullable SyntaxFragment syntaxFragment,
final @NonNull ArgumentParameterPair argumentPair) { final @NonNull ArgumentParameterPair argumentPair
) {
final Parameter parameter = argumentPair.getParameter(); final Parameter parameter = argumentPair.getParameter();
final Collection<Annotation> annotations = Arrays.asList(parameter.getAnnotations()); final Collection<Annotation> annotations = Arrays.asList(parameter.getAnnotations());
final TypeToken<?> token = TypeToken.get(parameter.getParameterizedType()); final TypeToken<?> token = TypeToken.get(parameter.getParameterizedType());
@ -269,7 +282,8 @@ public final class AnnotationParser<C> {
+ "has parser '%s' but no parser exists " + "has parser '%s' but no parser exists "
+ "for that type", + "for that type",
parameter.getName(), method.getName(), parameter.getName(), method.getName(),
token.toString()))); token.toString()
)));
} else { } else {
parser = this.manager.getParserRegistry() parser = this.manager.getParserRegistry()
.createParser(argumentPair.getArgument().parserName(), parameters) .createParser(argumentPair.getArgument().parserName(), parameters)
@ -278,7 +292,8 @@ public final class AnnotationParser<C> {
+ "has parser '%s' but no parser exists " + "has parser '%s' but no parser exists "
+ "for that type", + "for that type",
parameter.getName(), method.getName(), parameter.getName(), method.getName(),
token.toString()))); token.toString()
)));
} }
if (syntaxFragment == null || syntaxFragment.getArgumentMode() == ArgumentMode.LITERAL) { if (syntaxFragment == null || syntaxFragment.getArgumentMode() == ArgumentMode.LITERAL) {
@ -287,8 +302,10 @@ public final class AnnotationParser<C> {
+ "Missing syntax mapping", argumentPair.getArgument().value(), method.getName())); + "Missing syntax mapping", argumentPair.getArgument().value(), method.getName()));
} }
final Argument argument = argumentPair.getArgument(); final Argument argument = argumentPair.getArgument();
@SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(parameter.getType(), @SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(
argument.value()); parameter.getType(),
argument.value()
);
if (syntaxFragment.getArgumentMode() == ArgumentMode.OPTIONAL) { if (syntaxFragment.getArgumentMode() == ArgumentMode.OPTIONAL) {
if (argument.defaultValue().isEmpty()) { if (argument.defaultValue().isEmpty()) {
argumentBuilder.asOptional(); argumentBuilder.asOptional();

View file

@ -32,8 +32,10 @@ final class ArgumentParameterPair {
private final Parameter parameter; private final Parameter parameter;
private final Argument argument; private final Argument argument;
ArgumentParameterPair(final @NonNull Parameter parameter, ArgumentParameterPair(
final @NonNull Argument argument) { final @NonNull Parameter parameter,
final @NonNull Argument argument
) {
this.parameter = parameter; this.parameter = parameter;
this.argument = argument; this.argument = argument;
} }

View file

@ -32,8 +32,10 @@ final class CommandMethodPair {
private final Method method; private final Method method;
private final CommandMethod commandMethod; private final CommandMethod commandMethod;
CommandMethodPair(final @NonNull Method method, CommandMethodPair(
final @NonNull CommandMethod commandMethod) { final @NonNull Method method,
final @NonNull CommandMethod commandMethod
) {
this.method = method; this.method = method;
this.commandMethod = commandMethod; this.commandMethod = commandMethod;
} }

View file

@ -34,4 +34,5 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
public @interface Confirmation { public @interface Confirmation {
} }

View file

@ -55,8 +55,10 @@ final class FlagExtractor implements Function<@NonNull Method, Collection<@NonNu
continue; continue;
} }
final Flag flag = parameter.getAnnotation(Flag.class); final Flag flag = parameter.getAnnotation(Flag.class);
final CommandFlag.Builder<Void> builder = this.commandManager.flagBuilder(flag.value()) final CommandFlag.Builder<Void> builder = this.commandManager
.withDescription(Description.of(flag.description())).withAliases(flag.aliases()); .flagBuilder(flag.value())
.withDescription(Description.of(flag.description()))
.withAliases(flag.aliases());
if (parameter.getType().equals(boolean.class)) { if (parameter.getType().equals(boolean.class)) {
flags.add(builder.build()); flags.add(builder.build());
} else { } else {
@ -72,12 +74,14 @@ final class FlagExtractor implements Function<@NonNull Method, Collection<@NonNu
if (parser == null) { if (parser == null) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
String.format("Cannot find parser for type '%s' for flag '%s' in method '%s'", String.format("Cannot find parser for type '%s' for flag '%s' in method '%s'",
parameter.getType().getCanonicalName(), flag.value(), method.getName())); parameter.getType().getCanonicalName(), flag.value(), method.getName()
));
} }
@SuppressWarnings("ALL") @SuppressWarnings("ALL") final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(
final CommandArgument.Builder argumentBuilder = CommandArgument.ofType(parameter.getType(), flag.value()); parameter.getType(),
@SuppressWarnings("ALL") flag.value()
final CommandArgument argument = argumentBuilder.asRequired() );
@SuppressWarnings("ALL") final CommandArgument argument = argumentBuilder.asRequired()
.manager(this.commandManager) .manager(this.commandManager)
.withParser(parser) .withParser(parser)
.build(); .build();

View file

@ -36,4 +36,5 @@ import java.lang.annotation.Target;
@Target(ElementType.METHOD) @Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Hidden { public @interface Hidden {
} }

View file

@ -35,8 +35,10 @@ class MetaFactory implements Function<@NonNull Annotation @NonNull [], @NonNull
private final AnnotationParser<?> annotationParser; private final AnnotationParser<?> annotationParser;
private final Function<ParserParameters, CommandMeta> metaMapper; private final Function<ParserParameters, CommandMeta> metaMapper;
MetaFactory(final @NonNull AnnotationParser<?> annotationParser, MetaFactory(
final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper) { final @NonNull AnnotationParser<?> annotationParser,
final @NonNull Function<@NonNull ParserParameters, @NonNull CommandMeta> metaMapper
) {
this.annotationParser = annotationParser; this.annotationParser = annotationParser;
this.metaMapper = metaMapper; this.metaMapper = metaMapper;
} }

View file

@ -43,10 +43,12 @@ class MethodCommandExecutionHandler<C> implements CommandExecutionHandler<C> {
private final MethodHandle methodHandle; private final MethodHandle methodHandle;
private final Map<String, CommandArgument<C, ?>> commandArguments; private final Map<String, CommandArgument<C, ?>> commandArguments;
MethodCommandExecutionHandler(final @NonNull Object instance, MethodCommandExecutionHandler(
final @NonNull Object instance,
final @NonNull Map<@NonNull String, final @NonNull Map<@NonNull String,
@NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments, @NonNull CommandArgument<@NonNull C, @NonNull ?>> commandArguments,
@NonNull final Method method) throws Exception { @NonNull final Method method
) throws Exception {
this.commandArguments = commandArguments; this.commandArguments = commandArguments;
method.setAccessible(true); method.setAccessible(true);
this.methodHandle = MethodHandles.lookup().unreflect(method).bindTo(instance); this.methodHandle = MethodHandles.lookup().unreflect(method).bindTo(instance);

View file

@ -33,9 +33,11 @@ final class SyntaxFragment {
private final List<String> minor; private final List<String> minor;
private final ArgumentMode argumentMode; private final ArgumentMode argumentMode;
SyntaxFragment(final @NonNull String major, SyntaxFragment(
final @NonNull String major,
final @NonNull List<@NonNull String> minor, final @NonNull List<@NonNull String> minor,
final @NonNull ArgumentMode argumentMode) { final @NonNull ArgumentMode argumentMode
) {
this.major = major; this.major = major;
this.minor = minor; this.minor = minor;
this.argumentMode = argumentMode; this.argumentMode = argumentMode;

View file

@ -64,17 +64,20 @@ class AnnotationParserTest {
@ProxiedBy("proxycommand") @ProxiedBy("proxycommand")
@CommandMethod("test|t literal <int> [string]") @CommandMethod("test|t literal <int> [string]")
public void testCommand(final TestCommandSender sender, public void testCommand(
final TestCommandSender sender,
@Argument("int") @Range(max = "100") final int argument, @Argument("int") @Range(max = "100") final int argument,
@Argument(value = "string", defaultValue = "potato", parserName = "potato") @Argument(value = "string", defaultValue = "potato", parserName = "potato") final String string
final String string) { ) {
System.out.printf("Received int: %d and string '%s'\n", argument, string); System.out.printf("Received int: %d and string '%s'\n", argument, string);
} }
@CommandMethod("flagcommand") @CommandMethod("flagcommand")
public void testFlags(final TestCommandSender sender, public void testFlags(
final TestCommandSender sender,
@Flag(value = "print", aliases = "p") boolean print, @Flag(value = "print", aliases = "p") boolean print,
@Flag(value = "word", aliases = "w") String word) { @Flag(value = "word", aliases = "w") String word
) {
if (print) { if (print) {
System.out.println(word); System.out.println(word);
} }

View file

@ -40,8 +40,10 @@ public class TestCommandManager extends CommandManager<TestCommandSender> {
} }
@Override @Override
public final boolean hasPermission(final TestCommandSender sender, public final boolean hasPermission(
final String permission) { final TestCommandSender sender,
final String permission
) {
return !permission.equalsIgnoreCase("no"); return !permission.equalsIgnoreCase("no");
} }

View file

@ -73,11 +73,13 @@ public class Command<C> {
* @param commandPermission Command permission * @param commandPermission Command permission
* @param commandMeta Command meta instance * @param commandMeta Command meta instance
*/ */
public Command(final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments, public Command(
final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments,
final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler,
final @Nullable Class<? extends C> senderType, final @Nullable Class<? extends C> senderType,
final @NonNull CommandPermission commandPermission, final @NonNull CommandPermission commandPermission,
final @NonNull CommandMeta commandMeta) { final @NonNull CommandMeta commandMeta
) {
this.arguments = Objects.requireNonNull(commandArguments, "Command arguments may not be null"); this.arguments = Objects.requireNonNull(commandArguments, "Command arguments may not be null");
if (this.arguments.size() == 0) { if (this.arguments.size() == 0) {
throw new IllegalArgumentException("At least one command argument is required"); throw new IllegalArgumentException("At least one command argument is required");
@ -90,8 +92,10 @@ public class Command<C> {
} }
if (foundOptional && argument.isRequired()) { if (foundOptional && argument.isRequired()) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
String.format("Command argument '%s' cannot be placed after an optional argument", String.format(
argument.getName())); "Command argument '%s' cannot be placed after an optional argument",
argument.getName()
));
} else if (!argument.isRequired()) { } else if (!argument.isRequired()) {
foundOptional = true; foundOptional = true;
} }
@ -110,10 +114,12 @@ public class Command<C> {
* @param senderType Required sender type. May be {@code null} * @param senderType Required sender type. May be {@code null}
* @param commandMeta Command meta instance * @param commandMeta Command meta instance
*/ */
public Command(final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments, public Command(
final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments,
final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler,
final @Nullable Class<? extends C> senderType, final @Nullable Class<? extends C> senderType,
final @NonNull CommandMeta commandMeta) { final @NonNull CommandMeta commandMeta
) {
this(commandArguments, commandExecutionHandler, senderType, Permission.empty(), commandMeta); this(commandArguments, commandExecutionHandler, senderType, Permission.empty(), commandMeta);
} }
@ -125,10 +131,12 @@ public class Command<C> {
* @param commandPermission Command permission * @param commandPermission Command permission
* @param commandMeta Command meta instance * @param commandMeta Command meta instance
*/ */
public Command(final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments, public Command(
final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments,
final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler,
final @NonNull CommandPermission commandPermission, final @NonNull CommandPermission commandPermission,
final @NonNull CommandMeta commandMeta) { final @NonNull CommandMeta commandMeta
) {
this(commandArguments, commandExecutionHandler, null, commandPermission, commandMeta); this(commandArguments, commandExecutionHandler, null, commandPermission, commandMeta);
} }
@ -143,19 +151,23 @@ public class Command<C> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Command builder * @return Command builder
*/ */
public static <C> @NonNull Builder<C> newBuilder(final @NonNull String commandName, public static <C> @NonNull Builder<C> newBuilder(
final @NonNull String commandName,
final @NonNull CommandMeta commandMeta, final @NonNull CommandMeta commandMeta,
final @NonNull Description description, final @NonNull Description description,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
final Map<@NonNull CommandArgument<C, ?>, @NonNull Description> map = new LinkedHashMap<>(); final Map<@NonNull CommandArgument<C, ?>, @NonNull Description> map = new LinkedHashMap<>();
map.put(StaticArgument.of(commandName, aliases), description); map.put(StaticArgument.of(commandName, aliases), description);
return new Builder<>(null, return new Builder<>(
null,
commandMeta, commandMeta,
null, null,
map, map,
new CommandExecutionHandler.NullCommandExecutionHandler<>(), new CommandExecutionHandler.NullCommandExecutionHandler<>(),
Permission.empty(), Permission.empty(),
Collections.emptyList()); Collections.emptyList()
);
} }
/** /**
@ -168,18 +180,22 @@ public class Command<C> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Command builder * @return Command builder
*/ */
public static <C> @NonNull Builder<C> newBuilder(final @NonNull String commandName, public static <C> @NonNull Builder<C> newBuilder(
final @NonNull String commandName,
final @NonNull CommandMeta commandMeta, final @NonNull CommandMeta commandMeta,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
final Map<CommandArgument<C, ?>, Description> map = new LinkedHashMap<>(); final Map<CommandArgument<C, ?>, Description> map = new LinkedHashMap<>();
map.put(StaticArgument.of(commandName, aliases), Description.empty()); map.put(StaticArgument.of(commandName, aliases), Description.empty());
return new Builder<>(null, return new Builder<>(
null,
commandMeta, commandMeta,
null, null,
map, map,
new CommandExecutionHandler.NullCommandExecutionHandler<>(), new CommandExecutionHandler.NullCommandExecutionHandler<>(),
Permission.empty(), Permission.empty(),
Collections.emptyList()); Collections.emptyList()
);
} }
/** /**
@ -273,13 +289,15 @@ public class Command<C> {
private final CommandManager<C> commandManager; private final CommandManager<C> commandManager;
private final Collection<CommandFlag<?>> flags; private final Collection<CommandFlag<?>> flags;
private Builder(final @Nullable CommandManager<C> commandManager, private Builder(
final @Nullable CommandManager<C> commandManager,
final @NonNull CommandMeta commandMeta, final @NonNull CommandMeta commandMeta,
final @Nullable Class<? extends C> senderType, final @Nullable Class<? extends C> senderType,
final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments, final @NonNull Map<@NonNull CommandArgument<C, ?>, @NonNull Description> commandArguments,
final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler, final @NonNull CommandExecutionHandler<@NonNull C> commandExecutionHandler,
final @NonNull CommandPermission commandPermission, final @NonNull CommandPermission commandPermission,
final @NonNull Collection<CommandFlag<?>> flags) { final @NonNull Collection<CommandFlag<?>> flags
) {
this.commandManager = commandManager; this.commandManager = commandManager;
this.senderType = senderType; this.senderType = senderType;
this.commandArguments = Objects.requireNonNull(commandArguments, "Arguments may not be null"); this.commandArguments = Objects.requireNonNull(commandArguments, "Arguments may not be null");
@ -298,13 +316,15 @@ public class Command<C> {
*/ */
public @NonNull Builder<C> meta(final @NonNull String key, final @NonNull String value) { public @NonNull Builder<C> meta(final @NonNull String key, final @NonNull String value) {
final CommandMeta commandMeta = SimpleCommandMeta.builder().with(this.commandMeta).with(key, value).build(); final CommandMeta commandMeta = SimpleCommandMeta.builder().with(this.commandMeta).with(key, value).build();
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
commandMeta, commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -316,13 +336,15 @@ public class Command<C> {
* @return New builder instance using the provided command manager * @return New builder instance using the provided command manager
*/ */
public @NonNull Builder<C> manager(final @Nullable CommandManager<C> commandManager) { public @NonNull Builder<C> manager(final @Nullable CommandManager<C> commandManager) {
return new Builder<>(commandManager, return new Builder<>(
commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -332,8 +354,10 @@ public class Command<C> {
* @param aliases Argument aliases * @param aliases Argument aliases
* @return New builder instance with the modified command chain * @return New builder instance with the modified command chain
*/ */
public @NonNull Builder<C> literal(final @NonNull String main, public @NonNull Builder<C> literal(
final @NonNull String... aliases) { final @NonNull String main,
final @NonNull String... aliases
) {
return this.argument(StaticArgument.of(main, aliases)); return this.argument(StaticArgument.of(main, aliases));
} }
@ -345,9 +369,11 @@ public class Command<C> {
* @param aliases Argument aliases * @param aliases Argument aliases
* @return New builder instance with the modified command chain * @return New builder instance with the modified command chain
*/ */
public @NonNull Builder<C> literal(final @NonNull String main, public @NonNull Builder<C> literal(
final @NonNull String main,
final @NonNull Description description, final @NonNull Description description,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
return this.argument(StaticArgument.of(main, aliases), description); return this.argument(StaticArgument.of(main, aliases), description);
} }
@ -382,8 +408,10 @@ public class Command<C> {
* @param <T> Argument type * @param <T> Argument type
* @return New builder instance with the command argument inserted into the argument list * @return New builder instance with the command argument inserted into the argument list
*/ */
public <T> @NonNull Builder<C> argument(final @NonNull CommandArgument<C, T> argument, public <T> @NonNull Builder<C> argument(
final @NonNull Description description) { final @NonNull CommandArgument<C, T> argument,
final @NonNull Description description
) {
if (argument.isArgumentRegistered()) { if (argument.isArgumentRegistered()) {
throw new IllegalArgumentException("The provided argument has already been associated with a command." throw new IllegalArgumentException("The provided argument has already been associated with a command."
+ " Use CommandArgument#copy to create a copy of the argument."); + " Use CommandArgument#copy to create a copy of the argument.");
@ -391,13 +419,15 @@ public class Command<C> {
argument.setArgumentRegistered(); argument.setArgumentRegistered();
final Map<CommandArgument<C, ?>, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments); final Map<CommandArgument<C, ?>, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments);
commandArgumentMap.put(argument, description); commandArgumentMap.put(argument, description);
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
commandArgumentMap, commandArgumentMap,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -409,17 +439,21 @@ public class Command<C> {
* @param <T> Argument type * @param <T> Argument type
* @return New builder instance with the command argument inserted into the argument list * @return New builder instance with the command argument inserted into the argument list
*/ */
public <T> @NonNull Builder<C> argument(final CommandArgument.@NonNull Builder<C, T> builder, public <T> @NonNull Builder<C> argument(
final @NonNull Description description) { final CommandArgument.@NonNull Builder<C, T> builder,
final @NonNull Description description
) {
final Map<CommandArgument<C, ?>, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments); final Map<CommandArgument<C, ?>, Description> commandArgumentMap = new LinkedHashMap<>(this.commandArguments);
commandArgumentMap.put(builder.build(), description); commandArgumentMap.put(builder.build(), description);
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
commandArgumentMap, commandArgumentMap,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -431,9 +465,11 @@ public class Command<C> {
* @param <T> Argument type * @param <T> Argument type
* @return New builder instance with the command argument inserted into the argument list * @return New builder instance with the command argument inserted into the argument list
*/ */
public <T> @NonNull Builder<C> argument(final @NonNull Class<T> clazz, public <T> @NonNull Builder<C> argument(
final @NonNull Class<T> clazz,
final @NonNull String name, final @NonNull String name,
final @NonNull Consumer<CommandArgument.Builder<C, T>> builderConsumer) { final @NonNull Consumer<CommandArgument.Builder<C, T>> builderConsumer
) {
final CommandArgument.Builder<C, T> builder = CommandArgument.ofType(clazz, name); final CommandArgument.Builder<C, T> builder = CommandArgument.ofType(clazz, name);
if (this.commandManager != null) { if (this.commandManager != null) {
builder.manager(this.commandManager); builder.manager(this.commandManager);
@ -461,10 +497,12 @@ public class Command<C> {
* @param <V> Second type * @param <V> Second type
* @return Builder instance with the argument inserted * @return Builder instance with the argument inserted
*/ */
public <U, V> @NonNull Builder<C> argumentPair(final @NonNull String name, public <U, V> @NonNull Builder<C> argumentPair(
final @NonNull String name,
final @NonNull Pair<@NonNull String, @NonNull String> names, final @NonNull Pair<@NonNull String, @NonNull String> names,
final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> parserPair, final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> parserPair,
final @NonNull Description description) { final @NonNull Description description
) {
if (this.commandManager == null) { if (this.commandManager == null) {
throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); throw new IllegalStateException("This cannot be called from a command that has no command manager attached");
} }
@ -491,18 +529,21 @@ public class Command<C> {
* @param <O> Output type * @param <O> Output type
* @return Builder instance with the argument inserted * @return Builder instance with the argument inserted
*/ */
public <U, V, O> @NonNull Builder<C> argumentPair(final @NonNull String name, public <U, V, O> @NonNull Builder<C> argumentPair(
final @NonNull String name,
final @NonNull TypeToken<O> outputType, final @NonNull TypeToken<O> outputType,
final @NonNull Pair<String, String> names, final @NonNull Pair<String, String> names,
final @NonNull Pair<Class<U>, Class<V>> parserPair, final @NonNull Pair<Class<U>, Class<V>> parserPair,
final @NonNull BiFunction<C, Pair<U, V>, O> mapper, final @NonNull BiFunction<C, Pair<U, V>, O> mapper,
final @NonNull Description description) { final @NonNull Description description
) {
if (this.commandManager == null) { if (this.commandManager == null) {
throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); throw new IllegalStateException("This cannot be called from a command that has no command manager attached");
} }
return this.argument( return this.argument(
ArgumentPair.of(this.commandManager, name, names, parserPair).withMapper(outputType, mapper), ArgumentPair.of(this.commandManager, name, names, parserPair).withMapper(outputType, mapper),
description); description
);
} }
/** /**
@ -523,10 +564,12 @@ public class Command<C> {
* @param <W> Third type * @param <W> Third type
* @return Builder instance with the argument inserted * @return Builder instance with the argument inserted
*/ */
public <U, V, W> @NonNull Builder<C> argumentTriplet(final @NonNull String name, public <U, V, W> @NonNull Builder<C> argumentTriplet(
final @NonNull String name,
final @NonNull Triplet<String, String, String> names, final @NonNull Triplet<String, String, String> names,
final @NonNull Triplet<Class<U>, Class<V>, Class<W>> parserTriplet, final @NonNull Triplet<Class<U>, Class<V>, Class<W>> parserTriplet,
final @NonNull Description description) { final @NonNull Description description
) {
if (this.commandManager == null) { if (this.commandManager == null) {
throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); throw new IllegalStateException("This cannot be called from a command that has no command manager attached");
} }
@ -554,19 +597,22 @@ public class Command<C> {
* @param <O> Output type * @param <O> Output type
* @return Builder instance with the argument inserted * @return Builder instance with the argument inserted
*/ */
public <U, V, W, O> @NonNull Builder<C> argumentTriplet(final @NonNull String name, public <U, V, W, O> @NonNull Builder<C> argumentTriplet(
final @NonNull String name,
final @NonNull TypeToken<O> outputType, final @NonNull TypeToken<O> outputType,
final @NonNull Triplet<String, String, String> names, final @NonNull Triplet<String, String, String> names,
final @NonNull Triplet<Class<U>, Class<V>, final @NonNull Triplet<Class<U>, Class<V>,
Class<W>> parserTriplet, Class<W>> parserTriplet,
final @NonNull BiFunction<C, Triplet<U, V, W>, O> mapper, final @NonNull BiFunction<C, Triplet<U, V, W>, O> mapper,
final @NonNull Description description) { final @NonNull Description description
) {
if (this.commandManager == null) { if (this.commandManager == null) {
throw new IllegalStateException("This cannot be called from a command that has no command manager attached"); throw new IllegalStateException("This cannot be called from a command that has no command manager attached");
} }
return this.argument( return this.argument(
ArgumentTriplet.of(this.commandManager, name, names, parserTriplet).withMapper(outputType, mapper), ArgumentTriplet.of(this.commandManager, name, names, parserTriplet).withMapper(outputType, mapper),
description); description
);
} }
// End of compound helper methods // End of compound helper methods
@ -578,13 +624,15 @@ public class Command<C> {
* @return New builder instance using the command execution handler * @return New builder instance using the command execution handler
*/ */
public @NonNull Builder<C> handler(final @NonNull CommandExecutionHandler<C> commandExecutionHandler) { public @NonNull Builder<C> handler(final @NonNull CommandExecutionHandler<C> commandExecutionHandler) {
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
commandExecutionHandler, commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -593,14 +641,16 @@ public class Command<C> {
* @param senderType Required sender type * @param senderType Required sender type
* @return New builder instance using the command execution handler * @return New builder instance using the command execution handler
*/ */
public @NonNull Builder<C> withSenderType(final @NonNull Class<? extends C> senderType) { public @NonNull Builder<C> senderType(final @NonNull Class<? extends C> senderType) {
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
senderType, senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
this.flags); this.flags
);
} }
/** /**
@ -610,13 +660,15 @@ public class Command<C> {
* @return New builder instance using the command permission * @return New builder instance using the command permission
*/ */
public @NonNull Builder<C> withPermission(final @NonNull CommandPermission permission) { public @NonNull Builder<C> withPermission(final @NonNull CommandPermission permission) {
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
permission, permission,
this.flags); this.flags
);
} }
/** /**
@ -626,13 +678,15 @@ public class Command<C> {
* @return New builder instance using the command permission * @return New builder instance using the command permission
*/ */
public @NonNull Builder<C> withPermission(final @NonNull String permission) { public @NonNull Builder<C> withPermission(final @NonNull String permission) {
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
Permission.of(permission), Permission.of(permission),
this.flags); this.flags
);
} }
/** /**
@ -681,13 +735,15 @@ public class Command<C> {
public @NonNull <T> Builder<C> flag(final @NonNull CommandFlag<T> flag) { public @NonNull <T> Builder<C> flag(final @NonNull CommandFlag<T> flag) {
final List<CommandFlag<?>> flags = new ArrayList<>(this.flags); final List<CommandFlag<?>> flags = new ArrayList<>(this.flags);
flags.add(flag); flags.add(flag);
return new Builder<>(this.commandManager, return new Builder<>(
this.commandManager,
this.commandMeta, this.commandMeta,
this.senderType, this.senderType,
this.commandArguments, this.commandArguments,
this.commandExecutionHandler, this.commandExecutionHandler,
this.commandPermission, this.commandPermission,
Collections.unmodifiableList(flags)); Collections.unmodifiableList(flags)
);
} }
/** /**
@ -713,11 +769,13 @@ public class Command<C> {
final FlagArgument<C> flagArgument = new FlagArgument<>(this.flags); final FlagArgument<C> flagArgument = new FlagArgument<>(this.flags);
commandArguments.put(flagArgument, Description.of("Command flags")); commandArguments.put(flagArgument, Description.of("Command flags"));
} }
return new Command<>(Collections.unmodifiableMap(commandArguments), return new Command<>(
Collections.unmodifiableMap(commandArguments),
this.commandExecutionHandler, this.commandExecutionHandler,
this.senderType, this.senderType,
this.commandPermission, this.commandPermission,
this.commandMeta); this.commandMeta
);
} }
} }

View file

@ -56,10 +56,12 @@ public final class CommandHelpHandler<C> {
for (final Command<C> command : this.commandManager.getCommands()) { for (final Command<C> command : this.commandManager.getCommands()) {
final List<CommandArgument<C, ?>> arguments = command.getArguments(); final List<CommandArgument<C, ?>> arguments = command.getArguments();
final String description = command.getCommandMeta().getOrDefault("description", ""); final String description = command.getCommandMeta().getOrDefault("description", "");
syntaxHints.add(new VerboseHelpEntry<>(command, syntaxHints.add(new VerboseHelpEntry<>(
command,
this.commandManager.getCommandSyntaxFormatter() this.commandManager.getCommandSyntaxFormatter()
.apply(arguments, null), .apply(arguments, null),
description)); description
));
} }
syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString)); syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString));
return syntaxHints; return syntaxHints;
@ -76,57 +78,17 @@ public final class CommandHelpHandler<C> {
final List<String> chains = new ArrayList<>(); final List<String> chains = new ArrayList<>();
this.commandManager.getCommandTree().getRootNodes().forEach(node -> this.commandManager.getCommandTree().getRootNodes().forEach(node ->
chains.add(Objects.requireNonNull(node.getValue()) chains.add(Objects.requireNonNull(node.getValue())
.getName() + this.commandManager.getCommandSyntaxFormatter() .getName() + this.commandManager
.apply(Collections .getCommandSyntaxFormatter()
.apply(
Collections
.emptyList(), .emptyList(),
node))); node
)));
chains.sort(String::compareTo); chains.sort(String::compareTo);
return chains; return chains;
} }
public static final class VerboseHelpEntry<C> {
private final Command<C> command;
private final String syntaxString;
private final String description;
private VerboseHelpEntry(final @NonNull Command<C> command,
final @NonNull String syntaxString,
final @NonNull String description) {
this.command = command;
this.syntaxString = syntaxString;
this.description = description;
}
/**
* Get the command
*
* @return Command
*/
public @NonNull Command<C> getCommand() {
return this.command;
}
/**
* Get the syntax string
*
* @return Syntax string
*/
public @NonNull String getSyntaxString() {
return this.syntaxString;
}
/**
* Get the command description
*
* @return Command description
*/
public @NonNull String getDescription() {
return this.description;
}
}
/** /**
* Query for help * Query for help
* *
@ -144,12 +106,15 @@ public final class CommandHelpHandler<C> {
* @param query Query string * @param query Query string
* @return Help topic, will return an empty {@link IndexHelpTopic} if no results were found * @return Help topic, will return an empty {@link IndexHelpTopic} if no results were found
*/ */
public @NonNull HelpTopic<C> queryHelp(final @Nullable C recipient, public @NonNull HelpTopic<C> queryHelp(
final @NonNull String query) { final @Nullable C recipient,
final @NonNull String query
) {
final List<VerboseHelpEntry<C>> commands = this.getAllCommands(); final List<VerboseHelpEntry<C>> commands = this.getAllCommands();
commands.removeIf(command -> recipient != null && !this.commandManager.hasPermission(recipient, commands.removeIf(command -> recipient != null && !this.commandManager.hasPermission(
command.getCommand() recipient,
.getCommandPermission())); command.getCommand().getCommandPermission()
));
if (query.replace(" ", "").isEmpty()) { if (query.replace(" ", "").isEmpty()) {
return new IndexHelpTopic<>(commands); return new IndexHelpTopic<>(commands);
} }
@ -199,10 +164,12 @@ public final class CommandHelpHandler<C> {
for (final Command<C> command : availableCommands) { for (final Command<C> command : availableCommands) {
final List<CommandArgument<C, ?>> arguments = command.getArguments(); final List<CommandArgument<C, ?>> arguments = command.getArguments();
final String description = command.getCommandMeta().getOrDefault("description", ""); final String description = command.getCommandMeta().getOrDefault("description", "");
syntaxHints.add(new VerboseHelpEntry<>(command, syntaxHints.add(new VerboseHelpEntry<>(
command,
this.commandManager.getCommandSyntaxFormatter() this.commandManager.getCommandSyntaxFormatter()
.apply(arguments, null), .apply(arguments, null),
description)); description
));
} }
syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString)); syntaxHints.sort(Comparator.comparing(VerboseHelpEntry::getSyntaxString));
syntaxHints.removeIf(command -> recipient != null syntaxHints.removeIf(command -> recipient != null
@ -219,7 +186,8 @@ public final class CommandHelpHandler<C> {
CommandTree.Node<CommandArgument<C, ?>> head = node; CommandTree.Node<CommandArgument<C, ?>> head = node;
int index = 0; int index = 0;
outer: while (head != null) { outer:
while (head != null) {
++index; ++index;
traversedNodes.add(head.getValue()); traversedNodes.add(head.getValue());
@ -239,8 +207,8 @@ public final class CommandHelpHandler<C> {
if (index < queryFragments.length) { if (index < queryFragments.length) {
/* We might still be able to match an argument */ /* We might still be able to match an argument */
for (final CommandTree.Node<CommandArgument<C, ?>> child : head.getChildren()) { for (final CommandTree.Node<CommandArgument<C, ?>> child : head.getChildren()) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final StaticArgument<C> childArgument = (StaticArgument<C>) child
final StaticArgument<C> childArgument = (StaticArgument<C>) child.getValue(); .getValue();
if (childArgument == null) { if (childArgument == null) {
continue; continue;
} }
@ -260,8 +228,10 @@ public final class CommandHelpHandler<C> {
if (recipient == null if (recipient == null
|| child.getValue() == null || child.getValue() == null
|| child.getValue().getOwningCommand() == null || child.getValue().getOwningCommand() == null
|| this.commandManager.hasPermission(recipient, || this.commandManager.hasPermission(
child.getValue().getOwningCommand().getCommandPermission())) { recipient,
child.getValue().getOwningCommand().getCommandPermission()
)) {
traversedNodesSub.add(child.getValue()); traversedNodesSub.add(child.getValue());
childSuggestions.add(this.commandManager.getCommandSyntaxFormatter().apply(traversedNodesSub, child)); childSuggestions.add(this.commandManager.getCommandSyntaxFormatter().apply(traversedNodesSub, child));
} }
@ -273,7 +243,6 @@ public final class CommandHelpHandler<C> {
return new IndexHelpTopic<>(Collections.emptyList()); return new IndexHelpTopic<>(Collections.emptyList());
} }
/** /**
* Something that can be returned as the result of a help query * Something that can be returned as the result of a help query
* <p> * <p>
@ -287,8 +256,53 @@ public final class CommandHelpHandler<C> {
* @param <C> Command sender type * @param <C> Command sender type
*/ */
public interface HelpTopic<C> { public interface HelpTopic<C> {
} }
public static final class VerboseHelpEntry<C> {
private final Command<C> command;
private final String syntaxString;
private final String description;
private VerboseHelpEntry(
final @NonNull Command<C> command,
final @NonNull String syntaxString,
final @NonNull String description
) {
this.command = command;
this.syntaxString = syntaxString;
this.description = description;
}
/**
* Get the command
*
* @return Command
*/
public @NonNull Command<C> getCommand() {
return this.command;
}
/**
* Get the syntax string
*
* @return Syntax string
*/
public @NonNull String getSyntaxString() {
return this.syntaxString;
}
/**
* Get the command description
*
* @return Command description
*/
public @NonNull String getDescription() {
return this.description;
}
}
/** /**
* Index of available commands * Index of available commands
@ -371,8 +385,10 @@ public final class CommandHelpHandler<C> {
private final String longestPath; private final String longestPath;
private final List<String> childSuggestions; private final List<String> childSuggestions;
private MultiHelpTopic(final @NonNull String longestPath, private MultiHelpTopic(
final @NonNull List<@NonNull String> childSuggestions) { final @NonNull String longestPath,
final @NonNull List<@NonNull String> childSuggestions
) {
this.longestPath = longestPath; this.longestPath = longestPath;
this.childSuggestions = childSuggestions; this.childSuggestions = childSuggestions;
} }

View file

@ -45,13 +45,13 @@ import cloud.commandframework.execution.preprocessor.AcceptingCommandPreprocesso
import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext; import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext;
import cloud.commandframework.execution.preprocessor.CommandPreprocessor; import cloud.commandframework.execution.preprocessor.CommandPreprocessor;
import cloud.commandframework.internal.CommandRegistrationHandler; import cloud.commandframework.internal.CommandRegistrationHandler;
import io.leangen.geantyref.TypeToken;
import cloud.commandframework.meta.CommandMeta; import cloud.commandframework.meta.CommandMeta;
import cloud.commandframework.permission.CommandPermission; import cloud.commandframework.permission.CommandPermission;
import cloud.commandframework.permission.OrPermission; import cloud.commandframework.permission.OrPermission;
import cloud.commandframework.permission.Permission; import cloud.commandframework.permission.Permission;
import cloud.commandframework.services.ServicePipeline; import cloud.commandframework.services.ServicePipeline;
import cloud.commandframework.services.State; import cloud.commandframework.services.State;
import io.leangen.geantyref.TypeToken;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -76,7 +76,8 @@ import java.util.function.Function;
public abstract class CommandManager<C> { public abstract class CommandManager<C> {
private final Map<Class<? extends Exception>, BiConsumer<C, ? extends Exception>> exceptionHandlers = new HashMap<>(); private final Map<Class<? extends Exception>, BiConsumer<C, ? extends Exception>> exceptionHandlers = new HashMap<>();
private final EnumSet<ManagerSettings> managerSettings = EnumSet.of(ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS); private final EnumSet<ManagerSettings> managerSettings = EnumSet.of(
ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS);
private final CommandContextFactory<C> commandContextFactory = new StandardCommandContextFactory<>(); private final CommandContextFactory<C> commandContextFactory = new StandardCommandContextFactory<>();
private final ServicePipeline servicePipeline = ServicePipeline.builder().build(); private final ServicePipeline servicePipeline = ServicePipeline.builder().build();
@ -97,7 +98,8 @@ public abstract class CommandManager<C> {
*/ */
public CommandManager( public CommandManager(
final @NonNull Function<@NonNull CommandTree<C>, @NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator, final @NonNull Function<@NonNull CommandTree<C>, @NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator,
final @NonNull CommandRegistrationHandler commandRegistrationHandler) { final @NonNull CommandRegistrationHandler commandRegistrationHandler
) {
this.commandTree = CommandTree.newTree(this); this.commandTree = CommandTree.newTree(this);
this.commandExecutionCoordinator = commandExecutionCoordinator.apply(commandTree); this.commandExecutionCoordinator = commandExecutionCoordinator.apply(commandTree);
this.commandRegistrationHandler = commandRegistrationHandler; this.commandRegistrationHandler = commandRegistrationHandler;
@ -132,8 +134,10 @@ public abstract class CommandManager<C> {
* @param input Input provided by the sender * @param input Input provided by the sender
* @return Command result * @return Command result
*/ */
public @NonNull CompletableFuture<CommandResult<C>> executeCommand(final @NonNull C commandSender, public @NonNull CompletableFuture<CommandResult<C>> executeCommand(
final @NonNull String input) { final @NonNull C commandSender,
final @NonNull String input
) {
final CommandContext<C> context = this.commandContextFactory.create(false, commandSender); final CommandContext<C> context = this.commandContextFactory.create(false, commandSender);
final LinkedList<String> inputQueue = tokenize(input); final LinkedList<String> inputQueue = tokenize(input);
try { try {
@ -157,14 +161,18 @@ public abstract class CommandManager<C> {
* @param input Input provided by the sender * @param input Input provided by the sender
* @return List of suggestions * @return List of suggestions
*/ */
public @NonNull List<@NonNull String> suggest(final @NonNull C commandSender, public @NonNull List<@NonNull String> suggest(
final @NonNull String input) { final @NonNull C commandSender,
final @NonNull String input
) {
final CommandContext<C> context = this.commandContextFactory.create(true, commandSender); final CommandContext<C> context = this.commandContextFactory.create(true, commandSender);
final LinkedList<String> inputQueue = tokenize(input); final LinkedList<String> inputQueue = tokenize(input);
if (this.preprocessContext(context, inputQueue) == State.ACCEPTED) { if (this.preprocessContext(context, inputQueue) == State.ACCEPTED) {
return this.commandSuggestionProcessor.apply(new CommandPreprocessingContext<>(context, inputQueue), return this.commandSuggestionProcessor.apply(
new CommandPreprocessingContext<>(context, inputQueue),
this.commandTree.getSuggestions( this.commandTree.getSuggestions(
context, inputQueue)); context, inputQueue)
);
} else { } else {
return Collections.emptyList(); return Collections.emptyList();
} }
@ -231,8 +239,10 @@ public abstract class CommandManager<C> {
* @param permission Permission node * @param permission Permission node
* @return {@code true} if the sender has the permission, else {@code false} * @return {@code true} if the sender has the permission, else {@code false}
*/ */
public boolean hasPermission(final @NonNull C sender, public boolean hasPermission(
final @NonNull CommandPermission permission) { final @NonNull C sender,
final @NonNull CommandPermission permission
) {
if (permission.toString().isEmpty()) { if (permission.toString().isEmpty()) {
return true; return true;
} }
@ -269,10 +279,12 @@ public abstract class CommandManager<C> {
* @param meta Command meta * @param meta Command meta
* @return Builder instance * @return Builder instance
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Collection<String> aliases, final @NonNull Collection<String> aliases,
final @NonNull Description description, final @NonNull Description description,
final @NonNull CommandMeta meta) { final @NonNull CommandMeta meta
) {
return Command.newBuilder(name, meta, description, aliases.toArray(new String[0])); return Command.newBuilder(name, meta, description, aliases.toArray(new String[0]));
} }
@ -284,9 +296,11 @@ public abstract class CommandManager<C> {
* @param meta Command meta * @param meta Command meta
* @return Builder instance * @return Builder instance
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Collection<String> aliases, final @NonNull Collection<String> aliases,
final @NonNull CommandMeta meta) { final @NonNull CommandMeta meta
) {
return Command.newBuilder(name, meta, Description.empty(), aliases.toArray(new String[0])); return Command.newBuilder(name, meta, Description.empty(), aliases.toArray(new String[0]));
} }
@ -299,10 +313,12 @@ public abstract class CommandManager<C> {
* @param aliases Command aliases * @param aliases Command aliases
* @return Builder instance * @return Builder instance
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull CommandMeta meta, final @NonNull CommandMeta meta,
final @NonNull Description description, final @NonNull Description description,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
return Command.newBuilder(name, meta, description, aliases); return Command.newBuilder(name, meta, description, aliases);
} }
@ -314,9 +330,11 @@ public abstract class CommandManager<C> {
* @param aliases Command aliases * @param aliases Command aliases
* @return Builder instance * @return Builder instance
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull CommandMeta meta, final @NonNull CommandMeta meta,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
return Command.newBuilder(name, meta, Description.empty(), aliases); return Command.newBuilder(name, meta, Description.empty(), aliases);
} }
@ -330,9 +348,11 @@ public abstract class CommandManager<C> {
* @throws UnsupportedOperationException If the command manager does not support default command meta creation * @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation * @see #createDefaultCommandMeta() Default command meta creation
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Description description, final @NonNull Description description,
final @NonNull String... aliases) { final @NonNull String... aliases
) {
return Command.<C>newBuilder(name, this.createDefaultCommandMeta(), description, aliases).manager(this); return Command.<C>newBuilder(name, this.createDefaultCommandMeta(), description, aliases).manager(this);
} }
@ -345,8 +365,10 @@ public abstract class CommandManager<C> {
* @throws UnsupportedOperationException If the command manager does not support default command meta creation * @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation * @see #createDefaultCommandMeta() Default command meta creation
*/ */
public Command.@NonNull Builder<C> commandBuilder(final @NonNull String name, public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String... aliases) { final @NonNull String name,
final @NonNull String... aliases
) {
return Command.<C>newBuilder(name, this.createDefaultCommandMeta(), Description.empty(), aliases).manager(this); return Command.<C>newBuilder(name, this.createDefaultCommandMeta(), Description.empty(), aliases).manager(this);
} }
@ -358,8 +380,10 @@ public abstract class CommandManager<C> {
* @param <T> Generic argument name * @param <T> Generic argument name
* @return Argument builder * @return Argument builder
*/ */
public <T> CommandArgument.@NonNull Builder<C, T> argumentBuilder(final @NonNull Class<T> type, public <T> CommandArgument.@NonNull Builder<C, T> argumentBuilder(
final @NonNull String name) { final @NonNull Class<T> type,
final @NonNull String name
) {
return CommandArgument.<C, T>ofType(type, name).manager(this); return CommandArgument.<C, T>ofType(type, name).manager(this);
} }
@ -401,7 +425,8 @@ public abstract class CommandManager<C> {
public void registerCommandPreProcessor(final @NonNull CommandPreprocessor<C> processor) { public void registerCommandPreProcessor(final @NonNull CommandPreprocessor<C> processor) {
this.servicePipeline.registerServiceImplementation(new TypeToken<CommandPreprocessor<C>>() { this.servicePipeline.registerServiceImplementation(new TypeToken<CommandPreprocessor<C>>() {
}, processor, }, processor,
Collections.emptyList()); Collections.emptyList()
);
} }
/** /**
@ -414,7 +439,8 @@ public abstract class CommandManager<C> {
public void registerCommandPostProcessor(final @NonNull CommandPostprocessor<C> processor) { public void registerCommandPostProcessor(final @NonNull CommandPostprocessor<C> processor) {
this.servicePipeline.registerServiceImplementation(new TypeToken<CommandPostprocessor<C>>() { this.servicePipeline.registerServiceImplementation(new TypeToken<CommandPostprocessor<C>>() {
}, processor, }, processor,
Collections.emptyList()); Collections.emptyList()
);
} }
/** /**
@ -425,8 +451,10 @@ public abstract class CommandManager<C> {
* @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED} * @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED}
* @see #registerCommandPreProcessor(CommandPreprocessor) Register a command preprocessor * @see #registerCommandPreProcessor(CommandPreprocessor) Register a command preprocessor
*/ */
public State preprocessContext(final @NonNull CommandContext<C> context, public State preprocessContext(
final @NonNull LinkedList<@NonNull String> inputQueue) { final @NonNull CommandContext<C> context,
final @NonNull LinkedList<@NonNull String> inputQueue
) {
this.servicePipeline.pump(new CommandPreprocessingContext<>(context, inputQueue)) this.servicePipeline.pump(new CommandPreprocessingContext<>(context, inputQueue))
.through(new TypeToken<CommandPreprocessor<C>>() { .through(new TypeToken<CommandPreprocessor<C>>() {
}) })
@ -444,8 +472,10 @@ public abstract class CommandManager<C> {
* @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED} * @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED}
* @see #registerCommandPostProcessor(CommandPostprocessor) Register a command postprocessor * @see #registerCommandPostProcessor(CommandPostprocessor) Register a command postprocessor
*/ */
public State postprocessContext(final @NonNull CommandContext<C> context, public State postprocessContext(
final @NonNull Command<C> command) { final @NonNull CommandContext<C> context,
final @NonNull Command<C> command
) {
this.servicePipeline.pump(new CommandPostprocessingContext<>(context, command)) this.servicePipeline.pump(new CommandPostprocessingContext<>(context, command))
.through(new TypeToken<CommandPostprocessor<C>>() { .through(new TypeToken<CommandPostprocessor<C>>() {
}) })
@ -520,8 +550,10 @@ public abstract class CommandManager<C> {
* @param handler Exception handler * @param handler Exception handler
* @param <E> Exception type * @param <E> Exception type
*/ */
public final <E extends Exception> void registerExceptionHandler(final @NonNull Class<E> clazz, public final <E extends Exception> void registerExceptionHandler(
final @NonNull BiConsumer<@NonNull C, @NonNull E> handler) { final @NonNull Class<E> clazz,
final @NonNull BiConsumer<@NonNull C, @NonNull E> handler
) {
this.exceptionHandlers.put(clazz, handler); this.exceptionHandlers.put(clazz, handler);
} }
@ -536,10 +568,12 @@ public abstract class CommandManager<C> {
* handler stored for the exception type * handler stored for the exception type
* @param <E> Exception type * @param <E> Exception type
*/ */
public final <E extends Exception> void handleException(final @NonNull C sender, public final <E extends Exception> void handleException(
final @NonNull C sender,
final @NonNull Class<E> clazz, final @NonNull Class<E> clazz,
final @NonNull E exception, final @NonNull E exception,
final @NonNull BiConsumer<C, E> defaultHandler) { final @NonNull BiConsumer<C, E> defaultHandler
) {
Optional.ofNullable(this.getExceptionHandler(clazz)).orElse(defaultHandler).accept(sender, exception); Optional.ofNullable(this.getExceptionHandler(clazz)).orElse(defaultHandler).accept(sender, exception);
} }
@ -580,8 +614,10 @@ public abstract class CommandManager<C> {
* @param value Value * @param value Value
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void setSetting(final @NonNull ManagerSettings setting, public void setSetting(
final boolean value) { final @NonNull ManagerSettings setting,
final boolean value
) {
if (value) { if (value) {
this.managerSettings.add(setting); this.managerSettings.add(setting);
} else { } else {

View file

@ -112,45 +112,58 @@ public final class CommandTree<C> {
* @param args Input * @param args Input
* @return Parsed command, if one could be found * @return Parsed command, if one could be found
*/ */
public @NonNull Pair<@Nullable Command<C>, @Nullable Exception> parse(final @NonNull CommandContext<C> commandContext, public @NonNull Pair<@Nullable Command<C>, @Nullable Exception> parse(
final @NonNull Queue<@NonNull String> args) { final @NonNull CommandContext<C> commandContext,
final Pair<@Nullable Command<C>, @Nullable Exception> pair = this.parseCommand(new ArrayList<>(), final @NonNull Queue<@NonNull String> args
) {
final Pair<@Nullable Command<C>, @Nullable Exception> pair = this.parseCommand(
new ArrayList<>(),
commandContext, commandContext,
args, args,
this.internalTree); this.internalTree
);
if (pair.getFirst() != null) { if (pair.getFirst() != null) {
final Command<C> command = pair.getFirst(); final Command<C> command = pair.getFirst();
if (command.getSenderType().isPresent() && !command.getSenderType().get() if (command.getSenderType().isPresent() && !command.getSenderType().get()
.isAssignableFrom(commandContext.getSender().getClass())) { .isAssignableFrom(commandContext
return Pair.of(null, new InvalidCommandSenderException(commandContext.getSender(), .getSender()
.getClass())) {
return Pair.of(null, new InvalidCommandSenderException(
commandContext.getSender(),
command.getSenderType().get(), command.getSenderType().get(),
Collections.emptyList())); Collections.emptyList()
));
} }
} }
return pair; return pair;
} }
private @NonNull Pair<@Nullable Command<C>, @Nullable Exception> private @NonNull Pair<@Nullable Command<C>, @Nullable Exception> parseCommand(
parseCommand(final @NonNull List<@NonNull CommandArgument<C, ?>> parsedArguments, final @NonNull List<@NonNull CommandArgument<C, ?>> parsedArguments,
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> commandQueue, final @NonNull Queue<@NonNull String> commandQueue,
final @NonNull Node<@Nullable CommandArgument<C, ?>> root) { final @NonNull Node<@Nullable CommandArgument<C, ?>> root
) {
CommandPermission permission = this.isPermitted(commandContext.getSender(), root); CommandPermission permission = this.isPermitted(commandContext.getSender(), root);
if (permission != null) { if (permission != null) {
return Pair.of(null, new NoPermissionException(permission, return Pair.of(null, new NoPermissionException(
permission,
commandContext.getSender(), commandContext.getSender(),
this.getChain(root) this.getChain(root)
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
final Pair<@Nullable Command<C>, @Nullable Exception> parsedChild = this.attemptParseUnambiguousChild(parsedArguments, final Pair<@Nullable Command<C>, @Nullable Exception> parsedChild = this.attemptParseUnambiguousChild(
parsedArguments,
commandContext, commandContext,
root, root,
commandQueue); commandQueue
);
if (parsedChild.getFirst() != null || parsedChild.getSecond() != null) { if (parsedChild.getFirst() != null || parsedChild.getSecond() != null) {
return parsedChild; return parsedChild;
} }
@ -170,7 +183,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
} else { } else {
/* Too many arguments. We have a unique path, so we can send the entire context */ /* Too many arguments. We have a unique path, so we can send the entire context */
@ -181,7 +195,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
} else { } else {
final Iterator<Node<CommandArgument<C, ?>>> childIterator = root.getChildren().iterator(); final Iterator<Node<CommandArgument<C, ?>>> childIterator = root.getChildren().iterator();
@ -208,13 +223,16 @@ public final class CommandTree<C> {
return Pair.of(null, new NoSuchCommandException( return Pair.of(null, new NoSuchCommandException(
commandContext.getSender(), commandContext.getSender(),
getChain(root).stream().map(Node::getValue).collect(Collectors.toList()), getChain(root).stream().map(Node::getValue).collect(Collectors.toList()),
stringOrEmpty(commandQueue.peek()))); stringOrEmpty(commandQueue.peek())
));
} }
/* If we couldn't match a child, check if there's a command attached and execute it */ /* If we couldn't match a child, check if there's a command attached and execute it */
if (root.getValue() != null && root.getValue().getOwningCommand() != null && commandQueue.isEmpty()) { if (root.getValue() != null && root.getValue().getOwningCommand() != null && commandQueue.isEmpty()) {
final Command<C> command = root.getValue().getOwningCommand(); final Command<C> command = root.getValue().getOwningCommand();
if (!this.getCommandManager().hasPermission(commandContext.getSender(), if (!this.getCommandManager().hasPermission(
command.getCommandPermission())) { commandContext.getSender(),
command.getCommandPermission()
)) {
return Pair.of(null, new NoPermissionException( return Pair.of(null, new NoPermissionException(
command.getCommandPermission(), command.getCommandPermission(),
commandContext.getSender(), commandContext.getSender(),
@ -222,7 +240,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
return Pair.of(root.getValue().getOwningCommand(), null); return Pair.of(root.getValue().getOwningCommand(), null);
} }
@ -234,7 +253,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
} }
@ -242,7 +262,8 @@ public final class CommandTree<C> {
final @NonNull List<@NonNull CommandArgument<C, ?>> parsedArguments, final @NonNull List<@NonNull CommandArgument<C, ?>> parsedArguments,
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Node<@Nullable CommandArgument<C, ?>> root, final @NonNull Node<@Nullable CommandArgument<C, ?>> root,
final @NonNull Queue<String> commandQueue) { final @NonNull Queue<String> commandQueue
) {
CommandPermission permission; CommandPermission permission;
final List<Node<CommandArgument<C, ?>>> children = root.getChildren(); final List<Node<CommandArgument<C, ?>>> children = root.getChildren();
if (children.size() == 1 && !(children.get(0).getValue() instanceof StaticArgument)) { if (children.size() == 1 && !(children.get(0).getValue() instanceof StaticArgument)) {
@ -257,8 +278,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect( .collect(Collectors.toList())
Collectors.toList()))); ));
} }
if (child.getValue() != null) { if (child.getValue() != null) {
if (commandQueue.isEmpty()) { if (commandQueue.isEmpty()) {
@ -270,8 +291,10 @@ public final class CommandTree<C> {
/* The child is not a leaf, but may have an intermediary executor, attempt to use it */ /* The child is not a leaf, but may have an intermediary executor, attempt to use it */
if (root.getValue() != null && root.getValue().getOwningCommand() != null) { if (root.getValue() != null && root.getValue().getOwningCommand() != null) {
final Command<C> command = root.getValue().getOwningCommand(); final Command<C> command = root.getValue().getOwningCommand();
if (!this.getCommandManager().hasPermission(commandContext.getSender(), if (!this.getCommandManager().hasPermission(
command.getCommandPermission())) { commandContext.getSender(),
command.getCommandPermission()
)) {
return Pair.of(null, new NoPermissionException( return Pair.of(null, new NoPermissionException(
command.getCommandPermission(), command.getCommandPermission(),
commandContext.getSender(), commandContext.getSender(),
@ -279,7 +302,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
return Pair.of(command, null); return Pair.of(command, null);
} }
@ -294,14 +318,16 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect( .collect(Collectors.toList())
Collectors.toList()))); ));
} else { } else {
/* The child is not a leaf, but may have an intermediary executor, attempt to use it */ /* The child is not a leaf, but may have an intermediary executor, attempt to use it */
if (root.getValue() != null && root.getValue().getOwningCommand() != null) { if (root.getValue() != null && root.getValue().getOwningCommand() != null) {
final Command<C> command = root.getValue().getOwningCommand(); final Command<C> command = root.getValue().getOwningCommand();
if (!this.getCommandManager().hasPermission(commandContext.getSender(), if (!this.getCommandManager().hasPermission(
command.getCommandPermission())) { commandContext.getSender(),
command.getCommandPermission()
)) {
return Pair.of(null, new NoPermissionException( return Pair.of(null, new NoPermissionException(
command.getCommandPermission(), command.getCommandPermission(),
commandContext.getSender(), commandContext.getSender(),
@ -309,7 +335,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
return Pair.of(command, null); return Pair.of(command, null);
} }
@ -321,7 +348,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
} }
@ -346,8 +374,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect( .collect(Collectors.toList())
Collectors.toList()))); ));
} }
} else { } else {
parsedArguments.add(child.getValue()); parsedArguments.add(child.getValue());
@ -360,7 +388,8 @@ public final class CommandTree<C> {
.stream() .stream()
.filter(node -> node.getValue() != null) .filter(node -> node.getValue() != null)
.map(Node::getValue) .map(Node::getValue)
.collect(Collectors.toList()))); .collect(Collectors.toList())
));
} }
} }
} }
@ -374,14 +403,18 @@ public final class CommandTree<C> {
* @param commandQueue Input queue * @param commandQueue Input queue
* @return String suggestions. These should be filtered based on {@link String#startsWith(String)} * @return String suggestions. These should be filtered based on {@link String#startsWith(String)}
*/ */
public @NonNull List<@NonNull String> getSuggestions(final @NonNull CommandContext<C> context, public @NonNull List<@NonNull String> getSuggestions(
final @NonNull Queue<@NonNull String> commandQueue) { final @NonNull CommandContext<C> context,
final @NonNull Queue<@NonNull String> commandQueue
) {
return getSuggestions(context, commandQueue, this.internalTree); return getSuggestions(context, commandQueue, this.internalTree);
} }
private @NonNull List<@NonNull String> getSuggestions(final @NonNull CommandContext<C> commandContext, private @NonNull List<@NonNull String> getSuggestions(
final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> commandQueue, final @NonNull Queue<@NonNull String> commandQueue,
final @NonNull Node<@Nullable CommandArgument<C, ?>> root) { final @NonNull Node<@Nullable CommandArgument<C, ?>> root
) {
/* If the sender isn't allowed to access the root node, no suggestions are needed */ /* If the sender isn't allowed to access the root node, no suggestions are needed */
if (this.isPermitted(commandContext.getSender(), root) != null) { if (this.isPermitted(commandContext.getSender(), root) != null) {
@ -395,8 +428,8 @@ public final class CommandTree<C> {
// START: Compound arguments // START: Compound arguments
/* When we get in here, we need to treat compound arguments a little differently */ /* When we get in here, we need to treat compound arguments a little differently */
if (child.getValue() instanceof CompoundArgument) { if (child.getValue() instanceof CompoundArgument) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final CompoundArgument<?, C, ?> compoundArgument = (CompoundArgument<?, C, ?>) child
final CompoundArgument<?, C, ?> compoundArgument = (CompoundArgument<?, C, ?>) child.getValue(); .getValue();
/* See how many arguments it requires */ /* See how many arguments it requires */
final int requiredArguments = compoundArgument.getParserTuple().getSize(); final int requiredArguments = compoundArgument.getParserTuple().getSize();
/* Figure out whether we even need to care about this */ /* Figure out whether we even need to care about this */
@ -453,7 +486,10 @@ public final class CommandTree<C> {
while (childIterator.hasNext()) { while (childIterator.hasNext()) {
final Node<CommandArgument<C, ?>> child = childIterator.next(); final Node<CommandArgument<C, ?>> child = childIterator.next();
if (child.getValue() != null) { if (child.getValue() != null) {
final ArgumentParseResult<?> result = child.getValue().getParser().parse(commandContext, commandQueue); final ArgumentParseResult<?> result = child.getValue().getParser().parse(
commandContext,
commandQueue
);
if (result.getParsedValue().isPresent()) { if (result.getParsedValue().isPresent()) {
return this.getSuggestions(commandContext, commandQueue, child); return this.getSuggestions(commandContext, commandQueue, child);
} }
@ -517,17 +553,25 @@ public final class CommandTree<C> {
} }
} }
private @Nullable CommandPermission isPermitted(final @NonNull C sender, private @Nullable CommandPermission isPermitted(
final @NonNull Node<@Nullable CommandArgument<C, ?>> node) { final @NonNull C sender,
final @NonNull Node<@Nullable CommandArgument<C, ?>> node
) {
final CommandPermission permission = (CommandPermission) node.nodeMeta.get("permission"); final CommandPermission permission = (CommandPermission) node.nodeMeta.get("permission");
if (permission != null) { if (permission != null) {
return this.commandManager.hasPermission(sender, permission) ? null : permission; return this.commandManager.hasPermission(sender, permission) ? null : permission;
} }
if (node.isLeaf()) { if (node.isLeaf()) {
return this.commandManager.hasPermission(sender, return this.commandManager.hasPermission(
sender,
Objects.requireNonNull( Objects.requireNonNull(
Objects.requireNonNull(node.value, "node.value").getOwningCommand(), Objects.requireNonNull(
"owning command").getCommandPermission()) node.value,
"node.value"
).getOwningCommand(),
"owning command"
).getCommandPermission()
)
? null : Objects.requireNonNull(node.value.getOwningCommand(), "owning command") ? null : Objects.requireNonNull(node.value.getOwningCommand(), "owning command")
.getCommandPermission(); .getCommandPermission();
} }
@ -584,7 +628,8 @@ public final class CommandTree<C> {
chain = chain.subList(1, chain.size()); chain = chain.subList(1, chain.size());
// Go through all nodes from the tail upwards until a collision occurs // Go through all nodes from the tail upwards until a collision occurs
for (final Node<CommandArgument<C, ?>> commandArgumentNode : chain) { for (final Node<CommandArgument<C, ?>> commandArgumentNode : chain) {
final CommandPermission existingPermission = (CommandPermission) commandArgumentNode.nodeMeta.get("permission"); final CommandPermission existingPermission = (CommandPermission) commandArgumentNode.nodeMeta
.get("permission");
CommandPermission permission; CommandPermission permission;
if (existingPermission != null) { if (existingPermission != null) {
@ -594,9 +639,13 @@ public final class CommandTree<C> {
} }
/* Now also check if there's a command handler attached to an upper level node */ /* Now also check if there's a command handler attached to an upper level node */
if (commandArgumentNode.getValue() != null && commandArgumentNode.getValue().getOwningCommand() != null) { if (commandArgumentNode.getValue() != null && commandArgumentNode
.getValue()
.getOwningCommand() != null) {
final Command<C> command = commandArgumentNode.getValue().getOwningCommand(); final Command<C> command = commandArgumentNode.getValue().getOwningCommand();
if (this.getCommandManager().getSetting(CommandManager.ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS)) { if (this
.getCommandManager()
.getSetting(CommandManager.ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS)) {
permission = command.getCommandPermission(); permission = command.getCommandPermission();
} else { } else {
permission = OrPermission.of(Arrays.asList(permission, command.getCommandPermission())); permission = OrPermission.of(Arrays.asList(permission, command.getCommandPermission()));
@ -608,26 +657,30 @@ public final class CommandTree<C> {
}); });
} }
private void checkAmbiguity(final @NonNull Node<@Nullable CommandArgument<C, ?>> node) throws AmbiguousNodeException { private void checkAmbiguity(final @NonNull Node<@Nullable CommandArgument<C, ?>> node) throws
AmbiguousNodeException {
if (node.isLeaf()) { if (node.isLeaf()) {
return; return;
} }
final int size = node.children.size(); final int size = node.children.size();
for (final Node<CommandArgument<C, ?>> child : node.children) { for (final Node<CommandArgument<C, ?>> child : node.children) {
if (child.getValue() != null && !child.getValue().isRequired() && size > 1) { if (child.getValue() != null && !child.getValue().isRequired() && size > 1) {
throw new AmbiguousNodeException(node.getValue(), throw new AmbiguousNodeException(
node.getValue(),
child.getValue(), child.getValue(),
node.getChildren() node.getChildren()
.stream() .stream()
.filter(n -> n.getValue() != null) .filter(n -> n.getValue() != null)
.map(Node::getValue).collect(Collectors.toList())); .map(Node::getValue).collect(Collectors.toList())
);
} }
} }
node.children.forEach(this::checkAmbiguity); node.children.forEach(this::checkAmbiguity);
} }
private @NonNull List<@NonNull Node<@Nullable CommandArgument<C, ?>>> private @NonNull List<@NonNull Node<@Nullable CommandArgument<C, ?>>> getLeavesRaw(
getLeavesRaw(final @NonNull Node<@Nullable CommandArgument<C, ?>> node) { final @NonNull Node<@Nullable CommandArgument<C, ?>> node
) {
final List<Node<CommandArgument<C, ?>>> leaves = new LinkedList<>(); final List<Node<CommandArgument<C, ?>>> leaves = new LinkedList<>();
if (node.isLeaf()) { if (node.isLeaf()) {
if (node.getValue() != null) { if (node.getValue() != null) {
@ -639,7 +692,9 @@ public final class CommandTree<C> {
return leaves; return leaves;
} }
private @NonNull List<@NonNull CommandArgument<C, ?>> getLeaves(final @NonNull Node<@NonNull CommandArgument<C, ?>> node) { private @NonNull List<@NonNull CommandArgument<C, ?>> getLeaves(
final @NonNull Node<@NonNull CommandArgument<C, ?>> node
) {
final List<CommandArgument<C, ?>> leaves = new LinkedList<>(); final List<CommandArgument<C, ?>> leaves = new LinkedList<>();
if (node.isLeaf()) { if (node.isLeaf()) {
if (node.getValue() != null) { if (node.getValue() != null) {
@ -651,8 +706,9 @@ public final class CommandTree<C> {
return leaves; return leaves;
} }
private @NonNull List<@NonNull Node<@Nullable CommandArgument<C, ?>>> private @NonNull List<@NonNull Node<@Nullable CommandArgument<C, ?>>> getChain(
getChain(final @Nullable Node<@Nullable CommandArgument<C, ?>> end) { final @Nullable Node<@Nullable CommandArgument<C, ?>> end
) {
final List<Node<CommandArgument<C, ?>>> chain = new LinkedList<>(); final List<Node<CommandArgument<C, ?>>> chain = new LinkedList<>();
Node<CommandArgument<C, ?>> tail = end; Node<CommandArgument<C, ?>> tail = end;
while (tail != null) { while (tail != null) {
@ -812,6 +868,7 @@ public final class CommandTree<C> {
public String toString() { public String toString() {
return "Node{value=" + value + '}'; return "Node{value=" + value + '}';
} }
} }
} }

View file

@ -34,4 +34,5 @@ import java.lang.annotation.Target;
@Target(ElementType.PARAMETER) @Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface Greedy { public @interface Greedy {
} }

View file

@ -23,13 +23,13 @@
// //
package cloud.commandframework.arguments; package cloud.commandframework.arguments;
import cloud.commandframework.arguments.parser.ArgumentParser;
import io.leangen.geantyref.TypeToken;
import cloud.commandframework.Command; import cloud.commandframework.Command;
import cloud.commandframework.CommandManager; import cloud.commandframework.CommandManager;
import cloud.commandframework.arguments.parser.ArgumentParseResult; import cloud.commandframework.arguments.parser.ArgumentParseResult;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.arguments.parser.ParserParameters; import cloud.commandframework.arguments.parser.ParserParameters;
import cloud.commandframework.context.CommandContext; import cloud.commandframework.context.CommandContext;
import io.leangen.geantyref.TypeToken;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.Nullable;
@ -99,12 +99,14 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @param valueType Type produced by the parser * @param valueType Type produced by the parser
* @param suggestionsProvider Suggestions provider * @param suggestionsProvider Suggestions provider
*/ */
public CommandArgument(final boolean required, public CommandArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull ArgumentParser<C, T> parser, final @NonNull ArgumentParser<C, T> parser,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @NonNull TypeToken<T> valueType, final @NonNull TypeToken<T> valueType,
final @Nullable BiFunction<CommandContext<C>, String, List<String>> suggestionsProvider) { final @Nullable BiFunction<CommandContext<C>, String, List<String>> suggestionsProvider
) {
this.required = required; this.required = required;
this.name = Objects.requireNonNull(name, "Name may not be null"); this.name = Objects.requireNonNull(name, "Name may not be null");
if (!NAME_PATTERN.asPredicate().test(name)) { if (!NAME_PATTERN.asPredicate().test(name)) {
@ -128,13 +130,15 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @param valueType Type produced by the parser * @param valueType Type produced by the parser
* @param suggestionsProvider Suggestions provider * @param suggestionsProvider Suggestions provider
*/ */
public CommandArgument(final boolean required, public CommandArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull ArgumentParser<C, T> parser, final @NonNull ArgumentParser<C, T> parser,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @NonNull Class<T> valueType, final @NonNull Class<T> valueType,
final @Nullable BiFunction<@NonNull CommandContext<C>, final @Nullable BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider
) {
this(required, name, parser, defaultValue, TypeToken.get(valueType), suggestionsProvider); this(required, name, parser, defaultValue, TypeToken.get(valueType), suggestionsProvider);
} }
@ -146,10 +150,12 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @param parser The argument parser * @param parser The argument parser
* @param valueType Type produced by the parser * @param valueType Type produced by the parser
*/ */
public CommandArgument(final boolean required, public CommandArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull ArgumentParser<C, T> parser, final @NonNull ArgumentParser<C, T> parser,
final @NonNull Class<T> valueType) { final @NonNull Class<T> valueType
) {
this(required, name, parser, "", valueType, null); this(required, name, parser, "", valueType, null);
} }
@ -167,8 +173,10 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @param <T> Argument Type. Used to make the compiler happy. * @param <T> Argument Type. Used to make the compiler happy.
* @return Argument builder * @return Argument builder
*/ */
public static <C, T> CommandArgument.@NonNull Builder<C, T> ofType(final @NonNull TypeToken<T> clazz, public static <C, T> CommandArgument.@NonNull Builder<C, T> ofType(
final @NonNull String name) { final @NonNull TypeToken<T> clazz,
final @NonNull String name
) {
return new Builder<>(clazz, name); return new Builder<>(clazz, name);
} }
@ -181,8 +189,10 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
* @param <T> Argument Type. Used to make the compiler happy. * @param <T> Argument Type. Used to make the compiler happy.
* @return Argument builder * @return Argument builder
*/ */
public static <C, T> CommandArgument.@NonNull Builder<@NonNull C, @NonNull T> ofType(final @NonNull Class<T> clazz, public static <C, T> CommandArgument.@NonNull Builder<@NonNull C, @NonNull T> ofType(
final @NonNull String name) { final @NonNull Class<T> clazz,
final @NonNull String name
) {
return new Builder<>(TypeToken.get(clazz), name); return new Builder<>(TypeToken.get(clazz), name);
} }
@ -366,14 +376,18 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
private String defaultValue = ""; private String defaultValue = "";
private BiFunction<@NonNull CommandContext<C>, @NonNull String, @NonNull List<String>> suggestionsProvider; private BiFunction<@NonNull CommandContext<C>, @NonNull String, @NonNull List<String>> suggestionsProvider;
protected Builder(final @NonNull TypeToken<T> valueType, protected Builder(
final @NonNull String name) { final @NonNull TypeToken<T> valueType,
final @NonNull String name
) {
this.valueType = valueType; this.valueType = valueType;
this.name = name; this.name = name;
} }
protected Builder(final @NonNull Class<T> valueType, protected Builder(
final @NonNull String name) { final @NonNull Class<T> valueType,
final @NonNull String name
) {
this(TypeToken.get(valueType), name); this(TypeToken.get(valueType), name);
} }
@ -452,7 +466,8 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
*/ */
public @NonNull Builder<@NonNull C, @NonNull T> withSuggestionsProvider( public @NonNull Builder<@NonNull C, @NonNull T> withSuggestionsProvider(
final @NonNull BiFunction<@NonNull CommandContext<C>, final @NonNull BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<String>> suggestionsProvider) { @NonNull String, @NonNull List<String>> suggestionsProvider
) {
this.suggestionsProvider = suggestionsProvider; this.suggestionsProvider = suggestionsProvider;
return this; return this;
} }
@ -475,7 +490,8 @@ public class CommandArgument<C, T> implements Comparable<CommandArgument<?, ?>>
this.suggestionsProvider = new DelegatingSuggestionsProvider<>(this.name, this.parser); this.suggestionsProvider = new DelegatingSuggestionsProvider<>(this.name, this.parser);
} }
return new CommandArgument<>(this.required, this.name, this.parser, return new CommandArgument<>(this.required, this.name, this.parser,
this.defaultValue, this.valueType, this.suggestionsProvider); this.defaultValue, this.valueType, this.suggestionsProvider
);
} }
protected final @NonNull String getName() { protected final @NonNull String getName() {

View file

@ -44,7 +44,9 @@ public interface CommandSyntaxFormatter<C> {
* @param node Trailing node * @param node Trailing node
* @return Syntax string * @return Syntax string
*/ */
@NonNull String apply(@NonNull List<@NonNull CommandArgument<C, ?>> commandArguments, @NonNull String apply(
CommandTree.@Nullable Node<@Nullable CommandArgument<C, ?>> node); @NonNull List<@NonNull CommandArgument<C, ?>> commandArguments,
CommandTree.@Nullable Node<@Nullable CommandArgument<C, ?>> node
);
} }

View file

@ -49,7 +49,8 @@ final class DelegatingSuggestionsProvider<C> implements BiFunction<@NonNull Comm
@Override @Override
public String toString() { public String toString() {
return String.format("DelegatingSuggestionsProvider{name='%s',parser='%s'}", this.argumentName, return String.format("DelegatingSuggestionsProvider{name='%s',parser='%s'}", this.argumentName,
this.parser.getClass().getCanonicalName()); this.parser.getClass().getCanonicalName()
);
} }
} }

View file

@ -46,8 +46,10 @@ import java.util.List;
public class StandardCommandSyntaxFormatter<C> implements CommandSyntaxFormatter<C> { public class StandardCommandSyntaxFormatter<C> implements CommandSyntaxFormatter<C> {
@Override @Override
public final @NonNull String apply(final @NonNull List<@NonNull CommandArgument<C, ?>> commandArguments, public final @NonNull String apply(
final CommandTree.@Nullable Node<@Nullable CommandArgument<C, ?>> node) { final @NonNull List<@NonNull CommandArgument<C, ?>> commandArguments,
final CommandTree.@Nullable Node<@Nullable CommandArgument<C, ?>> node
) {
final StringBuilder stringBuilder = new StringBuilder(); final StringBuilder stringBuilder = new StringBuilder();
final Iterator<CommandArgument<C, ?>> iterator = commandArguments.iterator(); final Iterator<CommandArgument<C, ?>> iterator = commandArguments.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
@ -73,8 +75,9 @@ public class StandardCommandSyntaxFormatter<C> implements CommandSyntaxFormatter
if (commandArgument instanceof FlagArgument) { if (commandArgument instanceof FlagArgument) {
final StringBuilder flagBuilder = new StringBuilder(); final StringBuilder flagBuilder = new StringBuilder();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final Iterator<CommandFlag<?>> flagIterator = ((FlagArgument<C>) commandArgument)
final Iterator<CommandFlag<?>> flagIterator = ((FlagArgument<C>) commandArgument).getFlags().iterator(); .getFlags()
.iterator();
while (flagIterator.hasNext()) { while (flagIterator.hasNext()) {
final CommandFlag<?> flag = flagIterator.next(); final CommandFlag<?> flag = flagIterator.next();
flagBuilder.append("--").append(flag.getName()); flagBuilder.append("--").append(flag.getName());
@ -140,8 +143,9 @@ public class StandardCommandSyntaxFormatter<C> implements CommandSyntaxFormatter
stringBuilder.append(suffix); stringBuilder.append(suffix);
} else if (argument instanceof FlagArgument) { } else if (argument instanceof FlagArgument) {
final StringBuilder flagBuilder = new StringBuilder(); final StringBuilder flagBuilder = new StringBuilder();
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final Iterator<CommandFlag<?>> flagIterator = ((FlagArgument<C>) argument)
final Iterator<CommandFlag<?>> flagIterator = ((FlagArgument<C>) argument).getFlags().iterator(); .getFlags()
.iterator();
while (flagIterator.hasNext()) { while (flagIterator.hasNext()) {
final CommandFlag<?> flag = flagIterator.next(); final CommandFlag<?> flag = flagIterator.next();
flagBuilder.append("--").append(flag.getName()); flagBuilder.append("--").append(flag.getName());

View file

@ -56,8 +56,10 @@ public final class StaticArgument<C> extends CommandArgument<C, String> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Constructed argument * @return Constructed argument
*/ */
public static <C> @NonNull StaticArgument<C> of(final @NonNull String name, public static <C> @NonNull StaticArgument<C> of(
final @NonNull String... aliases) { final @NonNull String name,
final @NonNull String... aliases
) {
return new StaticArgument<>(true, name, aliases); return new StaticArgument<>(true, name, aliases);
} }
@ -104,8 +106,10 @@ public final class StaticArgument<C> extends CommandArgument<C, String> {
} }
@Override @Override
public @NonNull ArgumentParseResult<String> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<String> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String string = inputQueue.peek(); final String string = inputQueue.peek();
if (string == null) { if (string == null) {
return ArgumentParseResult.failure(new NullPointerException("No input provided")); return ArgumentParseResult.failure(new NullPointerException("No input provided"));
@ -118,8 +122,10 @@ public final class StaticArgument<C> extends CommandArgument<C, String> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return Collections.singletonList(this.name); return Collections.singletonList(this.name);
} }

View file

@ -54,13 +54,15 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
* @param mapper Mapper that maps the sub-arguments to the output type * @param mapper Mapper that maps the sub-arguments to the output type
* @param valueType The output type * @param valueType The output type
*/ */
protected ArgumentPair(final boolean required, protected ArgumentPair(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull Pair<@NonNull String, @NonNull String> names, final @NonNull Pair<@NonNull String, @NonNull String> names,
final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> types, final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> types,
final @NonNull Pair<@NonNull ArgumentParser<C, U>, @NonNull ArgumentParser<C, V>> parserPair, final @NonNull Pair<@NonNull ArgumentParser<C, U>, @NonNull ArgumentParser<C, V>> parserPair,
final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper, final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper,
final @NonNull TypeToken<O> valueType) { final @NonNull TypeToken<O> valueType
) {
super(required, name, names, parserPair, types, mapper, o -> Pair.of((U) o[0], (V) o[1]), valueType); super(required, name, names, parserPair, types, mapper, o -> Pair.of((U) o[0], (V) o[1]), valueType);
} }
@ -78,19 +80,25 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
* @param <V> Second parsed type * @param <V> Second parsed type
* @return Intermediary builder * @return Intermediary builder
*/ */
public static <C, U, V> @NonNull ArgumentPairIntermediaryBuilder<C, U, V> of(final @NonNull CommandManager<C> manager, public static <C, U, V> @NonNull ArgumentPairIntermediaryBuilder<C, U, V> of(
final @NonNull CommandManager<C> manager,
final @NonNull String name, final @NonNull String name,
final @NonNull Pair<@NonNull String, final @NonNull Pair<@NonNull String,
@NonNull String> names, @NonNull String> names,
final @NonNull Pair<@NonNull Class<U>, final @NonNull Pair<@NonNull Class<U>,
@NonNull Class<V>> types) { @NonNull Class<V>> types
) {
final ParserRegistry<C> parserRegistry = manager.getParserRegistry(); final ParserRegistry<C> parserRegistry = manager.getParserRegistry();
final ArgumentParser<C, U> firstParser = parserRegistry.createParser(TypeToken.get(types.getFirst()), final ArgumentParser<C, U> firstParser = parserRegistry.createParser(
ParserParameters.empty()).orElseThrow(() -> TypeToken.get(types.getFirst()),
ParserParameters.empty()
).orElseThrow(() ->
new IllegalArgumentException( new IllegalArgumentException(
"Could not create parser for primary type")); "Could not create parser for primary type"));
final ArgumentParser<C, V> secondaryParser = parserRegistry.createParser(TypeToken.get(types.getSecond()), final ArgumentParser<C, V> secondaryParser = parserRegistry.createParser(
ParserParameters.empty()).orElseThrow(() -> TypeToken.get(types.getSecond()),
ParserParameters.empty()
).orElseThrow(() ->
new IllegalArgumentException( new IllegalArgumentException(
"Could not create parser for secondary type")); "Could not create parser for secondary type"));
return new ArgumentPairIntermediaryBuilder<>(true, name, names, Pair.of(firstParser, secondaryParser), types); return new ArgumentPairIntermediaryBuilder<>(true, name, names, Pair.of(firstParser, secondaryParser), types);
@ -105,12 +113,14 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
private final Pair<String, String> names; private final Pair<String, String> names;
private final Pair<Class<U>, Class<V>> types; private final Pair<Class<U>, Class<V>> types;
private ArgumentPairIntermediaryBuilder(final boolean required, private ArgumentPairIntermediaryBuilder(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull Pair<@NonNull String, @NonNull String> names, final @NonNull Pair<@NonNull String, @NonNull String> names,
final @NonNull Pair<@NonNull ArgumentParser<@NonNull C, @NonNull U>, final @NonNull Pair<@NonNull ArgumentParser<@NonNull C, @NonNull U>,
@NonNull ArgumentParser<@NonNull C, @NonNull V>> parserPair, @NonNull ArgumentParser<@NonNull C, @NonNull V>> parserPair,
final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> types) { final @NonNull Pair<@NonNull Class<U>, @NonNull Class<V>> types
) {
this.required = required; this.required = required;
this.name = name; this.name = name;
this.names = names; this.names = names;
@ -124,14 +134,16 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
* @return Argument pair * @return Argument pair
*/ */
public @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull Pair<@NonNull U, @NonNull V>> simple() { public @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull Pair<@NonNull U, @NonNull V>> simple() {
return new ArgumentPair<C, U, V, Pair<U, V>>(this.required, return new ArgumentPair<C, U, V, Pair<U, V>>(
this.required,
this.name, this.name,
this.names, this.names,
this.types, this.types,
this.parserPair, this.parserPair,
(sender, pair) -> pair, (sender, pair) -> pair,
new TypeToken<Pair<U, V>>() { new TypeToken<Pair<U, V>>() {
}); }
);
} }
/** /**
@ -142,9 +154,11 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
* @param <O> Output type * @param <O> Output type
* @return Created pair * @return Created pair
*/ */
public <O> @NonNull ArgumentPair<C, U, V, O> withMapper(final @NonNull TypeToken<O> clazz, public <O> @NonNull ArgumentPair<C, U, V, O> withMapper(
final @NonNull TypeToken<O> clazz,
final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U,
@NonNull V>, @NonNull O> mapper) { @NonNull V>, @NonNull O> mapper
) {
return new ArgumentPair<C, U, V, O>(this.required, this.name, this.names, this.types, this.parserPair, mapper, clazz); return new ArgumentPair<C, U, V, O>(this.required, this.name, this.names, this.types, this.parserPair, mapper, clazz);
} }
@ -158,7 +172,8 @@ public class ArgumentPair<C, U, V, O> extends CompoundArgument<Pair<U, V>, C, O>
*/ */
public <O> @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull O> withMapper( public <O> @NonNull ArgumentPair<@NonNull C, @NonNull U, @NonNull V, @NonNull O> withMapper(
final @NonNull Class<O> clazz, final @NonNull Class<O> clazz,
final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper) { final @NonNull BiFunction<@NonNull C, @NonNull Pair<@NonNull U, @NonNull V>, @NonNull O> mapper
) {
return this.withMapper(TypeToken.get(clazz), mapper); return this.withMapper(TypeToken.get(clazz), mapper);
} }

View file

@ -55,7 +55,8 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
* @param mapper Mapper that maps the sub-arguments to the output type * @param mapper Mapper that maps the sub-arguments to the output type
* @param valueType The output type * @param valueType The output type
*/ */
protected ArgumentTriplet(final boolean required, protected ArgumentTriplet(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names, final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names,
final @NonNull Triplet<@NonNull Class<U>, @NonNull Class<V>, @NonNull Class<W>> types, final @NonNull Triplet<@NonNull Class<U>, @NonNull Class<V>, @NonNull Class<W>> types,
@ -63,7 +64,8 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
@NonNull ArgumentParser<C, W>> parserTriplet, @NonNull ArgumentParser<C, W>> parserTriplet,
final @NonNull BiFunction<@NonNull C, final @NonNull BiFunction<@NonNull C,
@NonNull Triplet<U, @NonNull V, @NonNull W>, @NonNull O> mapper, @NonNull Triplet<U, @NonNull V, @NonNull W>, @NonNull O> mapper,
final @NonNull TypeToken<O> valueType) { final @NonNull TypeToken<O> valueType
) {
super(required, name, names, parserTriplet, types, mapper, o -> Triplet.of((U) o[0], (V) o[1], (W) o[2]), valueType); super(required, name, names, parserTriplet, types, mapper, o -> Triplet.of((U) o[0], (V) o[1], (W) o[2]), valueType);
} }
@ -83,25 +85,34 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
* @return Intermediary builder * @return Intermediary builder
*/ */
public static <C, U, V, W> @NonNull ArgumentTripletIntermediaryBuilder<@NonNull C, @NonNull U, @NonNull V, @NonNull W> public static <C, U, V, W> @NonNull ArgumentTripletIntermediaryBuilder<@NonNull C, @NonNull U, @NonNull V, @NonNull W>
of(final @NonNull CommandManager<C> manager, of(
final @NonNull CommandManager<C> manager,
final @NonNull String name, final @NonNull String name,
final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names, final @NonNull Triplet<@NonNull String, @NonNull String, @NonNull String> names,
final @NonNull Triplet<@NonNull Class<U>, @NonNull Class<V>, @NonNull Class<W>> types) { final @NonNull Triplet<@NonNull Class<U>, @NonNull Class<V>, @NonNull Class<W>> types
) {
final ParserRegistry<C> parserRegistry = manager.getParserRegistry(); final ParserRegistry<C> parserRegistry = manager.getParserRegistry();
final ArgumentParser<C, U> firstParser = parserRegistry.createParser(TypeToken.get(types.getFirst()), final ArgumentParser<C, U> firstParser = parserRegistry.createParser(
ParserParameters.empty()).orElseThrow(() -> TypeToken.get(types.getFirst()),
ParserParameters.empty()
).orElseThrow(() ->
new IllegalArgumentException( new IllegalArgumentException(
"Could not create parser for primary type")); "Could not create parser for primary type"));
final ArgumentParser<C, V> secondaryParser = parserRegistry.createParser(TypeToken.get(types.getSecond()), final ArgumentParser<C, V> secondaryParser = parserRegistry.createParser(
ParserParameters.empty()).orElseThrow(() -> TypeToken.get(types.getSecond()),
ParserParameters.empty()
).orElseThrow(() ->
new IllegalArgumentException( new IllegalArgumentException(
"Could not create parser for secondary type")); "Could not create parser for secondary type"));
final ArgumentParser<C, W> tertiaryParser = parserRegistry.createParser(TypeToken.get(types.getThird()), final ArgumentParser<C, W> tertiaryParser = parserRegistry.createParser(
ParserParameters.empty()).orElseThrow(() -> TypeToken.get(types.getThird()),
ParserParameters.empty()
).orElseThrow(() ->
new IllegalArgumentException( new IllegalArgumentException(
"Could not create parser for tertiary type")); "Could not create parser for tertiary type"));
return new ArgumentTripletIntermediaryBuilder<>(true, name, names, return new ArgumentTripletIntermediaryBuilder<>(true, name, names,
Triplet.of(firstParser, secondaryParser, tertiaryParser), types); Triplet.of(firstParser, secondaryParser, tertiaryParser), types
);
} }
@SuppressWarnings("ALL") @SuppressWarnings("ALL")
@ -113,7 +124,8 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
private final Triplet<String, String, String> names; private final Triplet<String, String, String> names;
private final Triplet<Class<U>, Class<V>, Class<W>> types; private final Triplet<Class<U>, Class<V>, Class<W>> types;
private ArgumentTripletIntermediaryBuilder(final boolean required, private ArgumentTripletIntermediaryBuilder(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull Triplet<@NonNull String, @NonNull String, final @NonNull Triplet<@NonNull String, @NonNull String,
@NonNull String> names, @NonNull String> names,
@ -121,7 +133,8 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
@NonNull ArgumentParser<C, V>, @NonNull ArgumentParser<C, V>,
@NonNull ArgumentParser<C, W>> parserTriplet, @NonNull ArgumentParser<C, W>> parserTriplet,
final @NonNull Triplet<@NonNull Class<U>, final @NonNull Triplet<@NonNull Class<U>,
@NonNull Class<V>, @NonNull Class<W>> types) { @NonNull Class<V>, @NonNull Class<W>> types
) {
this.required = required; this.required = required;
this.name = name; this.name = name;
this.names = names; this.names = names;
@ -136,14 +149,16 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
*/ */
public @NonNull ArgumentTriplet<@NonNull C, @NonNull U, @NonNull V, public @NonNull ArgumentTriplet<@NonNull C, @NonNull U, @NonNull V,
@NonNull W, Triplet<U, V, W>> simple() { @NonNull W, Triplet<U, V, W>> simple() {
return new ArgumentTriplet<>(this.required, return new ArgumentTriplet<>(
this.required,
this.name, this.name,
this.names, this.names,
this.types, this.types,
this.parserTriplet, this.parserTriplet,
(sender, triplet) -> triplet, (sender, triplet) -> triplet,
new TypeToken<Triplet<U, V, W>>() { new TypeToken<Triplet<U, V, W>>() {
}); }
);
} }
/** /**
@ -155,9 +170,11 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
* @return Created triplet * @return Created triplet
*/ */
public <O> @NonNull ArgumentTriplet<@NonNull C, @NonNull U, @NonNull V, public <O> @NonNull ArgumentTriplet<@NonNull C, @NonNull U, @NonNull V,
@NonNull W, @NonNull O> withMapper(final @NonNull TypeToken<O> clazz, @NonNull W, @NonNull O> withMapper(
final @NonNull TypeToken<O> clazz,
final @NonNull BiFunction<@NonNull C, @NonNull Triplet<@NonNull U, final @NonNull BiFunction<@NonNull C, @NonNull Triplet<@NonNull U,
@NonNull V, @NonNull W>, @NonNull O> mapper) { @NonNull V, @NonNull W>, @NonNull O> mapper
) {
return new ArgumentTriplet<>(this.required, this.name, this.names, this.types, this.parserTriplet, mapper, clazz); return new ArgumentTriplet<>(this.required, this.name, this.names, this.types, this.parserTriplet, mapper, clazz);
} }
@ -169,12 +186,15 @@ public class ArgumentTriplet<C, U, V, W, O> extends CompoundArgument<Triplet<U,
* @param <O> Output type * @param <O> Output type
* @return Created triplet * @return Created triplet
*/ */
public <O> @NonNull ArgumentTriplet<C, U, V, W, O> withMapper(final @NonNull Class<O> clazz, public <O> @NonNull ArgumentTriplet<C, U, V, W, O> withMapper(
final @NonNull Class<O> clazz,
final @NonNull BiFunction<@NonNull C, @NonNull Triplet< final @NonNull BiFunction<@NonNull C, @NonNull Triplet<
@NonNull U, @NonNull V, @NonNull W>, @NonNull U, @NonNull V, @NonNull W>,
@NonNull O> mapper) { @NonNull O> mapper
) {
return new ArgumentTriplet<>(this.required, this.name, this.names, this.types, return new ArgumentTriplet<>(this.required, this.name, this.names, this.types,
this.parserTriplet, mapper, TypeToken.get(clazz)); this.parserTriplet, mapper, TypeToken.get(clazz)
);
} }
} }

View file

@ -61,20 +61,24 @@ public class CompoundArgument<T extends Tuple, C, O> extends CommandArgument<C,
* @param tupleFactory Function to use when creating tuple * @param tupleFactory Function to use when creating tuple
* @param valueType The output type * @param valueType The output type
*/ */
public CompoundArgument(final boolean required, public CompoundArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull Tuple names, final @NonNull Tuple names,
final @NonNull Tuple parserTuple, final @NonNull Tuple parserTuple,
final @NonNull Tuple types, final @NonNull Tuple types,
final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper, final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper,
final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory, final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory,
final @NonNull TypeToken<O> valueType) { final @NonNull TypeToken<O> valueType
super(required, ) {
super(
required,
name, name,
new CompoundParser<>(parserTuple, mapper, tupleFactory), new CompoundParser<>(parserTuple, mapper, tupleFactory),
"", "",
valueType, valueType,
null); null
);
this.parserTuple = parserTuple; this.parserTuple = parserTuple;
this.names = names; this.names = names;
this.types = types; this.types = types;
@ -114,17 +118,21 @@ public class CompoundArgument<T extends Tuple, C, O> extends CommandArgument<C,
private final BiFunction<C, T, O> mapper; private final BiFunction<C, T, O> mapper;
private final Function<Object[], T> tupleFactory; private final Function<Object[], T> tupleFactory;
private CompoundParser(final @NonNull Tuple parserTuple, private CompoundParser(
final @NonNull Tuple parserTuple,
final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper, final @NonNull BiFunction<@NonNull C, @NonNull T, @NonNull O> mapper,
final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory) { final @NonNull Function<@NonNull Object[], @NonNull T> tupleFactory
) {
this.parsers = parserTuple.toArray(); this.parsers = parserTuple.toArray();
this.mapper = mapper; this.mapper = mapper;
this.tupleFactory = tupleFactory; this.tupleFactory = tupleFactory;
} }
@Override @Override
public @NonNull ArgumentParseResult<O> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<O> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final Object[] output = new Object[this.parsers.length]; final Object[] output = new Object[this.parsers.length];
for (int i = 0; i < this.parsers.length; i++) { for (int i = 0; i < this.parsers.length; i++) {
@SuppressWarnings("unchecked") final ArgumentParser<C, ?> parser = (ArgumentParser<C, ?>) this.parsers[i]; @SuppressWarnings("unchecked") final ArgumentParser<C, ?> parser = (ArgumentParser<C, ?>) this.parsers[i];
@ -141,16 +149,20 @@ public class CompoundArgument<T extends Tuple, C, O> extends CommandArgument<C,
* Now check if the mapper threw any exceptions * Now check if the mapper threw any exceptions
*/ */
try { try {
return ArgumentParseResult.success(this.mapper.apply(commandContext.getSender(), return ArgumentParseResult.success(this.mapper.apply(
this.tupleFactory.apply(output))); commandContext.getSender(),
this.tupleFactory.apply(output)
));
} catch (final Exception e) { } catch (final Exception e) {
return ArgumentParseResult.failure(e); return ArgumentParseResult.failure(e);
} }
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
/* /*
This method will be called n times, each time for each of the internal types. This method will be called n times, each time for each of the internal types.
The problem is that we need to then know which of the parsers to forward the The problem is that we need to then know which of the parsers to forward the
@ -163,6 +175,7 @@ public class CompoundArgument<T extends Tuple, C, O> extends CommandArgument<C,
//noinspection all //noinspection all
return ((ArgumentParser<C, ?>) this.parsers[argument]).suggestions(commandContext, input); return ((ArgumentParser<C, ?>) this.parsers[argument]).suggestions(commandContext, input);
} }
} }
} }

View file

@ -66,10 +66,12 @@ public final class FlagArgument<C> extends CommandArgument<C, Object> {
* @param flags Flags * @param flags Flags
*/ */
public FlagArgument(final Collection<CommandFlag<?>> flags) { public FlagArgument(final Collection<CommandFlag<?>> flags) {
super(false, super(
false,
FLAG_ARGUMENT_NAME, FLAG_ARGUMENT_NAME,
new FlagArgumentParser<>(flags.toArray(new CommandFlag<?>[0])), new FlagArgumentParser<>(flags.toArray(new CommandFlag<?>[0])),
Object.class); Object.class
);
this.flags = flags; this.flags = flags;
} }
@ -92,8 +94,10 @@ public final class FlagArgument<C> extends CommandArgument<C, Object> {
} }
@Override @Override
public @NonNull ArgumentParseResult<@NonNull Object> parse(final @NonNull CommandContext<@NonNull C> commandContext, public @NonNull ArgumentParseResult<@NonNull Object> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<@NonNull C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
/* /*
This argument must necessarily be the last so we can just consume all remaining input. This argument type This argument must necessarily be the last so we can just consume all remaining input. This argument type
is similar to a greedy string in that sense. But, we need to keep all flag logic contained to the parser is similar to a greedy string in that sense. But, we need to keep all flag logic contained to the parser
@ -149,8 +153,10 @@ public final class FlagArgument<C> extends CommandArgument<C, Object> {
final ArgumentParseResult<?> result = final ArgumentParseResult<?> result =
((CommandArgument) currentFlag.getCommandArgument()) ((CommandArgument) currentFlag.getCommandArgument())
.getParser() .getParser()
.parse(commandContext, .parse(
new LinkedList<>(Collections.singletonList(string))); commandContext,
new LinkedList<>(Collections.singletonList(string))
);
if (result.getFailure().isPresent()) { if (result.getFailure().isPresent()) {
return ArgumentParseResult.failure(result.getFailure().get()); return ArgumentParseResult.failure(result.getFailure().get());
} else { } else {
@ -167,8 +173,10 @@ public final class FlagArgument<C> extends CommandArgument<C, Object> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
/* Check if we have a last flag stored */ /* Check if we have a last flag stored */
final String lastArg = commandContext.getOrDefault(FLAG_META, ""); final String lastArg = commandContext.getOrDefault(FLAG_META, "");
if (lastArg.isEmpty() || !lastArg.startsWith("-")) { if (lastArg.isEmpty() || !lastArg.startsWith("-")) {

View file

@ -48,10 +48,12 @@ public final class CommandFlag<T> {
private final @Nullable CommandArgument<?, T> commandArgument; private final @Nullable CommandArgument<?, T> commandArgument;
private CommandFlag(final @NonNull String name, private CommandFlag(
final @NonNull String name,
final @NonNull String @NonNull [] aliases, final @NonNull String @NonNull [] aliases,
final @NonNull Description description, final @NonNull Description description,
final @Nullable CommandArgument<?, T> commandArgument) { final @Nullable CommandArgument<?, T> commandArgument
) {
this.name = name; this.name = name;
this.aliases = aliases; this.aliases = aliases;
this.description = description; this.description = description;
@ -135,10 +137,12 @@ public final class CommandFlag<T> {
private final Description description; private final Description description;
private final CommandArgument<?, T> commandArgument; private final CommandArgument<?, T> commandArgument;
private Builder(final @NonNull String name, private Builder(
final @NonNull String name,
final @NonNull String[] aliases, final @NonNull String[] aliases,
final @NonNull Description description, final @NonNull Description description,
final @Nullable CommandArgument<?, T> commandArgument) { final @Nullable CommandArgument<?, T> commandArgument
) {
this.name = name; this.name = name;
this.aliases = aliases; this.aliases = aliases;
this.description = description; this.description = description;

View file

@ -70,8 +70,10 @@ public final class FlagContext {
* @param value Flag value * @param value Flag value
* @param <T> Value type * @param <T> Value type
*/ */
public <T> void addValueFlag(final @NonNull CommandFlag<T> flag, public <T> void addValueFlag(
final @NonNull T value) { final @NonNull CommandFlag<T> flag,
final @NonNull T value
) {
this.flagValues.put(flag.getName(), value); this.flagValues.put(flag.getName(), value);
} }
@ -96,8 +98,10 @@ public final class FlagContext {
* @param <T> Value type * @param <T> Value type
* @return Stored value, or the supplied default value * @return Stored value, or the supplied default value
*/ */
public <T> @Nullable T getValue(final @NonNull String name, public <T> @Nullable T getValue(
final @Nullable T defaultValue) { final @NonNull String name,
final @Nullable T defaultValue
) {
final Object value = this.flagValues.get(name); final Object value = this.flagValues.get(name);
if (value == null) { if (value == null) {
return defaultValue; return defaultValue;

View file

@ -118,6 +118,7 @@ public abstract class ArgumentParseResult<T> {
public @NonNull Optional<Throwable> getFailure() { public @NonNull Optional<Throwable> getFailure() {
return Optional.of(this.failure); return Optional.of(this.failure);
} }
} }
} }

View file

@ -46,8 +46,10 @@ public interface ArgumentParser<C, T> {
* @param inputQueue The queue of arguments * @param inputQueue The queue of arguments
* @return Parsed command result * @return Parsed command result
*/ */
@NonNull ArgumentParseResult<@NonNull T> parse(@NonNull CommandContext<@NonNull C> commandContext, @NonNull ArgumentParseResult<@NonNull T> parse(
@NonNull Queue<@NonNull String> inputQueue); @NonNull CommandContext<@NonNull C> commandContext,
@NonNull Queue<@NonNull String> inputQueue
);
/** /**
* Get a list of suggested arguments that would be correctly parsed by this parser * Get a list of suggested arguments that would be correctly parsed by this parser
@ -56,8 +58,10 @@ public interface ArgumentParser<C, T> {
* @param input Input string * @param input Input string
* @return List of suggestions * @return List of suggestions
*/ */
default @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, default @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return Collections.emptyList(); return Collections.emptyList();
} }

View file

@ -44,8 +44,10 @@ public class ParserParameter<T> {
* @param key Parameter key * @param key Parameter key
* @param expectedType Type that is expected to be mapped to this parameter * @param expectedType Type that is expected to be mapped to this parameter
*/ */
public ParserParameter(final @NonNull String key, public ParserParameter(
final @NonNull TypeToken<T> expectedType) { final @NonNull String key,
final @NonNull TypeToken<T> expectedType
) {
this.key = key; this.key = key;
this.expectedType = expectedType; this.expectedType = expectedType;
} }

View file

@ -53,8 +53,10 @@ public final class ParserParameters {
* @param <T> Value type * @param <T> Value type
* @return Constructed instance * @return Constructed instance
*/ */
public static <T> @NonNull ParserParameters single(final @NonNull ParserParameter<T> parameter, public static <T> @NonNull ParserParameters single(
final @NonNull T value) { final @NonNull ParserParameter<T> parameter,
final @NonNull T value
) {
final ParserParameters parameters = new ParserParameters(); final ParserParameters parameters = new ParserParameters();
parameters.store(parameter, value); parameters.store(parameter, value);
return parameters; return parameters;
@ -78,8 +80,10 @@ public final class ParserParameters {
* @param value Object * @param value Object
* @param <T> Parameter type * @param <T> Parameter type
*/ */
public <T> void store(final @NonNull ParserParameter<T> parameter, public <T> void store(
final @NonNull T value) { final @NonNull ParserParameter<T> parameter,
final @NonNull T value
) {
this.internalMap.put(parameter, value); this.internalMap.put(parameter, value);
} }
@ -92,8 +96,10 @@ public final class ParserParameters {
* @return Parameter value * @return Parameter value
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> @NonNull T get(final @NonNull ParserParameter<T> parameter, public <T> @NonNull T get(
final @NonNull T defaultValue) { final @NonNull ParserParameter<T> parameter,
final @NonNull T defaultValue
) {
return (T) this.internalMap.getOrDefault(parameter, defaultValue); return (T) this.internalMap.getOrDefault(parameter, defaultValue);
} }

View file

@ -49,8 +49,10 @@ public interface ParserRegistry<C> {
* to configure the parser, many of which are documented in {@link StandardParameters} * to configure the parser, many of which are documented in {@link StandardParameters}
* @param <T> Generic type specifying what is produced by the parser * @param <T> Generic type specifying what is produced by the parser
*/ */
<T> void registerParserSupplier(@NonNull TypeToken<T> type, <T> void registerParserSupplier(
@NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser<C, ?>> supplier); @NonNull TypeToken<T> type,
@NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser<C, ?>> supplier
);
/** /**
* Register a named parser supplier * Register a named parser supplier
@ -59,8 +61,10 @@ public interface ParserRegistry<C> {
* @param supplier The function that generates the parser. The map supplied my contain parameters used * @param supplier The function that generates the parser. The map supplied my contain parameters used
* to configure the parser, many of which are documented in {@link StandardParameters} * to configure the parser, many of which are documented in {@link StandardParameters}
*/ */
void registerNamedParserSupplier(@NonNull String name, void registerNamedParserSupplier(
@NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser<C, ?>> supplier); @NonNull String name,
@NonNull Function<@NonNull ParserParameters, @NonNull ArgumentParser<C, ?>> supplier
);
/** /**
* Register a mapper that maps annotation instances to a map of parameter-object pairs * Register a mapper that maps annotation instances to a map of parameter-object pairs
@ -71,9 +75,11 @@ public interface ParserRegistry<C> {
* @param <A> Annotation type * @param <A> Annotation type
* @param <T> Type of the object that the parser is retrieved for * @param <T> Type of the object that the parser is retrieved for
*/ */
<A extends Annotation, T> void registerAnnotationMapper(@NonNull Class<A> annotation, <A extends Annotation, T> void registerAnnotationMapper(
@NonNull Class<A> annotation,
@NonNull BiFunction<@NonNull A, @NonNull TypeToken<?>, @NonNull BiFunction<@NonNull A, @NonNull TypeToken<?>,
@NonNull ParserParameters> mapper); @NonNull ParserParameters> mapper
);
/** /**
* Parse annotations into {@link ParserParameters} * Parse annotations into {@link ParserParameters}
@ -82,8 +88,10 @@ public interface ParserRegistry<C> {
* @param annotations The annotations to be parsed * @param annotations The annotations to be parsed
* @return Parsed parameters * @return Parsed parameters
*/ */
@NonNull ParserParameters parseAnnotations(@NonNull TypeToken<?> parsingType, @NonNull ParserParameters parseAnnotations(
@NonNull Collection<? extends Annotation> annotations); @NonNull TypeToken<?> parsingType,
@NonNull Collection<? extends Annotation> annotations
);
/** /**
* Attempt to create a {@link ArgumentParser} for a specified type, using * Attempt to create a {@link ArgumentParser} for a specified type, using
@ -94,8 +102,10 @@ public interface ParserRegistry<C> {
* @param <T> Generic type * @param <T> Generic type
* @return Parser, if one can be created * @return Parser, if one can be created
*/ */
<T> @NonNull Optional<ArgumentParser<C, T>> createParser(@NonNull TypeToken<T> type, <T> @NonNull Optional<ArgumentParser<C, T>> createParser(
@NonNull ParserParameters parserParameters); @NonNull TypeToken<T> type,
@NonNull ParserParameters parserParameters
);
/** /**
* Attempt to create a {@link ArgumentParser} for a specified type, using * Attempt to create a {@link ArgumentParser} for a specified type, using
@ -106,7 +116,9 @@ public interface ParserRegistry<C> {
* @param <T> Generic type * @param <T> Generic type
* @return Parser, if one can be created * @return Parser, if one can be created
*/ */
<T> @NonNull Optional<ArgumentParser<C, T>> createParser(@NonNull String name, <T> @NonNull Optional<ArgumentParser<C, T>> createParser(
@NonNull ParserParameters parserParameters); @NonNull String name,
@NonNull ParserParameters parserParameters
);
} }

View file

@ -63,8 +63,10 @@ public final class StandardParameters {
private StandardParameters() { private StandardParameters() {
} }
private static <T> @NonNull ParserParameter<T> create(final @NonNull String key, private static <T> @NonNull ParserParameter<T> create(
final @NonNull TypeToken<T> expectedType) { final @NonNull String key,
final @NonNull TypeToken<T> expectedType
) {
return new ParserParameter<>(key, expectedType); return new ParserParameter<>(key, expectedType);
} }

View file

@ -23,9 +23,8 @@
// //
package cloud.commandframework.arguments.parser; package cloud.commandframework.arguments.parser;
import cloud.commandframework.annotations.specifier.Greedy;
import cloud.commandframework.arguments.standard.UUIDArgument;
import cloud.commandframework.annotations.specifier.Completions; import cloud.commandframework.annotations.specifier.Completions;
import cloud.commandframework.annotations.specifier.Greedy;
import cloud.commandframework.annotations.specifier.Range; import cloud.commandframework.annotations.specifier.Range;
import cloud.commandframework.arguments.standard.BooleanArgument; import cloud.commandframework.arguments.standard.BooleanArgument;
import cloud.commandframework.arguments.standard.ByteArgument; import cloud.commandframework.arguments.standard.ByteArgument;
@ -36,6 +35,7 @@ import cloud.commandframework.arguments.standard.FloatArgument;
import cloud.commandframework.arguments.standard.IntegerArgument; import cloud.commandframework.arguments.standard.IntegerArgument;
import cloud.commandframework.arguments.standard.ShortArgument; import cloud.commandframework.arguments.standard.ShortArgument;
import cloud.commandframework.arguments.standard.StringArgument; import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.arguments.standard.UUIDArgument;
import io.leangen.geantyref.GenericTypeReflector; import io.leangen.geantyref.GenericTypeReflector;
import io.leangen.geantyref.TypeToken; import io.leangen.geantyref.TypeToken;
import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.NonNull;
@ -86,20 +86,30 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
/* Register standard types */ /* Register standard types */
this.registerParserSupplier(TypeToken.get(Byte.class), options -> this.registerParserSupplier(TypeToken.get(Byte.class), options ->
new ByteArgument.ByteParser<C>((byte) options.get(StandardParameters.RANGE_MIN, Byte.MIN_VALUE), new ByteArgument.ByteParser<C>(
(byte) options.get(StandardParameters.RANGE_MAX, Byte.MAX_VALUE))); (byte) options.get(StandardParameters.RANGE_MIN, Byte.MIN_VALUE),
(byte) options.get(StandardParameters.RANGE_MAX, Byte.MAX_VALUE)
));
this.registerParserSupplier(TypeToken.get(Short.class), options -> this.registerParserSupplier(TypeToken.get(Short.class), options ->
new ShortArgument.ShortParser<C>((short) options.get(StandardParameters.RANGE_MIN, Short.MIN_VALUE), new ShortArgument.ShortParser<C>(
(short) options.get(StandardParameters.RANGE_MAX, Short.MAX_VALUE))); (short) options.get(StandardParameters.RANGE_MIN, Short.MIN_VALUE),
(short) options.get(StandardParameters.RANGE_MAX, Short.MAX_VALUE)
));
this.registerParserSupplier(TypeToken.get(Integer.class), options -> this.registerParserSupplier(TypeToken.get(Integer.class), options ->
new IntegerArgument.IntegerParser<C>((int) options.get(StandardParameters.RANGE_MIN, Integer.MIN_VALUE), new IntegerArgument.IntegerParser<C>(
(int) options.get(StandardParameters.RANGE_MAX, Integer.MAX_VALUE))); (int) options.get(StandardParameters.RANGE_MIN, Integer.MIN_VALUE),
(int) options.get(StandardParameters.RANGE_MAX, Integer.MAX_VALUE)
));
this.registerParserSupplier(TypeToken.get(Float.class), options -> this.registerParserSupplier(TypeToken.get(Float.class), options ->
new FloatArgument.FloatParser<C>((float) options.get(StandardParameters.RANGE_MIN, Float.MIN_VALUE), new FloatArgument.FloatParser<C>(
(float) options.get(StandardParameters.RANGE_MAX, Float.MAX_VALUE))); (float) options.get(StandardParameters.RANGE_MIN, Float.MIN_VALUE),
(float) options.get(StandardParameters.RANGE_MAX, Float.MAX_VALUE)
));
this.registerParserSupplier(TypeToken.get(Double.class), options -> this.registerParserSupplier(TypeToken.get(Double.class), options ->
new DoubleArgument.DoubleParser<C>((double) options.get(StandardParameters.RANGE_MIN, Double.MIN_VALUE), new DoubleArgument.DoubleParser<C>(
(double) options.get(StandardParameters.RANGE_MAX, Double.MAX_VALUE))); (double) options.get(StandardParameters.RANGE_MIN, Double.MIN_VALUE),
(double) options.get(StandardParameters.RANGE_MAX, Double.MAX_VALUE)
));
this.registerParserSupplier(TypeToken.get(Character.class), options -> new CharArgument.CharacterParser<C>()); this.registerParserSupplier(TypeToken.get(Character.class), options -> new CharArgument.CharacterParser<C>());
/* Make this one less awful */ /* Make this one less awful */
this.registerParserSupplier(TypeToken.get(String.class), options -> { this.registerParserSupplier(TypeToken.get(String.class), options -> {
@ -109,37 +119,50 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
: StringArgument.StringMode.SINGLE; : StringArgument.StringMode.SINGLE;
return new StringArgument.StringParser<C>( return new StringArgument.StringParser<C>(
stringMode, stringMode,
(context, s) -> Arrays.asList(options.get(StandardParameters.COMPLETIONS, new String[0]))); (context, s) -> Arrays.asList(options.get(StandardParameters.COMPLETIONS, new String[0]))
);
}); });
/* Add options to this */ /* Add options to this */
this.registerParserSupplier(TypeToken.get(Boolean.class), options -> new BooleanArgument.BooleanParser<>(false)); this.registerParserSupplier(TypeToken.get(Boolean.class), options -> new BooleanArgument.BooleanParser<>(false));
this.registerParserSupplier(TypeToken.get(UUID.class), options -> new UUIDArgument.UUIDParser<>()); this.registerParserSupplier(TypeToken.get(UUID.class), options -> new UUIDArgument.UUIDParser<>());
} }
private static boolean isPrimitive(final @NonNull TypeToken<?> type) {
return GenericTypeReflector.erase(type.getType()).isPrimitive();
}
@Override @Override
public <T> void registerParserSupplier(final @NonNull TypeToken<T> type, public <T> void registerParserSupplier(
final @NonNull TypeToken<T> type,
final @NonNull Function<@NonNull ParserParameters, final @NonNull Function<@NonNull ParserParameters,
@NonNull ArgumentParser<C, ?>> supplier) { @NonNull ArgumentParser<C, ?>> supplier
) {
this.parserSuppliers.put(type, supplier); this.parserSuppliers.put(type, supplier);
} }
@Override @Override
public void registerNamedParserSupplier(final @NonNull String name, public void registerNamedParserSupplier(
final @NonNull String name,
final @NonNull Function<@NonNull ParserParameters, final @NonNull Function<@NonNull ParserParameters,
@NonNull ArgumentParser<C, ?>> supplier) { @NonNull ArgumentParser<C, ?>> supplier
) {
this.namedParsers.put(name, supplier); this.namedParsers.put(name, supplier);
} }
@Override @Override
public <A extends Annotation, T> void registerAnnotationMapper(final @NonNull Class<A> annotation, public <A extends Annotation, T> void registerAnnotationMapper(
final @NonNull Class<A> annotation,
final @NonNull BiFunction<@NonNull A, @NonNull TypeToken<?>, final @NonNull BiFunction<@NonNull A, @NonNull TypeToken<?>,
@NonNull ParserParameters> mapper) { @NonNull ParserParameters> mapper
) {
this.annotationMappers.put(annotation, mapper); this.annotationMappers.put(annotation, mapper);
} }
@Override @Override
public @NonNull ParserParameters parseAnnotations(final @NonNull TypeToken<?> parsingType, public @NonNull ParserParameters parseAnnotations(
final @NonNull Collection<@NonNull ? extends Annotation> annotations) { final @NonNull TypeToken<?> parsingType,
final @NonNull Collection<@NonNull ? extends Annotation> annotations
) {
final ParserParameters parserParameters = new ParserParameters(); final ParserParameters parserParameters = new ParserParameters();
annotations.forEach(annotation -> { annotations.forEach(annotation -> {
// noinspection all // noinspection all
@ -155,8 +178,10 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
} }
@Override @Override
public <T> @NonNull Optional<ArgumentParser<C, T>> createParser(final @NonNull TypeToken<T> type, public <T> @NonNull Optional<ArgumentParser<C, T>> createParser(
final @NonNull ParserParameters parserParameters) { final @NonNull TypeToken<T> type,
final @NonNull ParserParameters parserParameters
) {
final TypeToken<?> actualType; final TypeToken<?> actualType;
if (GenericTypeReflector.erase(type.getType()).isPrimitive()) { if (GenericTypeReflector.erase(type.getType()).isPrimitive()) {
actualType = TypeToken.get(PRIMITIVE_MAPPINGS.get(GenericTypeReflector.erase(type.getType()))); actualType = TypeToken.get(PRIMITIVE_MAPPINGS.get(GenericTypeReflector.erase(type.getType())));
@ -180,8 +205,10 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
} }
@Override @Override
public <T> @NonNull Optional<ArgumentParser<C, T>> createParser(final @NonNull String name, public <T> @NonNull Optional<ArgumentParser<C, T>> createParser(
final @NonNull ParserParameters parserParameters) { final @NonNull String name,
final @NonNull ParserParameters parserParameters
) {
final Function<ParserParameters, ArgumentParser<C, ?>> producer = this.namedParsers.get(name); final Function<ParserParameters, ArgumentParser<C, ?>> producer = this.namedParsers.get(name);
if (producer == null) { if (producer == null) {
return Optional.empty(); return Optional.empty();
@ -191,12 +218,6 @@ public final class StandardParserRegistry<C> implements ParserRegistry<C> {
return Optional.of(parser); return Optional.of(parser);
} }
private static boolean isPrimitive(final @NonNull TypeToken<?> type) {
return GenericTypeReflector.erase(type.getType()).isPrimitive();
}
private static final class RangeMapper<T> implements BiFunction<@NonNull Range, @NonNull TypeToken<?>, private static final class RangeMapper<T> implements BiFunction<@NonNull Range, @NonNull TypeToken<?>,
@NonNull ParserParameters> { @NonNull ParserParameters> {

View file

@ -37,14 +37,17 @@ import java.util.function.BiFunction;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class BooleanArgument<C> extends CommandArgument<C, Boolean> { public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
private final boolean liberal; private final boolean liberal;
private BooleanArgument(final boolean required, private BooleanArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final boolean liberal, final boolean liberal,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new BooleanParser<>(liberal), defaultValue, Boolean.class, suggestionsProvider); super(required, name, new BooleanParser<>(liberal), defaultValue, Boolean.class, suggestionsProvider);
this.liberal = liberal; this.liberal = liberal;
} }
@ -90,8 +93,10 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Boolean> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Boolean> optional(
final boolean defaultBoolean) { final @NonNull String name,
final boolean defaultBoolean
) {
return BooleanArgument.<C>newBuilder(name).asOptionalWithDefault(Boolean.toString(defaultBoolean)).build(); return BooleanArgument.<C>newBuilder(name).asOptionalWithDefault(Boolean.toString(defaultBoolean)).build();
} }
@ -131,7 +136,8 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
@Override @Override
public @NonNull BooleanArgument<C> build() { public @NonNull BooleanArgument<C> build() {
return new BooleanArgument<>(this.isRequired(), this.getName(), this.liberal, return new BooleanArgument<>(this.isRequired(), this.getName(), this.liberal,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -154,8 +160,10 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
} }
@Override @Override
public @NonNull ArgumentParseResult<Boolean> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<Boolean> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -188,8 +196,10 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
if (!liberal) { if (!liberal) {
return Arrays.asList("TRUE", "FALSE"); return Arrays.asList("TRUE", "FALSE");
} }
@ -201,6 +211,7 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
public boolean isContextFree() { public boolean isContextFree() {
return true; return true;
} }
} }
@ -218,8 +229,10 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
* @param input String input * @param input String input
* @param liberal Liberal value * @param liberal Liberal value
*/ */
public BooleanParseException(final @NonNull String input, public BooleanParseException(
final boolean liberal) { final @NonNull String input,
final boolean liberal
) {
this.input = input; this.input = input;
this.liberal = liberal; this.liberal = liberal;
} }
@ -246,5 +259,7 @@ public final class BooleanArgument<C> extends CommandArgument<C, Boolean> {
public String getMessage() { public String getMessage() {
return String.format("Could not parse boolean from '%s'.", input); return String.format("Could not parse boolean from '%s'.", input);
} }
} }
} }

View file

@ -41,13 +41,15 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
private final byte min; private final byte min;
private final byte max; private final byte max;
private ByteArgument(final boolean required, private ByteArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final byte min, final byte min,
final byte max, final byte max,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new ByteParser<>(min, max), defaultValue, Byte.class, suggestionsProvider); super(required, name, new ByteParser<>(min, max), defaultValue, Byte.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -94,8 +96,10 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Byte> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Byte> optional(
final byte defaultNum) { final @NonNull String name,
final byte defaultNum
) {
return ByteArgument.<C>newBuilder(name).asOptionalWithDefault(Byte.toString(defaultNum)).build(); return ByteArgument.<C>newBuilder(name).asOptionalWithDefault(Byte.toString(defaultNum)).build();
} }
@ -156,7 +160,8 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
@Override @Override
public @NonNull ByteArgument<C> build() { public @NonNull ByteArgument<C> build() {
return new ByteArgument<>(this.isRequired(), this.getName(), this.min, this.max, return new ByteArgument<>(this.isRequired(), this.getName(), this.min, this.max,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -180,7 +185,8 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
@Override @Override
public @NonNull ArgumentParseResult<Byte> parse( public @NonNull ArgumentParseResult<Byte> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -189,16 +195,19 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
final byte value = Byte.parseByte(input); final byte value = Byte.parseByte(input);
if (value < this.min || value > this.max) { if (value < this.min || value > this.max) {
return ArgumentParseResult.failure( return ArgumentParseResult.failure(
new ByteParseException(input, new ByteParseException(
input,
this.min, this.min,
this.max)); this.max
));
} }
inputQueue.remove(); inputQueue.remove();
return ArgumentParseResult.success(value); return ArgumentParseResult.success(value);
} catch (final Exception e) { } catch (final Exception e) {
return ArgumentParseResult.failure( return ArgumentParseResult.failure(
new ByteParseException(input, this.min, new ByteParseException(input, this.min,
this.max)); this.max
));
} }
} }
@ -208,8 +217,10 @@ public final class ByteArgument<C> extends CommandArgument<C, Byte> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input);
} }

View file

@ -37,11 +37,13 @@ import java.util.function.BiFunction;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class CharArgument<C> extends CommandArgument<C, Character> { public final class CharArgument<C> extends CommandArgument<C, Character> {
private CharArgument(final boolean required, private CharArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, final @Nullable BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new CharacterParser<>(), defaultValue, Character.class, suggestionsProvider); super(required, name, new CharacterParser<>(), defaultValue, Character.class, suggestionsProvider);
} }
@ -86,8 +88,10 @@ public final class CharArgument<C> extends CommandArgument<C, Character> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Character> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Character> optional(
final @NonNull String defaultNum) { final @NonNull String name,
final @NonNull String defaultNum
) {
return CharArgument.<C>newBuilder(name).asOptionalWithDefault(defaultNum).build(); return CharArgument.<C>newBuilder(name).asOptionalWithDefault(defaultNum).build();
} }
@ -106,7 +110,8 @@ public final class CharArgument<C> extends CommandArgument<C, Character> {
@Override @Override
public @NonNull CharArgument<C> build() { public @NonNull CharArgument<C> build() {
return new CharArgument<>(this.isRequired(), this.getName(), return new CharArgument<>(this.isRequired(), this.getName(),
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -115,8 +120,10 @@ public final class CharArgument<C> extends CommandArgument<C, Character> {
public static final class CharacterParser<C> implements ArgumentParser<C, Character> { public static final class CharacterParser<C> implements ArgumentParser<C, Character> {
@Override @Override
public @NonNull ArgumentParseResult<Character> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<Character> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -166,5 +173,7 @@ public final class CharArgument<C> extends CommandArgument<C, Character> {
public String getMessage() { public String getMessage() {
return String.format("'%s' is not a valid character.", input); return String.format("'%s' is not a valid character.", input);
} }
} }
} }

View file

@ -41,13 +41,15 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
private final double min; private final double min;
private final double max; private final double max;
private DoubleArgument(final boolean required, private DoubleArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final double min, final double min,
final double max, final double max,
final String defaultValue, final String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new DoubleParser<>(min, max), defaultValue, Double.class, suggestionsProvider); super(required, name, new DoubleParser<>(min, max), defaultValue, Double.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -94,8 +96,10 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Double> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Double> optional(
final double defaultNum) { final @NonNull String name,
final double defaultNum
) {
return DoubleArgument.<C>newBuilder(name).asOptionalWithDefault(Double.toString(defaultNum)).build(); return DoubleArgument.<C>newBuilder(name).asOptionalWithDefault(Double.toString(defaultNum)).build();
} }
@ -156,7 +160,8 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
@Override @Override
public @NonNull DoubleArgument<C> build() { public @NonNull DoubleArgument<C> build() {
return new DoubleArgument<>(this.isRequired(), this.getName(), this.min, this.max, return new DoubleArgument<>(this.isRequired(), this.getName(), this.min, this.max,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -180,7 +185,8 @@ public final class DoubleArgument<C> extends CommandArgument<C, Double> {
@Override @Override
public @NonNull ArgumentParseResult<Double> parse( public @NonNull ArgumentParseResult<Double> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));

View file

@ -45,12 +45,14 @@ import java.util.stream.Collectors;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> { public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
protected EnumArgument(final @NonNull Class<E> enumClass, protected EnumArgument(
final @NonNull Class<E> enumClass,
final boolean required, final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new EnumParser<>(enumClass), defaultValue, enumClass, suggestionsProvider); super(required, name, new EnumParser<>(enumClass), defaultValue, enumClass, suggestionsProvider);
} }
@ -65,7 +67,8 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
*/ */
public static <C, E extends Enum<E>> EnumArgument.@NonNull Builder<C, E> newBuilder( public static <C, E extends Enum<E>> EnumArgument.@NonNull Builder<C, E> newBuilder(
@NonNull final Class<E> enumClass, @NonNull final Class<E> enumClass,
final @NonNull String name) { final @NonNull String name
) {
return new EnumArgument.Builder<>(name, enumClass); return new EnumArgument.Builder<>(name, enumClass);
} }
@ -80,7 +83,8 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
*/ */
public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> of( public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> of(
final @NonNull Class<E> enumClass, final @NonNull Class<E> enumClass,
final @NonNull String name) { final @NonNull String name
) {
return EnumArgument.<C, E>newBuilder(enumClass, name).asRequired().build(); return EnumArgument.<C, E>newBuilder(enumClass, name).asRequired().build();
} }
@ -95,7 +99,8 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
*/ */
public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> optional( public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> optional(
final @NonNull Class<E> enumClass, final @NonNull Class<E> enumClass,
final @NonNull String name) { final @NonNull String name
) {
return EnumArgument.<C, E>newBuilder(enumClass, name).asOptional().build(); return EnumArgument.<C, E>newBuilder(enumClass, name).asOptional().build();
} }
@ -112,7 +117,8 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> optional( public static <C, E extends Enum<E>> @NonNull CommandArgument<C, E> optional(
final @NonNull Class<E> enumClass, final @NonNull Class<E> enumClass,
final @NonNull String name, final @NonNull String name,
final @NonNull E defaultValue) { final @NonNull E defaultValue
) {
return EnumArgument.<C, E>newBuilder(enumClass, name).asOptionalWithDefault(defaultValue.name().toLowerCase()).build(); return EnumArgument.<C, E>newBuilder(enumClass, name).asOptionalWithDefault(defaultValue.name().toLowerCase()).build();
} }
@ -129,8 +135,10 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
@Override @Override
public @NonNull CommandArgument<C, E> build() { public @NonNull CommandArgument<C, E> build() {
return new EnumArgument<>(this.enumClass, this.isRequired(), this.getName(), return new EnumArgument<>(this.enumClass, this.isRequired(), this.getName(),
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -150,8 +158,10 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
} }
@Override @Override
public @NonNull ArgumentParseResult<E> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<E> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -168,8 +178,10 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return EnumSet.allOf(this.enumClass).stream().map(e -> e.name().toLowerCase()).collect(Collectors.toList()); return EnumSet.allOf(this.enumClass).stream().map(e -> e.name().toLowerCase()).collect(Collectors.toList());
} }
@ -177,6 +189,7 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
public boolean isContextFree() { public boolean isContextFree() {
return true; return true;
} }
} }
@ -191,8 +204,10 @@ public class EnumArgument<C, E extends Enum<E>> extends CommandArgument<C, E> {
* @param input Input * @param input Input
* @param enumClass Enum class * @param enumClass Enum class
*/ */
public EnumParseException(final @NonNull String input, public EnumParseException(
final @NonNull Class<? extends Enum<?>> enumClass) { final @NonNull String input,
final @NonNull Class<? extends Enum<?>> enumClass
) {
this.input = input; this.input = input;
this.enumClass = enumClass; this.enumClass = enumClass;
} }

View file

@ -41,13 +41,15 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
private final float min; private final float min;
private final float max; private final float max;
private FloatArgument(final boolean required, private FloatArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final float min, final float min,
final float max, final float max,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, final @Nullable BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new FloatParser<>(min, max), defaultValue, Float.class, suggestionsProvider); super(required, name, new FloatParser<>(min, max), defaultValue, Float.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -94,8 +96,10 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Float> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Float> optional(
final float defaultNum) { final @NonNull String name,
final float defaultNum
) {
return FloatArgument.<C>newBuilder(name).asOptionalWithDefault(Float.toString(defaultNum)).build(); return FloatArgument.<C>newBuilder(name).asOptionalWithDefault(Float.toString(defaultNum)).build();
} }
@ -156,7 +160,8 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
@Override @Override
public @NonNull FloatArgument<C> build() { public @NonNull FloatArgument<C> build() {
return new FloatArgument<>(this.isRequired(), this.getName(), this.min, this.max, return new FloatArgument<>(this.isRequired(), this.getName(), this.min, this.max,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -180,7 +185,8 @@ public final class FloatArgument<C> extends CommandArgument<C, Float> {
@Override @Override
public @NonNull ArgumentParseResult<Float> parse( public @NonNull ArgumentParseResult<Float> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<String> inputQueue) { final @NonNull Queue<String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));

View file

@ -48,13 +48,15 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
private final int min; private final int min;
private final int max; private final int max;
private IntegerArgument(final boolean required, private IntegerArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final int min, final int min,
final int max, final int max,
final String defaultValue, final String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new IntegerParser<>(min, max), defaultValue, Integer.class, suggestionsProvider); super(required, name, new IntegerParser<>(min, max), defaultValue, Integer.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -101,8 +103,10 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Integer> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Integer> optional(
final int defaultNum) { final @NonNull String name,
final int defaultNum
) {
return IntegerArgument.<C>newBuilder(name).asOptionalWithDefault(Integer.toString(defaultNum)).build(); return IntegerArgument.<C>newBuilder(name).asOptionalWithDefault(Integer.toString(defaultNum)).build();
} }
@ -163,7 +167,8 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
@Override @Override
public @NonNull IntegerArgument<C> build() { public @NonNull IntegerArgument<C> build() {
return new IntegerArgument<>(this.isRequired(), this.getName(), this.min, this.max, return new IntegerArgument<>(this.isRequired(), this.getName(), this.min, this.max,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -209,7 +214,8 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
@Override @Override
public @NonNull ArgumentParseResult<Integer> parse( public @NonNull ArgumentParseResult<Integer> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -250,8 +256,10 @@ public final class IntegerArgument<C> extends CommandArgument<C, Integer> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return getSuggestions(this.min, this.max, input); return getSuggestions(this.min, this.max, input);
} }

View file

@ -41,13 +41,15 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
private final long min; private final long min;
private final long max; private final long max;
private LongArgument(final boolean required, private LongArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final long min, final long min,
final long max, final long max,
final String defaultValue, final String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new LongParser<>(min, max), defaultValue, Long.class, suggestionsProvider); super(required, name, new LongParser<>(min, max), defaultValue, Long.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -94,8 +96,10 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Long> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Long> optional(
final long defaultNum) { final @NonNull String name,
final long defaultNum
) {
return LongArgument.<C>newBuilder(name).asOptionalWithDefault(Long.toString(defaultNum)).build(); return LongArgument.<C>newBuilder(name).asOptionalWithDefault(Long.toString(defaultNum)).build();
} }
@ -156,7 +160,8 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
@Override @Override
public @NonNull LongArgument<C> build() { public @NonNull LongArgument<C> build() {
return new LongArgument<>(this.isRequired(), this.getName(), this.min, return new LongArgument<>(this.isRequired(), this.getName(), this.min,
this.max, this.getDefaultValue(), this.getSuggestionsProvider()); this.max, this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -174,7 +179,8 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
@Override @Override
public @NonNull ArgumentParseResult<Long> parse( public @NonNull ArgumentParseResult<Long> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -197,8 +203,10 @@ public final class LongArgument<C> extends CommandArgument<C, Long> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input);
} }

View file

@ -41,13 +41,15 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
private final short min; private final short min;
private final short max; private final short max;
private ShortArgument(final boolean required, private ShortArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final short min, final short min,
final short max, final short max,
final String defaultValue, final String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String, final @Nullable BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<String>> suggestionsProvider) { @NonNull List<String>> suggestionsProvider
) {
super(required, name, new ShortParser<>(min, max), defaultValue, Short.class, suggestionsProvider); super(required, name, new ShortParser<>(min, max), defaultValue, Short.class, suggestionsProvider);
this.min = min; this.min = min;
this.max = max; this.max = max;
@ -94,8 +96,10 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, Short> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, Short> optional(
final short defaultNum) { final @NonNull String name,
final short defaultNum
) {
return ShortArgument.<C>newBuilder(name).asOptionalWithDefault(Short.toString(defaultNum)).build(); return ShortArgument.<C>newBuilder(name).asOptionalWithDefault(Short.toString(defaultNum)).build();
} }
@ -156,7 +160,8 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
@Override @Override
public @NonNull ShortArgument<C> build() { public @NonNull ShortArgument<C> build() {
return new ShortArgument<>(this.isRequired(), this.getName(), this.min, this.max, return new ShortArgument<>(this.isRequired(), this.getName(), this.min, this.max,
this.getDefaultValue(), this.getSuggestionsProvider()); this.getDefaultValue(), this.getSuggestionsProvider()
);
} }
} }
@ -180,7 +185,8 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
@Override @Override
public @NonNull ArgumentParseResult<Short> parse( public @NonNull ArgumentParseResult<Short> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -203,8 +209,10 @@ public final class ShortArgument<C> extends CommandArgument<C, Short> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input); return IntegerArgument.IntegerParser.getSuggestions(this.min, this.max, input);
} }

View file

@ -40,14 +40,17 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
private final StringMode stringMode; private final StringMode stringMode;
private StringArgument(final boolean required, private StringArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull StringMode stringMode, final @NonNull StringMode stringMode,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @NonNull BiFunction<@NonNull CommandContext<C>, @NonNull String, final @NonNull BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new StringParser<>(stringMode, suggestionsProvider), super(required, name, new StringParser<>(stringMode, suggestionsProvider),
defaultValue, String.class, suggestionsProvider); defaultValue, String.class, suggestionsProvider
);
this.stringMode = stringMode; this.stringMode = stringMode;
} }
@ -81,8 +84,10 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, String> of(final @NonNull String name, public static <C> @NonNull CommandArgument<C, String> of(
final @NonNull StringMode stringMode) { final @NonNull String name,
final @NonNull StringMode stringMode
) {
return StringArgument.<C>newBuilder(name).withMode(stringMode).asRequired().build(); return StringArgument.<C>newBuilder(name).withMode(stringMode).asRequired().build();
} }
@ -105,8 +110,10 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, String> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, String> optional(
final @NonNull StringMode stringMode) { final @NonNull String name,
final @NonNull StringMode stringMode
) {
return StringArgument.<C>newBuilder(name).withMode(stringMode).asOptional().build(); return StringArgument.<C>newBuilder(name).withMode(stringMode).asOptional().build();
} }
@ -118,8 +125,10 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created argument * @return Created argument
*/ */
public static <C> @NonNull CommandArgument<C, String> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, String> optional(
final @NonNull String defaultString) { final @NonNull String name,
final @NonNull String defaultString
) {
return StringArgument.<C>newBuilder(name).asOptionalWithDefault(defaultString).build(); return StringArgument.<C>newBuilder(name).asOptionalWithDefault(defaultString).build();
} }
@ -190,8 +199,10 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
* @param suggestionsProvider Suggestions provider * @param suggestionsProvider Suggestions provider
* @return Builder instance * @return Builder instance
*/ */
public @NonNull Builder<C> withSuggestionsProvider(final @NonNull BiFunction<@NonNull CommandContext<C>, public @NonNull Builder<C> withSuggestionsProvider(
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { final @NonNull BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider
) {
this.suggestionsProvider = suggestionsProvider; this.suggestionsProvider = suggestionsProvider;
return this; return this;
} }
@ -204,7 +215,8 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
@Override @Override
public @NonNull StringArgument<C> build() { public @NonNull StringArgument<C> build() {
return new StringArgument<>(this.isRequired(), this.getName(), this.stringMode, return new StringArgument<>(this.isRequired(), this.getName(), this.stringMode,
this.getDefaultValue(), this.suggestionsProvider); this.getDefaultValue(), this.suggestionsProvider
);
} }
} }
@ -221,16 +233,20 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
* @param stringMode String parsing mode * @param stringMode String parsing mode
* @param suggestionsProvider Suggestions provider * @param suggestionsProvider Suggestions provider
*/ */
public StringParser(final @NonNull StringMode stringMode, public StringParser(
final @NonNull StringMode stringMode,
final @NonNull BiFunction<@NonNull CommandContext<C>, @NonNull String, final @NonNull BiFunction<@NonNull CommandContext<C>, @NonNull String,
@NonNull List<@NonNull String>> suggestionsProvider) { @NonNull List<@NonNull String>> suggestionsProvider
) {
this.stringMode = stringMode; this.stringMode = stringMode;
this.suggestionsProvider = suggestionsProvider; this.suggestionsProvider = suggestionsProvider;
} }
@Override @Override
public @NonNull ArgumentParseResult<String> parse(final @NonNull CommandContext<C> commandContext, public @NonNull ArgumentParseResult<String> parse(
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -294,8 +310,10 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
} }
@Override @Override
public @NonNull List<@NonNull String> suggestions(final @NonNull CommandContext<C> commandContext, public @NonNull List<@NonNull String> suggestions(
final @NonNull String input) { final @NonNull CommandContext<C> commandContext,
final @NonNull String input
) {
return this.suggestionsProvider.apply(commandContext, input); return this.suggestionsProvider.apply(commandContext, input);
} }
@ -312,6 +330,7 @@ public final class StringArgument<C> extends CommandArgument<C, String> {
public @NonNull StringMode getStringMode() { public @NonNull StringMode getStringMode() {
return this.stringMode; return this.stringMode;
} }
} }

View file

@ -38,11 +38,13 @@ import java.util.function.BiFunction;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class UUIDArgument<C> extends CommandArgument<C, UUID> { public final class UUIDArgument<C> extends CommandArgument<C, UUID> {
private UUIDArgument(final boolean required, private UUIDArgument(
final boolean required,
final @NonNull String name, final @NonNull String name,
final @NonNull String defaultValue, final @NonNull String defaultValue,
final @Nullable BiFunction<@NonNull CommandContext<C>, final @Nullable BiFunction<@NonNull CommandContext<C>,
@NonNull String, @NonNull List<@NonNull String>> suggestionsProvider) { @NonNull String, @NonNull List<@NonNull String>> suggestionsProvider
) {
super(required, name, new UUIDParser<>(), defaultValue, UUID.class, suggestionsProvider); super(required, name, new UUIDParser<>(), defaultValue, UUID.class, suggestionsProvider);
} }
@ -87,8 +89,10 @@ public final class UUIDArgument<C> extends CommandArgument<C, UUID> {
* @param <C> Command sender type * @param <C> Command sender type
* @return Created component * @return Created component
*/ */
public static <C> @NonNull CommandArgument<C, UUID> optional(final @NonNull String name, public static <C> @NonNull CommandArgument<C, UUID> optional(
final @NonNull UUID defaultUUID) { final @NonNull String name,
final @NonNull UUID defaultUUID
) {
return UUIDArgument.<C>newBuilder(name).asOptionalWithDefault(defaultUUID.toString()).build(); return UUIDArgument.<C>newBuilder(name).asOptionalWithDefault(defaultUUID.toString()).build();
} }
@ -117,7 +121,8 @@ public final class UUIDArgument<C> extends CommandArgument<C, UUID> {
@Override @Override
public @NonNull ArgumentParseResult<UUID> parse( public @NonNull ArgumentParseResult<UUID> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -136,6 +141,7 @@ public final class UUIDArgument<C> extends CommandArgument<C, UUID> {
public boolean isContextFree() { public boolean isContextFree() {
return true; return true;
} }
} }
@ -156,5 +162,7 @@ public final class UUIDArgument<C> extends CommandArgument<C, UUID> {
public String getMessage() { public String getMessage() {
return String.format("Could not parse UUID from '%s'.", input); return String.format("Could not parse UUID from '%s'.", input);
} }
} }
} }

View file

@ -61,8 +61,10 @@ public final class CommandContext<C> {
* @param suggestions Whether or not the context is created for command suggestions * @param suggestions Whether or not the context is created for command suggestions
* @param commandSender Sender of the command * @param commandSender Sender of the command
*/ */
public CommandContext(final boolean suggestions, public CommandContext(
final @NonNull C commandSender) { final boolean suggestions,
final @NonNull C commandSender
) {
this.commandSender = commandSender; this.commandSender = commandSender;
this.suggestions = suggestions; this.suggestions = suggestions;
} }
@ -181,8 +183,10 @@ public final class CommandContext<C> {
* @param <T> Argument type * @param <T> Argument type
* @return Stored value, or supplied default value * @return Stored value, or supplied default value
*/ */
public <T> @Nullable T getOrDefault(final @NonNull CommandArgument<C, T> argument, public <T> @Nullable T getOrDefault(
final @Nullable T defaultValue) { final @NonNull CommandArgument<C, T> argument,
final @Nullable T defaultValue
) {
return this.<T>getOptional(argument.getName()).orElse(defaultValue); return this.<T>getOptional(argument.getName()).orElse(defaultValue);
} }
@ -194,8 +198,10 @@ public final class CommandContext<C> {
* @param <T> Argument type * @param <T> Argument type
* @return Argument, or supplied default value * @return Argument, or supplied default value
*/ */
public <T> @Nullable T getOrDefault(final @NonNull String key, public <T> @Nullable T getOrDefault(
final @Nullable T defaultValue) { final @NonNull String key,
final @Nullable T defaultValue
) {
return this.<T>getOptional(key).orElse(defaultValue); return this.<T>getOptional(key).orElse(defaultValue);
} }

View file

@ -51,9 +51,11 @@ public final class AmbiguousNodeException extends IllegalStateException {
* @param ambiguousNode Node that caused exception * @param ambiguousNode Node that caused exception
* @param children All children of the parent * @param children All children of the parent
*/ */
public AmbiguousNodeException(final @Nullable CommandArgument<?, ?> parentNode, public AmbiguousNodeException(
final @Nullable CommandArgument<?, ?> parentNode,
final @NonNull CommandArgument<?, ?> ambiguousNode, final @NonNull CommandArgument<?, ?> ambiguousNode,
final @NonNull List<@NonNull CommandArgument<?, ?>> children) { final @NonNull List<@NonNull CommandArgument<?, ?>> children
) {
this.parentNode = parentNode; this.parentNode = parentNode;
this.ambiguousNode = ambiguousNode; this.ambiguousNode = ambiguousNode;
this.children = children; this.children = children;

View file

@ -39,9 +39,11 @@ public class ArgumentParseException extends CommandParseException {
* @param commandSender Command sender * @param commandSender Command sender
* @param currentChain Chain leading up to the exception * @param currentChain Chain leading up to the exception
*/ */
public ArgumentParseException(final @NonNull Throwable throwable, public ArgumentParseException(
final @NonNull Throwable throwable,
final @NonNull Object commandSender, final @NonNull Object commandSender,
final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain) { final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain
) {
super(commandSender, currentChain); super(commandSender, currentChain);
this.cause = throwable; this.cause = throwable;
} }

View file

@ -44,8 +44,10 @@ public class CommandParseException extends IllegalArgumentException {
* @param commandSender Sender who executed the command * @param commandSender Sender who executed the command
* @param currentChain Chain leading up to the exception * @param currentChain Chain leading up to the exception
*/ */
protected CommandParseException(final @NonNull Object commandSender, protected CommandParseException(
final @NonNull List<CommandArgument<?, ?>> currentChain) { final @NonNull Object commandSender,
final @NonNull List<CommandArgument<?, ?>> currentChain
) {
this.commandSender = commandSender; this.commandSender = commandSender;
this.currentChain = currentChain; this.currentChain = currentChain;
} }

View file

@ -42,9 +42,11 @@ public final class InvalidCommandSenderException extends CommandParseException {
* @param requiredSender The sender type that is required * @param requiredSender The sender type that is required
* @param currentChain Chain leading up to the exception * @param currentChain Chain leading up to the exception
*/ */
public InvalidCommandSenderException(final @NonNull Object commandSender, public InvalidCommandSenderException(
final @NonNull Object commandSender,
final @NonNull Class<?> requiredSender, final @NonNull Class<?> requiredSender,
final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain) { final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain
) {
super(commandSender, currentChain); super(commandSender, currentChain);
this.requiredSender = requiredSender; this.requiredSender = requiredSender;
} }
@ -60,8 +62,11 @@ public final class InvalidCommandSenderException extends CommandParseException {
@Override @Override
public String getMessage() { public String getMessage() {
return String.format("%s is not allowed to execute that command. Must be of type %s", return String.format(
"%s is not allowed to execute that command. Must be of type %s",
getCommandSender().getClass().getSimpleName(), getCommandSender().getClass().getSimpleName(),
requiredSender.getSimpleName()); requiredSender.getSimpleName()
);
} }
} }

View file

@ -43,9 +43,11 @@ public class InvalidSyntaxException extends CommandParseException {
* @param commandSender Sender that sent the command * @param commandSender Sender that sent the command
* @param currentChain Chain leading up to issue * @param currentChain Chain leading up to issue
*/ */
public InvalidSyntaxException(final @NonNull String correctSyntax, public InvalidSyntaxException(
final @NonNull String correctSyntax,
final @NonNull Object commandSender, final @NonNull Object commandSender,
final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain) { final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain
) {
super(commandSender, currentChain); super(commandSender, currentChain);
this.correctSyntax = correctSyntax; this.correctSyntax = correctSyntax;
} }

View file

@ -46,9 +46,11 @@ public class NoPermissionException extends CommandParseException {
* @param commandSender Command sender * @param commandSender Command sender
* @param currentChain Chain leading up to the exception * @param currentChain Chain leading up to the exception
*/ */
public NoPermissionException(final @NonNull CommandPermission missingPermission, public NoPermissionException(
final @NonNull CommandPermission missingPermission,
final @NonNull Object commandSender, final @NonNull Object commandSender,
final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain) { final @NonNull List<@NonNull CommandArgument<?, ?>> currentChain
) {
super(commandSender, currentChain); super(commandSender, currentChain);
this.missingPermission = missingPermission; this.missingPermission = missingPermission;
} }

View file

@ -44,9 +44,11 @@ public final class NoSuchCommandException extends CommandParseException {
* @param currentChain Chain leading up to the exception * @param currentChain Chain leading up to the exception
* @param command Entered command (following the command chain) * @param command Entered command (following the command chain)
*/ */
public NoSuchCommandException(final @NonNull Object commandSender, public NoSuchCommandException(
final @NonNull Object commandSender,
final @NonNull List<CommandArgument<?, ?>> currentChain, final @NonNull List<CommandArgument<?, ?>> currentChain,
final @NonNull String command) { final @NonNull String command
) {
super(commandSender, currentChain); super(commandSender, currentChain);
this.suppliedCommand = command; this.suppliedCommand = command;
} }

View file

@ -38,9 +38,11 @@ public abstract class NumberParseException extends IllegalArgumentException {
* @param min Maximum value * @param min Maximum value
* @param max Minimum value * @param max Minimum value
*/ */
public NumberParseException(final @NonNull String input, public NumberParseException(
final @NonNull String input,
final @NonNull Number min, final @NonNull Number min,
final @NonNull Number max) { final @NonNull Number max
) {
this.input = input; this.input = input;
this.min = min; this.min = min;
this.max = max; this.max = max;

View file

@ -50,9 +50,11 @@ public final class AsynchronousCommandExecutionCoordinator<C> extends CommandExe
private final Executor executor; private final Executor executor;
private final boolean synchronizeParsing; private final boolean synchronizeParsing;
private AsynchronousCommandExecutionCoordinator(final @Nullable Executor executor, private AsynchronousCommandExecutionCoordinator(
final @Nullable Executor executor,
final boolean synchronizeParsing, final boolean synchronizeParsing,
final @NonNull CommandTree<C> commandTree) { final @NonNull CommandTree<C> commandTree
) {
super(commandTree); super(commandTree);
this.executor = executor == null ? ForkJoinPool.commonPool() : executor; this.executor = executor == null ? ForkJoinPool.commonPool() : executor;
this.synchronizeParsing = synchronizeParsing; this.synchronizeParsing = synchronizeParsing;
@ -70,8 +72,10 @@ public final class AsynchronousCommandExecutionCoordinator<C> extends CommandExe
} }
@Override @Override
public @NonNull CompletableFuture<CommandResult<C>> coordinateExecution(final @NonNull CommandContext<C> commandContext, public @NonNull CompletableFuture<CommandResult<C>> coordinateExecution(
final @NonNull Queue<@NonNull String> input) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> input
) {
final Consumer<Command<C>> commandConsumer = command -> { final Consumer<Command<C>> commandConsumer = command -> {
if (this.commandManager.postprocessContext(commandContext, command) == State.ACCEPTED) { if (this.commandManager.postprocessContext(commandContext, command) == State.ACCEPTED) {

View file

@ -74,8 +74,10 @@ public abstract class CommandExecutionCoordinator<C> {
* @param input Command input * @param input Command input
* @return Future that completes with the result * @return Future that completes with the result
*/ */
public abstract @NonNull CompletableFuture<CommandResult<C>> coordinateExecution(@NonNull CommandContext<C> commandContext, public abstract @NonNull CompletableFuture<CommandResult<C>> coordinateExecution(
@NonNull Queue<@NonNull String> input); @NonNull CommandContext<C> commandContext,
@NonNull Queue<@NonNull String> input
);
/** /**
* Get the command tree * Get the command tree
@ -100,8 +102,10 @@ public abstract class CommandExecutionCoordinator<C> {
} }
@Override @Override
public CompletableFuture<CommandResult<C>> coordinateExecution(final @NonNull CommandContext<C> commandContext, public CompletableFuture<CommandResult<C>> coordinateExecution(
final @NonNull Queue<@NonNull String> input) { final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> input
) {
final CompletableFuture<CommandResult<C>> completableFuture = new CompletableFuture<>(); final CompletableFuture<CommandResult<C>> completableFuture = new CompletableFuture<>();
try { try {
final @NonNull Pair<@Nullable Command<C>, @Nullable Exception> pair = final @NonNull Pair<@Nullable Command<C>, @Nullable Exception> pair =

View file

@ -37,8 +37,10 @@ import java.util.List;
public final class FilteringCommandSuggestionProcessor<C> implements CommandSuggestionProcessor<C> { public final class FilteringCommandSuggestionProcessor<C> implements CommandSuggestionProcessor<C> {
@Override @Override
public @NonNull List<@NonNull String> apply(final @NonNull CommandPreprocessingContext<C> context, public @NonNull List<@NonNull String> apply(
final @NonNull List<@NonNull String> strings) { final @NonNull CommandPreprocessingContext<C> context,
final @NonNull List<@NonNull String> strings
) {
final String input; final String input;
if (context.getInputQueue().isEmpty()) { if (context.getInputQueue().isEmpty()) {
input = ""; input = "";

View file

@ -45,8 +45,10 @@ public final class CommandPostprocessingContext<C> {
* @param commandContext Command context * @param commandContext Command context
* @param command Command instance * @param command Command instance
*/ */
public CommandPostprocessingContext(final @NonNull CommandContext<@NonNull C> commandContext, public CommandPostprocessingContext(
final @NonNull Command<@NonNull C> command) { final @NonNull CommandContext<@NonNull C> commandContext,
final @NonNull Command<@NonNull C> command
) {
this.commandContext = commandContext; this.commandContext = commandContext;
this.command = command; this.command = command;
} }

View file

@ -31,4 +31,5 @@ import cloud.commandframework.services.types.ConsumerService;
* @param <C> Command sender type * @param <C> Command sender type
*/ */
public interface CommandPostprocessor<C> extends ConsumerService<CommandPostprocessingContext<C>> { public interface CommandPostprocessor<C> extends ConsumerService<CommandPostprocessingContext<C>> {
} }

View file

@ -45,8 +45,10 @@ public final class CommandPreprocessingContext<C> {
* @param commandContext Command context * @param commandContext Command context
* @param inputQueue Command input as supplied by sender * @param inputQueue Command input as supplied by sender
*/ */
public CommandPreprocessingContext(final @NonNull CommandContext<C> commandContext, public CommandPreprocessingContext(
final @NonNull LinkedList<@NonNull String> inputQueue) { final @NonNull CommandContext<C> commandContext,
final @NonNull LinkedList<@NonNull String> inputQueue
) {
this.commandContext = commandContext; this.commandContext = commandContext;
this.inputQueue = inputQueue; this.inputQueue = inputQueue;
} }

View file

@ -35,4 +35,5 @@ import cloud.commandframework.services.types.ConsumerService;
* @param <C> Command sender type * @param <C> Command sender type
*/ */
public interface CommandPreprocessor<C> extends ConsumerService<CommandPreprocessingContext<C>> { public interface CommandPreprocessor<C> extends ConsumerService<CommandPreprocessingContext<C>> {
} }

View file

@ -72,10 +72,12 @@ public class CommandConfirmationManager<C> {
* @param notifier Notifier that gets called when a command gets added to the queue * @param notifier Notifier that gets called when a command gets added to the queue
* @param errorNotifier Notifier that gets called when someone tries to confirm a command with nothing in the queue * @param errorNotifier Notifier that gets called when someone tries to confirm a command with nothing in the queue
*/ */
public CommandConfirmationManager(final long timeout, public CommandConfirmationManager(
final long timeout,
final @NonNull TimeUnit timeoutTimeUnit, final @NonNull TimeUnit timeoutTimeUnit,
final @NonNull Consumer<@NonNull CommandPostprocessingContext<C>> notifier, final @NonNull Consumer<@NonNull CommandPostprocessingContext<C>> notifier,
final @NonNull Consumer<@NonNull C> errorNotifier) { final @NonNull Consumer<@NonNull C> errorNotifier
) {
this.notifier = notifier; this.notifier = notifier;
this.errorNotifier = errorNotifier; this.errorNotifier = errorNotifier;
this.pendingCommands = new LinkedHashMap<C, Pair<CommandPostprocessingContext<C>, Long>>() { this.pendingCommands = new LinkedHashMap<C, Pair<CommandPostprocessingContext<C>, Long>>() {

View file

@ -121,8 +121,10 @@ public class SimpleCommandMeta extends CommandMeta {
* @param value Value * @param value Value
* @return Builder instance * @return Builder instance
*/ */
public @NonNull Builder with(final @NonNull String key, public @NonNull Builder with(
final @NonNull String value) { final @NonNull String key,
final @NonNull String value
) {
this.map.put(key, value); this.map.put(key, value);
return this; return this;
} }

View file

@ -38,8 +38,10 @@ public class Pair<U, V> implements Tuple {
private final U first; private final U first;
private final V second; private final V second;
protected Pair(final U first, protected Pair(
final V second) { final U first,
final V second
) {
this.first = first; this.first = first;
this.second = second; this.second = second;
} }
@ -53,8 +55,10 @@ public class Pair<U, V> implements Tuple {
* @param <V> Second type * @param <V> Second type
* @return Created pair * @return Created pair
*/ */
public static <U, V> @NonNull Pair<U, V> of(final U first, public static <U, V> @NonNull Pair<U, V> of(
final V second) { final U first,
final V second
) {
return new Pair<>(first, second); return new Pair<>(first, second);
} }

View file

@ -42,10 +42,12 @@ public class Quartet<U, V, W, X> implements Tuple {
private final W third; private final W third;
private final X fourth; private final X fourth;
protected Quartet(final @NonNull U first, protected Quartet(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth) { final @NonNull X fourth
) {
this.first = first; this.first = first;
this.second = second; this.second = second;
this.third = third; this.third = third;
@ -65,10 +67,12 @@ public class Quartet<U, V, W, X> implements Tuple {
* @param <X> Fourth type * @param <X> Fourth type
* @return Created quartet * @return Created quartet
*/ */
public static <U, V, W, X> @NonNull Quartet<@NonNull U, @NonNull V, @NonNull W, @NonNull X> of(final @NonNull U first, public static <U, V, W, X> @NonNull Quartet<@NonNull U, @NonNull V, @NonNull W, @NonNull X> of(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth) { final @NonNull X fourth
) {
return new Quartet<>(first, second, third, fourth); return new Quartet<>(first, second, third, fourth);
} }

View file

@ -44,11 +44,13 @@ public class Quintet<U, V, W, X, Y> implements Tuple {
private final X fourth; private final X fourth;
private final Y fifth; private final Y fifth;
protected Quintet(final @NonNull U first, protected Quintet(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth, final @NonNull X fourth,
final @NonNull Y fifth) { final @NonNull Y fifth
) {
this.first = first; this.first = first;
this.second = second; this.second = second;
this.third = third; this.third = third;
@ -76,7 +78,8 @@ public class Quintet<U, V, W, X, Y> implements Tuple {
final @NonNull V second, final @NonNull V second,
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth, final @NonNull X fourth,
final @NonNull Y fifth) { final @NonNull Y fifth
) {
return new Quintet<>(first, second, third, fourth, fifth); return new Quintet<>(first, second, third, fourth, fifth);
} }

View file

@ -46,12 +46,14 @@ public class Sextet<U, V, W, X, Y, Z> implements Tuple {
private final Y fifth; private final Y fifth;
private final Z sixth; private final Z sixth;
protected Sextet(final @NonNull U first, protected Sextet(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth, final @NonNull X fourth,
final @NonNull Y fifth, final @NonNull Y fifth,
final @NonNull Z sixth) { final @NonNull Z sixth
) {
this.first = first; this.first = first;
this.second = second; this.second = second;
this.third = third; this.third = third;
@ -83,7 +85,8 @@ public class Sextet<U, V, W, X, Y, Z> implements Tuple {
final @NonNull W third, final @NonNull W third,
final @NonNull X fourth, final @NonNull X fourth,
final @NonNull Y fifth, final @NonNull Y fifth,
final @NonNull Z sixth) { final @NonNull Z sixth
) {
return new Sextet<>(first, second, third, fourth, fifth, sixth); return new Sextet<>(first, second, third, fourth, fifth, sixth);
} }
@ -166,7 +169,8 @@ public class Sextet<U, V, W, X, Y, Z> implements Tuple {
@Override @Override
public final String toString() { public final String toString() {
return String.format("(%s, %s, %s, %s, %s, %s)", this.first, this.second, this.third, return String.format("(%s, %s, %s, %s, %s, %s)", this.first, this.second, this.third,
this.fourth, this.fifth, this.sixth); this.fourth, this.fifth, this.sixth
);
} }
@Override @Override

View file

@ -40,9 +40,11 @@ public class Triplet<U, V, W> implements Tuple {
private final V second; private final V second;
private final W third; private final W third;
protected Triplet(final @NonNull U first, protected Triplet(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third) { final @NonNull W third
) {
this.first = first; this.first = first;
this.second = second; this.second = second;
this.third = third; this.third = third;
@ -59,9 +61,11 @@ public class Triplet<U, V, W> implements Tuple {
* @param <W> Third type * @param <W> Third type
* @return Created triplet * @return Created triplet
*/ */
public static <U, V, W> @NonNull Triplet<@NonNull U, @NonNull V, @NonNull W> of(final @NonNull U first, public static <U, V, W> @NonNull Triplet<@NonNull U, @NonNull V, @NonNull W> of(
final @NonNull U first,
final @NonNull V second, final @NonNull V second,
final @NonNull W third) { final @NonNull W third
) {
return new Triplet<>(first, second, third); return new Triplet<>(first, second, third);
} }

View file

@ -52,7 +52,8 @@ class CommandHelpHandlerTest {
manager.command(manager.commandBuilder("vec") manager.command(manager.commandBuilder("vec")
.meta("description", "Takes in a vector") .meta("description", "Takes in a vector")
.argumentPair("vec", Pair.of("x", "y"), .argumentPair("vec", Pair.of("x", "y"),
Pair.of(Double.class, Double.class), Description.of("Vector")) Pair.of(Double.class, Double.class), Description.of("Vector")
)
.build()); .build());
} }
@ -88,8 +89,10 @@ class CommandHelpHandlerTest {
this.printTopic("vec", query4); this.printTopic("vec", query4);
} }
private void printTopic(final String query, private void printTopic(
final CommandHelpHandler.HelpTopic<TestCommandSender> helpTopic) { final String query,
final CommandHelpHandler.HelpTopic<TestCommandSender> helpTopic
) {
System.out.printf("Showing results for query: \"/%s\"\n", query); System.out.printf("Showing results for query: \"/%s\"\n", query);
if (helpTopic instanceof CommandHelpHandler.IndexHelpTopic) { if (helpTopic instanceof CommandHelpHandler.IndexHelpTopic) {
this.printIndexHelpTopic((CommandHelpHandler.IndexHelpTopic<TestCommandSender>) helpTopic); this.printIndexHelpTopic((CommandHelpHandler.IndexHelpTopic<TestCommandSender>) helpTopic);

View file

@ -23,8 +23,8 @@
// //
package cloud.commandframework; package cloud.commandframework;
import cloud.commandframework.execution.CommandResult;
import cloud.commandframework.context.CommandContext; import cloud.commandframework.context.CommandContext;
import cloud.commandframework.execution.CommandResult;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -73,7 +73,8 @@ final class CommandPerformanceTest {
double averageTime = elapsedTime / (double) amount; double averageTime = elapsedTime / (double) amount;
System.out.printf("Average literal parse time: %fns (%f ms) | %d samples & %d iterations\n", System.out.printf("Average literal parse time: %fns (%f ms) | %d samples & %d iterations\n",
averageTime, averageTime / 10e6, 101, 100000); averageTime, averageTime / 10e6, 101, 100000
);
} }
@Test @Test

View file

@ -57,8 +57,10 @@ class CommandPermissionTest {
} }
@Override @Override
public boolean hasPermission(final TestCommandSender sender, public boolean hasPermission(
final String permission) { final TestCommandSender sender,
final String permission
) {
return acceptOne && permission.equalsIgnoreCase("test.permission.four"); return acceptOne && permission.equalsIgnoreCase("test.permission.four");
} }
@ -66,6 +68,7 @@ class CommandPermissionTest {
public CommandMeta createDefaultCommandMeta() { public CommandMeta createDefaultCommandMeta() {
return SimpleCommandMeta.empty(); return SimpleCommandMeta.empty();
} }
} }
} }

View file

@ -33,8 +33,8 @@ import org.junit.jupiter.api.Test;
public class CommandPostProcessorTest { public class CommandPostProcessorTest {
private static final boolean[] state = new boolean[]{false};
private static CommandManager<TestCommandSender> manager; private static CommandManager<TestCommandSender> manager;
private static final boolean[] state = new boolean[] {false};
@BeforeAll @BeforeAll
static void newTree() { static void newTree() {
@ -47,7 +47,7 @@ public class CommandPostProcessorTest {
@Test @Test
void testPreprocessing() { void testPreprocessing() {
manager.executeCommand(new TestCommandSender(),"test").join(); manager.executeCommand(new TestCommandSender(), "test").join();
Assertions.assertEquals(false, state[0]); Assertions.assertEquals(false, state[0]);
} }

View file

@ -42,14 +42,16 @@ public class CommandPreProcessorTest {
manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty()) manager.command(manager.commandBuilder("test", SimpleCommandMeta.empty())
.argument(EnumArgument.of(SampleEnum.class, "enum")) .argument(EnumArgument.of(SampleEnum.class, "enum"))
.handler( .handler(
commandContext -> System.out.printf("enum = %s | integer = %d\n", commandContext -> System.out.printf(
"enum = %s | integer = %d\n",
commandContext.<SampleEnum>getOptional( commandContext.<SampleEnum>getOptional(
"enum").orElse( "enum").orElse(
SampleEnum.VALUE1), SampleEnum.VALUE1),
commandContext.<Integer>getOptional( commandContext.<Integer>getOptional(
"int").orElseThrow( "int").orElseThrow(
() -> new NullPointerException( () -> new NullPointerException(
"int")))) "int"))
))
.build()); .build());
manager.registerCommandPreProcessor(new SamplePreprocessor()); manager.registerCommandPreProcessor(new SamplePreprocessor());
} }

View file

@ -62,12 +62,14 @@ public class CommandSuggestionsTest {
manager.command(manager.commandBuilder("com") manager.command(manager.commandBuilder("com")
.argumentPair("com", Pair.of("x", "y"), Pair.of(Integer.class, TestEnum.class), .argumentPair("com", Pair.of("x", "y"), Pair.of(Integer.class, TestEnum.class),
Description.empty()) Description.empty()
)
.argument(IntegerArgument.of("int"))); .argument(IntegerArgument.of("int")));
manager.command(manager.commandBuilder("com2") manager.command(manager.commandBuilder("com2")
.argumentPair("com", Pair.of("x", "enum"), .argumentPair("com", Pair.of("x", "enum"),
Pair.of(Integer.class, TestEnum.class), Description.empty())); Pair.of(Integer.class, TestEnum.class), Description.empty()
));
manager.command(manager.commandBuilder("flags") manager.command(manager.commandBuilder("flags")
.argument(IntegerArgument.of("num")) .argument(IntegerArgument.of("num"))

View file

@ -55,12 +55,13 @@ class CommandTreeTest {
.command(manager.commandBuilder("test", SimpleCommandMeta.empty()) .command(manager.commandBuilder("test", SimpleCommandMeta.empty())
.literal("two").withPermission("no").build()) .literal("two").withPermission("no").build())
.command(manager.commandBuilder("test", Collections.singleton("other"), .command(manager.commandBuilder("test", Collections.singleton("other"),
SimpleCommandMeta.empty()) SimpleCommandMeta.empty()
)
.literal("opt", "öpt") .literal("opt", "öpt")
.argument(IntegerArgument .argument(IntegerArgument
.optional("num", EXPECTED_INPUT_NUMBER)) .optional("num", EXPECTED_INPUT_NUMBER))
.build()) .build())
.command(manager.commandBuilder("req").withSenderType(SpecificCommandSender.class).build()); .command(manager.commandBuilder("req").senderType(SpecificCommandSender.class).build());
/* Build command to test command proxying */ /* Build command to test command proxying */
final Command<TestCommandSender> toProxy = manager.commandBuilder("test") final Command<TestCommandSender> toProxy = manager.commandBuilder("test")
@ -86,7 +87,8 @@ class CommandTreeTest {
/* Build command for testing compound types */ /* Build command for testing compound types */
manager.command(manager.commandBuilder("pos") manager.command(manager.commandBuilder("pos")
.argument(ArgumentPair.of(manager, "pos", Pair.of("x", "y"), .argument(ArgumentPair.of(manager, "pos", Pair.of("x", "y"),
Pair.of(Integer.class, Integer.class)) Pair.of(Integer.class, Integer.class)
)
.simple()) .simple())
.handler(c -> { .handler(c -> {
final Pair<Integer, Integer> pair = c.get("pos"); final Pair<Integer, Integer> pair = c.get("pos");
@ -94,9 +96,12 @@ class CommandTreeTest {
})); }));
manager.command(manager.commandBuilder("vec") manager.command(manager.commandBuilder("vec")
.argument(ArgumentPair.of(manager, "vec", Pair.of("x", "y"), .argument(ArgumentPair.of(manager, "vec", Pair.of("x", "y"),
Pair.of(Double.class, Double.class)) Pair.of(Double.class, Double.class)
.withMapper(Vector2.class, )
(sender, pair) -> new Vector2(pair.getFirst(), pair.getSecond())) .withMapper(
Vector2.class,
(sender, pair) -> new Vector2(pair.getFirst(), pair.getSecond())
)
) )
.handler(c -> { .handler(c -> {
final Vector2 vector2 = c.get("vec"); final Vector2 vector2 = c.get("vec");
@ -122,17 +127,23 @@ class CommandTreeTest {
@Test @Test
void parse() { void parse() {
final Pair<Command<TestCommandSender>, Exception> command = manager.getCommandTree() final Pair<Command<TestCommandSender>, Exception> command = manager.getCommandTree()
.parse(new CommandContext<>( .parse(
new CommandContext<>(
new TestCommandSender()), new TestCommandSender()),
new LinkedList<>( new LinkedList<>(
Arrays.asList("test", Arrays.asList(
"one"))); "test",
"one"
))
);
Assertions.assertNotNull(command.getFirst()); Assertions.assertNotNull(command.getFirst());
Assertions.assertEquals(NoPermissionException.class, manager.getCommandTree() Assertions.assertEquals(NoPermissionException.class, manager.getCommandTree()
.parse(new CommandContext<>( .parse(
new CommandContext<>(
new TestCommandSender()), new TestCommandSender()),
new LinkedList<>( new LinkedList<>(
Arrays.asList("test", "two"))) Arrays.asList("test", "two"))
)
.getSecond().getClass()); .getSecond().getClass());
manager.getCommandTree() manager.getCommandTree()
.parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt"))) .parse(new CommandContext<>(new TestCommandSender()), new LinkedList<>(Arrays.asList("test", "opt")))
@ -224,6 +235,7 @@ class CommandTreeTest {
public static final class SpecificCommandSender extends TestCommandSender { public static final class SpecificCommandSender extends TestCommandSender {
} }

View file

@ -68,8 +68,10 @@ public class ParserRegistryTest {
final ParserParameters parserParameters = parserRegistry.parseAnnotations(parsedType, Collections.singleton(range)); final ParserParameters parserParameters = parserRegistry.parseAnnotations(parsedType, Collections.singleton(range));
Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MIN)); Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MIN));
Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MAX)); Assertions.assertTrue(parserParameters.has(StandardParameters.RANGE_MAX));
final ArgumentParser<TestCommandSender, ?> parser = parserRegistry.createParser(parsedType, final ArgumentParser<TestCommandSender, ?> parser = parserRegistry.createParser(
parserParameters) parsedType,
parserParameters
)
.orElseThrow( .orElseThrow(
() -> new NullPointerException( () -> new NullPointerException(
"No parser found")); "No parser found"));

View file

@ -48,9 +48,11 @@ public class JavacordCommand<C> implements MessageCreateListener {
private final CommandArgument<C, ?> command; private final CommandArgument<C, ?> command;
private final cloud.commandframework.Command<C> cloudCommand; private final cloud.commandframework.Command<C> cloudCommand;
JavacordCommand(final cloud.commandframework.@NonNull Command<C> cloudCommand, JavacordCommand(
final cloud.commandframework.@NonNull Command<C> cloudCommand,
final @NonNull CommandArgument<C, ?> command, final @NonNull CommandArgument<C, ?> command,
final @NonNull JavacordCommandManager<C> manager) { final @NonNull JavacordCommandManager<C> manager
) {
this.command = command; this.command = command;
this.manager = manager; this.manager = manager;
this.cloudCommand = cloudCommand; this.cloudCommand = cloudCommand;
@ -107,7 +109,8 @@ public class JavacordCommand<C> implements MessageCreateListener {
} }
if (throwable instanceof InvalidSyntaxException) { if (throwable instanceof InvalidSyntaxException) {
manager.handleException(sender, manager.handleException(
sender,
InvalidSyntaxException.class, InvalidSyntaxException.class,
(InvalidSyntaxException) throwable, (InvalidSyntaxException) throwable,
(c, e) -> commandSender.sendErrorMessage( (c, e) -> commandSender.sendErrorMessage(
@ -120,29 +123,35 @@ public class JavacordCommand<C> implements MessageCreateListener {
} }
if (throwable instanceof InvalidCommandSenderException) { if (throwable instanceof InvalidCommandSenderException) {
manager.handleException(sender, manager.handleException(
sender,
InvalidCommandSenderException.class, InvalidCommandSenderException.class,
(InvalidCommandSenderException) throwable, (InvalidCommandSenderException) throwable,
(c, e) -> commandSender.sendErrorMessage(e.getMessage())); (c, e) -> commandSender.sendErrorMessage(e.getMessage())
);
return; return;
} }
if (throwable instanceof NoPermissionException) { if (throwable instanceof NoPermissionException) {
manager.handleException(sender, manager.handleException(
sender,
NoPermissionException.class, NoPermissionException.class,
(NoPermissionException) throwable, (NoPermissionException) throwable,
(c, e) -> commandSender.sendErrorMessage(MESSAGE_NO_PERMS)); (c, e) -> commandSender.sendErrorMessage(MESSAGE_NO_PERMS)
);
return; return;
} }
if (throwable instanceof ArgumentParseException) { if (throwable instanceof ArgumentParseException) {
manager.handleException(sender, manager.handleException(
sender,
ArgumentParseException.class, ArgumentParseException.class,
(ArgumentParseException) throwable, (ArgumentParseException) throwable,
(c, e) -> commandSender.sendErrorMessage( (c, e) -> commandSender.sendErrorMessage(
"Invalid Command Argument: `" + e.getCause().getMessage() + "`")); "Invalid Command Argument: `" + e.getCause().getMessage() + "`")
);
return; return;
} }
@ -151,4 +160,5 @@ public class JavacordCommand<C> implements MessageCreateListener {
throwable.printStackTrace(); throwable.printStackTrace();
})); }));
} }
} }

View file

@ -59,7 +59,8 @@ public class JavacordCommandManager<C> extends CommandManager<C> {
* @param commandPermissionMapper Function used to check if a command sender has the permission to execute a command * @param commandPermissionMapper Function used to check if a command sender has the permission to execute a command
* @throws Exception If the construction of the manager fails * @throws Exception If the construction of the manager fails
*/ */
public JavacordCommandManager(final @NonNull DiscordApi discordApi, public JavacordCommandManager(
final @NonNull DiscordApi discordApi,
final @NonNull Function<@NonNull CommandTree<C>, final @NonNull Function<@NonNull CommandTree<C>,
@NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator, @NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator,
final @NonNull Function<@NonNull JavacordCommandSender, @NonNull C> commandSenderMapper, final @NonNull Function<@NonNull JavacordCommandSender, @NonNull C> commandSenderMapper,
@ -67,7 +68,8 @@ public class JavacordCommandManager<C> extends CommandManager<C> {
@NonNull JavacordCommandSender> backwardsCommandSenderMapper, @NonNull JavacordCommandSender> backwardsCommandSenderMapper,
final @NonNull Function<@NonNull C, @NonNull String> commandPrefixMapper, final @NonNull Function<@NonNull C, @NonNull String> commandPrefixMapper,
final @Nullable BiFunction<@NonNull C, final @Nullable BiFunction<@NonNull C,
@NonNull String, @NonNull Boolean> commandPermissionMapper) @NonNull String, @NonNull Boolean> commandPermissionMapper
)
throws Exception { throws Exception {
super(commandExecutionCoordinator, new JavacordRegistrationHandler<>()); super(commandExecutionCoordinator, new JavacordRegistrationHandler<>());
((JavacordRegistrationHandler<C>) this.getCommandRegistrationHandler()).initialize(this); ((JavacordRegistrationHandler<C>) this.getCommandRegistrationHandler()).initialize(this);
@ -81,7 +83,8 @@ public class JavacordCommandManager<C> extends CommandManager<C> {
@Override @Override
public final boolean hasPermission( public final boolean hasPermission(
final @NonNull C sender, final @NonNull String permission) { final @NonNull C sender, final @NonNull String permission
) {
if (permission.isEmpty()) { if (permission.isEmpty()) {
return true; return true;
} }
@ -131,4 +134,5 @@ public class JavacordCommandManager<C> extends CommandManager<C> {
public @NonNull DiscordApi getDiscordApi() { public @NonNull DiscordApi getDiscordApi() {
return this.discordApi; return this.discordApi;
} }
} }

View file

@ -26,9 +26,10 @@ package cloud.commandframework.javacord;
import cloud.commandframework.Command; import cloud.commandframework.Command;
import cloud.commandframework.arguments.CommandArgument; import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.internal.CommandRegistrationHandler; import cloud.commandframework.internal.CommandRegistrationHandler;
import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.checkerframework.checker.nullness.qual.NonNull;
final class JavacordRegistrationHandler<C> implements CommandRegistrationHandler { final class JavacordRegistrationHandler<C> implements CommandRegistrationHandler {
@ -53,7 +54,8 @@ final class JavacordRegistrationHandler<C> implements CommandRegistrationHandler
@SuppressWarnings("unchecked") final JavacordCommand<C> javacordCommand = new JavacordCommand<>( @SuppressWarnings("unchecked") final JavacordCommand<C> javacordCommand = new JavacordCommand<>(
(Command<C>) command, (Command<C>) command,
(CommandArgument<C, ?>) commandArgument, (CommandArgument<C, ?>) commandArgument,
this.javacordCommandManager); this.javacordCommandManager
);
this.registeredCommands.put(commandArgument, javacordCommand); this.registeredCommands.put(commandArgument, javacordCommand);
this.javacordCommandManager.getDiscordApi().addMessageCreateListener(javacordCommand); this.javacordCommandManager.getDiscordApi().addMessageCreateListener(javacordCommand);
return true; return true;

View file

@ -49,4 +49,5 @@ public class JavacordPrivateSender extends JavacordCommandSender {
.orElseThrow(() -> new UnsupportedOperationException( .orElseThrow(() -> new UnsupportedOperationException(
"PrivateTextChannel not present even though message was sent in a private channel")); "PrivateTextChannel not present even though message was sent in a private channel"));
} }
} }

View file

@ -62,4 +62,5 @@ public class JavacordServerSender extends JavacordCommandSender {
.orElseThrow(() -> new UnsupportedOperationException( .orElseThrow(() -> new UnsupportedOperationException(
"Server not present even though message was sent on a server")); "Server not present even though message was sent on a server"));
} }
} }

View file

@ -84,10 +84,13 @@ public class JDACommandListener<C> extends ListenerAdapter {
this.commandManager.handleException(sender, this.commandManager.handleException(sender,
InvalidSyntaxException.class, InvalidSyntaxException.class,
(InvalidSyntaxException) throwable, (c, e) -> { (InvalidSyntaxException) throwable, (c, e) -> {
this.sendMessage(event, this.sendMessage(
event,
MESSAGE_INVALID_SYNTAX + prefix + ((InvalidSyntaxException) throwable) MESSAGE_INVALID_SYNTAX + prefix + ((InvalidSyntaxException) throwable)
.getCorrectSyntax()); .getCorrectSyntax()
}); );
}
);
} else if (throwable instanceof InvalidCommandSenderException) { } else if (throwable instanceof InvalidCommandSenderException) {
this.commandManager.handleException(sender, this.commandManager.handleException(sender,
InvalidCommandSenderException.class, InvalidCommandSenderException.class,
@ -109,10 +112,13 @@ public class JDACommandListener<C> extends ListenerAdapter {
} else if (throwable instanceof ArgumentParseException) { } else if (throwable instanceof ArgumentParseException) {
this.commandManager.handleException(sender, ArgumentParseException.class, this.commandManager.handleException(sender, ArgumentParseException.class,
(ArgumentParseException) throwable, (c, e) -> { (ArgumentParseException) throwable, (c, e) -> {
this.sendMessage(event, this.sendMessage(
event,
"Invalid Command Argument: " + throwable.getCause() "Invalid Command Argument: " + throwable.getCause()
.getMessage()); .getMessage()
}); );
}
);
} else { } else {
this.sendMessage(event, throwable.getMessage()); this.sendMessage(event, throwable.getMessage());
} }
@ -122,4 +128,5 @@ public class JDACommandListener<C> extends ListenerAdapter {
private void sendMessage(final @NonNull MessageReceivedEvent event, final @NonNull String message) { private void sendMessage(final @NonNull MessageReceivedEvent event, final @NonNull String message) {
event.getChannel().sendMessage(message).queue(); event.getChannel().sendMessage(message).queue();
} }
} }

View file

@ -45,6 +45,7 @@ import java.util.function.Function;
* @param <C> Command sender type * @param <C> Command sender type
*/ */
public class JDACommandManager<C> extends CommandManager<C> { public class JDACommandManager<C> extends CommandManager<C> {
private final long botId; private final long botId;
private final Function<@NonNull C, @NonNull String> prefixMapper; private final Function<@NonNull C, @NonNull String> prefixMapper;
@ -63,12 +64,14 @@ public class JDACommandManager<C> extends CommandManager<C> {
* @param backwardsCommandSenderMapper Function that maps the command sender type to {@link MessageReceivedEvent} * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link MessageReceivedEvent}
* @throws InterruptedException If the jda instance does not ready correctly * @throws InterruptedException If the jda instance does not ready correctly
*/ */
public JDACommandManager(final @NonNull JDA jda, public JDACommandManager(
final @NonNull JDA jda,
final @NonNull Function<@NonNull C, @NonNull String> prefixMapper, final @NonNull Function<@NonNull C, @NonNull String> prefixMapper,
final @Nullable BiFunction<@NonNull C, @NonNull String, @NonNull Boolean> permissionMapper, final @Nullable BiFunction<@NonNull C, @NonNull String, @NonNull Boolean> permissionMapper,
final @NonNull Function<CommandTree<C>, CommandExecutionCoordinator<C>> commandExecutionCoordinator, final @NonNull Function<CommandTree<C>, CommandExecutionCoordinator<C>> commandExecutionCoordinator,
final @NonNull Function<@NonNull MessageReceivedEvent, @NonNull C> commandSenderMapper, final @NonNull Function<@NonNull MessageReceivedEvent, @NonNull C> commandSenderMapper,
final @NonNull Function<@NonNull C, @NonNull MessageReceivedEvent> backwardsCommandSenderMapper) final @NonNull Function<@NonNull C, @NonNull MessageReceivedEvent> backwardsCommandSenderMapper
)
throws InterruptedException { throws InterruptedException {
super(commandExecutionCoordinator, CommandRegistrationHandler.nullCommandRegistrationHandler()); super(commandExecutionCoordinator, CommandRegistrationHandler.nullCommandRegistrationHandler());
this.prefixMapper = prefixMapper; this.prefixMapper = prefixMapper;
@ -130,4 +133,5 @@ public class JDACommandManager<C> extends CommandManager<C> {
public final @NonNull CommandMeta createDefaultCommandMeta() { public final @NonNull CommandMeta createDefaultCommandMeta() {
return SimpleCommandMeta.empty(); return SimpleCommandMeta.empty();
} }
} }

View file

@ -31,6 +31,7 @@ import org.checkerframework.checker.nullness.qual.NonNull;
* Wrapper for {@link MessageReceivedEvent} * Wrapper for {@link MessageReceivedEvent}
*/ */
public class JDACommandSender { public class JDACommandSender {
private final MessageReceivedEvent event; private final MessageReceivedEvent event;
/** /**
@ -42,15 +43,6 @@ public class JDACommandSender {
this.event = event; this.event = event;
} }
/**
* Get the {@link MessageReceivedEvent}
*
* @return Message Received Event
*/
public @NonNull MessageReceivedEvent getEvent() {
return event;
}
/** /**
* Create a JDA Command Sender from a {@link MessageReceivedEvent} * Create a JDA Command Sender from a {@link MessageReceivedEvent}
* *
@ -64,4 +56,14 @@ public class JDACommandSender {
return new JDAGuildSender(event); return new JDAGuildSender(event);
} }
/**
* Get the {@link MessageReceivedEvent}
*
* @return Message Received Event
*/
public @NonNull MessageReceivedEvent getEvent() {
return event;
}
} }

View file

@ -34,4 +34,5 @@ public class JDAGuildSender extends JDACommandSender {
JDAGuildSender(final @NonNull MessageReceivedEvent event) { JDAGuildSender(final @NonNull MessageReceivedEvent event) {
super(event); super(event);
} }
} }

View file

@ -34,4 +34,5 @@ public class JDAPrivateSender extends JDACommandSender {
JDAPrivateSender(final @NonNull MessageReceivedEvent event) { JDAPrivateSender(final @NonNull MessageReceivedEvent event) {
super(event); super(event);
} }
} }

View file

@ -43,10 +43,13 @@ import java.util.Queue;
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public final class UserArgument<C> extends CommandArgument<C, User> { public final class UserArgument<C> extends CommandArgument<C, User> {
private final List<ParserMode> modes; private final List<ParserMode> modes;
private UserArgument(final boolean required, final @NonNull String name, private UserArgument(
final @NonNull JDA jda, final @NonNull List<ParserMode> modes) { final boolean required, final @NonNull String name,
final @NonNull JDA jda, final @NonNull List<ParserMode> modes
) {
super(required, name, new UserParser<>(jda, modes), User.class); super(required, name, new UserParser<>(jda, modes), User.class);
this.modes = modes; this.modes = modes;
} }
@ -105,6 +108,7 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
public static final class Builder<C> extends CommandArgument.Builder<C, User> { public static final class Builder<C> extends CommandArgument.Builder<C, User> {
private final JDA jda; private final JDA jda;
private List<ParserMode> modes = new ArrayList<>(); private List<ParserMode> modes = new ArrayList<>();
@ -138,6 +142,7 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
public static final class UserParser<C> implements ArgumentParser<C, User> { public static final class UserParser<C> implements ArgumentParser<C, User> {
private final JDA jda; private final JDA jda;
private final List<ParserMode> modes; private final List<ParserMode> modes;
@ -149,7 +154,8 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
@Override @Override
public @NonNull ArgumentParseResult<User> parse( public @NonNull ArgumentParseResult<User> parse(
final @NonNull CommandContext<C> commandContext, final @NonNull CommandContext<C> commandContext,
final @NonNull Queue<@NonNull String> inputQueue) { final @NonNull Queue<@NonNull String> inputQueue
) {
final String input = inputQueue.peek(); final String input = inputQueue.peek();
if (input == null) { if (input == null) {
return ArgumentParseResult.failure(new NullPointerException("No input was provided")); return ArgumentParseResult.failure(new NullPointerException("No input was provided"));
@ -218,6 +224,7 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
return ArgumentParseResult.success(user); return ArgumentParseResult.success(user);
} }
} }
} }
@ -242,10 +249,12 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
public final @NonNull String getInput() { public final @NonNull String getInput() {
return input; return input;
} }
} }
public static final class TooManyUsersFoundParseException extends UserParseException { public static final class TooManyUsersFoundParseException extends UserParseException {
/** /**
* Construct a new UUID parse exception * Construct a new UUID parse exception
* *
@ -259,10 +268,12 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
public @NonNull String getMessage() { public @NonNull String getMessage() {
return String.format("Too many users found for '%s'.", getInput()); return String.format("Too many users found for '%s'.", getInput());
} }
} }
public static final class UserNotFoundParseException extends UserParseException { public static final class UserNotFoundParseException extends UserParseException {
/** /**
* Construct a new UUID parse exception * Construct a new UUID parse exception
* *
@ -276,5 +287,7 @@ public final class UserArgument<C> extends CommandArgument<C, User> {
public @NonNull String getMessage() { public @NonNull String getMessage() {
return String.format("User not found for '%s'.", getInput()); return String.format("User not found for '%s'.", getInput());
} }
} }
} }

View file

@ -54,8 +54,10 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender> impl
* *
* @param executionCoordinatorFunction Function producing a new coordinator * @param executionCoordinatorFunction Function producing a new coordinator
*/ */
public JLineCommandManager(final @NonNull Function<CommandTree<JLineCommandSender>, public JLineCommandManager(
CommandExecutionCoordinator<JLineCommandSender>> executionCoordinatorFunction) { final @NonNull Function<CommandTree<JLineCommandSender>,
CommandExecutionCoordinator<JLineCommandSender>> executionCoordinatorFunction
) {
super(executionCoordinatorFunction, CommandRegistrationHandler.nullCommandRegistrationHandler()); super(executionCoordinatorFunction, CommandRegistrationHandler.nullCommandRegistrationHandler());
} }
@ -138,9 +140,11 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender> impl
} }
@Override @Override
public final void complete(final @NonNull LineReader lineReader, public final void complete(
final @NonNull LineReader lineReader,
final @NonNull ParsedLine parsedLine, final @NonNull ParsedLine parsedLine,
final @NonNull List<@NonNull Candidate> list) { final @NonNull List<@NonNull Candidate> list
) {
final String line = parsedLine.line(); final String line = parsedLine.line();
if (line == null || line.isEmpty() || !line.startsWith("/")) { if (line == null || line.isEmpty() || !line.startsWith("/")) {
System.out.println("Cannot suggest: empty line"); System.out.println("Cannot suggest: empty line");
@ -155,8 +159,10 @@ public class JLineCommandManager extends CommandManager<JLineCommandSender> impl
} }
@Override @Override
public final boolean hasPermission(final @NonNull JLineCommandSender sender, public final boolean hasPermission(
final @NonNull String permission) { final @NonNull JLineCommandSender sender,
final @NonNull String permission
) {
return true; return true;
} }

View file

@ -95,9 +95,10 @@ public final class CloudBrigadierManager<C, S> {
* @param commandManager Command manager * @param commandManager Command manager
* @param dummyContextProvider Provider of dummy context for completions * @param dummyContextProvider Provider of dummy context for completions
*/ */
public CloudBrigadierManager(final @NonNull CommandManager<C> commandManager, public CloudBrigadierManager(
final @NonNull Supplier<@NonNull CommandContext<C>> final @NonNull CommandManager<C> commandManager,
dummyContextProvider) { final @NonNull Supplier<@NonNull CommandContext<C>> dummyContextProvider
) {
this.mappers = new HashMap<>(); this.mappers = new HashMap<>();
this.defaultArgumentTypeSuppliers = new HashMap<>(); this.defaultArgumentTypeSuppliers = new HashMap<>();
this.commandManager = commandManager; this.commandManager = commandManager;
@ -199,10 +200,12 @@ public final class CloudBrigadierManager<C, S> {
* @param <K> cloud argument type * @param <K> cloud argument type
* @param <O> Brigadier argument type value * @param <O> Brigadier argument type value
*/ */
public <T, K extends ArgumentParser<C, T>, O> void registerMapping(final @NonNull TypeToken<K> argumentType, public <T, K extends ArgumentParser<C, T>, O> void registerMapping(
final @NonNull TypeToken<K> argumentType,
final boolean nativeSuggestions, final boolean nativeSuggestions,
final @NonNull Function<@NonNull ? extends K, final @NonNull Function<@NonNull ? extends K,
@NonNull ? extends ArgumentType<O>> mapper) { @NonNull ? extends ArgumentType<O>> mapper
) {
this.mappers.put(GenericTypeReflector.erase(argumentType.getType()), Pair.of(mapper, nativeSuggestions)); this.mappers.put(GenericTypeReflector.erase(argumentType.getType()), Pair.of(mapper, nativeSuggestions));
} }
@ -212,8 +215,10 @@ public final class CloudBrigadierManager<C, S> {
* @param clazz Type to map * @param clazz Type to map
* @param supplier Supplier that supplies the argument type * @param supplier Supplier that supplies the argument type
*/ */
public void registerDefaultArgumentTypeSupplier(final @NonNull Class<?> clazz, public void registerDefaultArgumentTypeSupplier(
final @NonNull Supplier<@Nullable ArgumentType<?>> supplier) { final @NonNull Class<?> clazz,
final @NonNull Supplier<@Nullable ArgumentType<?>> supplier
) {
this.defaultArgumentTypeSuppliers.put(clazz, supplier); this.defaultArgumentTypeSuppliers.put(clazz, supplier);
} }
@ -221,19 +226,23 @@ public final class CloudBrigadierManager<C, S> {
private <T, K extends ArgumentParser<?, ?>> @Nullable Pair<@NonNull ArgumentType<?>, @NonNull Boolean> getArgument( private <T, K extends ArgumentParser<?, ?>> @Nullable Pair<@NonNull ArgumentType<?>, @NonNull Boolean> getArgument(
final @NonNull TypeToken<?> valueType, final @NonNull TypeToken<?> valueType,
final @NonNull TypeToken<T> argumentType, final @NonNull TypeToken<T> argumentType,
final @NonNull K argument) { final @NonNull K argument
) {
final ArgumentParser<C, ?> commandArgument = (ArgumentParser<C, ?>) argument; final ArgumentParser<C, ?> commandArgument = (ArgumentParser<C, ?>) argument;
final Pair pair = this.mappers.get(GenericTypeReflector.erase(argumentType.getType())); final Pair pair = this.mappers.get(GenericTypeReflector.erase(argumentType.getType()));
if (pair == null || pair.getFirst() == null) { if (pair == null || pair.getFirst() == null) {
return this.createDefaultMapper(valueType, commandArgument); return this.createDefaultMapper(valueType, commandArgument);
} }
return Pair.of((ArgumentType<?>) ((Function) pair.getFirst()).apply(commandArgument), return Pair.of(
(boolean) pair.getSecond()); (ArgumentType<?>) ((Function) pair.getFirst()).apply(commandArgument),
(boolean) pair.getSecond()
);
} }
private <T, K extends ArgumentParser<C, T>> @NonNull Pair<@NonNull ArgumentType<?>, @NonNull Boolean> createDefaultMapper( private <T, K extends ArgumentParser<C, T>> @NonNull Pair<@NonNull ArgumentType<?>, @NonNull Boolean> createDefaultMapper(
final @NonNull TypeToken<?> clazz, final @NonNull TypeToken<?> clazz,
final @NonNull ArgumentParser<C, T> argument) { final @NonNull ArgumentParser<C, T> argument
) {
final Supplier<ArgumentType<?>> argumentTypeSupplier = this.defaultArgumentTypeSuppliers final Supplier<ArgumentType<?>> argumentTypeSupplier = this.defaultArgumentTypeSuppliers
.get(GenericTypeReflector.erase(clazz.getType())); .get(GenericTypeReflector.erase(clazz.getType()));
final @Nullable ArgumentType<?> defaultType; final @Nullable ArgumentType<?> defaultType;
@ -258,20 +267,24 @@ public final class CloudBrigadierManager<C, S> {
* @param executor Command executor * @param executor Command executor
* @return Literal command node * @return Literal command node
*/ */
public @NonNull LiteralCommandNode<S> createLiteralCommandNode(final @NonNull String label, public @NonNull LiteralCommandNode<S> createLiteralCommandNode(
final @NonNull String label,
final @NonNull Command<C> cloudCommand, final @NonNull Command<C> cloudCommand,
final @NonNull BiPredicate<@NonNull S, final @NonNull BiPredicate<@NonNull S,
@NonNull CommandPermission> permissionChecker, @NonNull CommandPermission> permissionChecker,
final boolean forceRegister, final boolean forceRegister,
final com.mojang.brigadier.@NonNull Command<S> executor) { final com.mojang.brigadier.@NonNull Command<S> executor
) {
final CommandTree.Node<CommandArgument<C, ?>> node = this.commandManager final CommandTree.Node<CommandArgument<C, ?>> node = this.commandManager
.getCommandTree().getNamedNode(cloudCommand.getArguments().get(0).getName()); .getCommandTree().getNamedNode(cloudCommand.getArguments().get(0).getName());
final SuggestionProvider<S> provider = (context, builder) -> this.buildSuggestions(node.getValue(), context, builder); final SuggestionProvider<S> provider = (context, builder) -> this.buildSuggestions(node.getValue(), context, builder);
final LiteralArgumentBuilder<S> literalArgumentBuilder = LiteralArgumentBuilder final LiteralArgumentBuilder<S> literalArgumentBuilder = LiteralArgumentBuilder
.<S>literal(label) .<S>literal(label)
.requires(sender -> permissionChecker.test(sender, (CommandPermission) node.getNodeMeta() .requires(sender -> permissionChecker.test(sender, (CommandPermission) node.getNodeMeta()
.getOrDefault("permission", .getOrDefault(
Permission.empty()))); "permission",
Permission.empty()
)));
if (forceRegister || (node.getValue() != null && node.getValue().getOwningCommand() != null)) { if (forceRegister || (node.getValue() != null && node.getValue().getOwningCommand() != null)) {
literalArgumentBuilder.executes(executor); literalArgumentBuilder.executes(executor);
} }
@ -279,7 +292,8 @@ public final class CloudBrigadierManager<C, S> {
final LiteralCommandNode<S> constructedRoot = literalArgumentBuilder.build(); final LiteralCommandNode<S> constructedRoot = literalArgumentBuilder.build();
for (final CommandTree.Node<CommandArgument<C, ?>> child : node.getChildren()) { for (final CommandTree.Node<CommandArgument<C, ?>> child : node.getChildren()) {
constructedRoot.addChild(this.constructCommandNode(forceRegister, child, constructedRoot.addChild(this.constructCommandNode(forceRegister, child,
permissionChecker, executor, provider).build()); permissionChecker, executor, provider
).build());
} }
return constructedRoot; return constructedRoot;
} }
@ -299,19 +313,25 @@ public final class CloudBrigadierManager<C, S> {
final @NonNull LiteralCommandNode<S> root, final @NonNull LiteralCommandNode<S> root,
final @NonNull SuggestionProvider<S> suggestionProvider, final @NonNull SuggestionProvider<S> suggestionProvider,
final com.mojang.brigadier.@NonNull Command<S> executor, final com.mojang.brigadier.@NonNull Command<S> executor,
final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker) { final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker
) {
final LiteralArgumentBuilder<S> literalArgumentBuilder = LiteralArgumentBuilder.<S>literal(root.getLiteral()) final LiteralArgumentBuilder<S> literalArgumentBuilder = LiteralArgumentBuilder.<S>literal(root.getLiteral())
.requires(sender -> permissionChecker.test(sender, .requires(sender -> permissionChecker.test(
sender,
(CommandPermission) cloudCommand.getNodeMeta() (CommandPermission) cloudCommand.getNodeMeta()
.getOrDefault("permission", .getOrDefault(
Permission.empty()))); "permission",
Permission.empty()
)
));
if (cloudCommand.getValue() != null && cloudCommand.getValue().getOwningCommand() != null) { if (cloudCommand.getValue() != null && cloudCommand.getValue().getOwningCommand() != null) {
literalArgumentBuilder.executes(executor); literalArgumentBuilder.executes(executor);
} }
final LiteralCommandNode<S> constructedRoot = literalArgumentBuilder.build(); final LiteralCommandNode<S> constructedRoot = literalArgumentBuilder.build();
for (final CommandTree.Node<CommandArgument<C, ?>> child : cloudCommand.getChildren()) { for (final CommandTree.Node<CommandArgument<C, ?>> child : cloudCommand.getChildren()) {
constructedRoot.addChild(this.constructCommandNode(false, child, permissionChecker, constructedRoot.addChild(this.constructCommandNode(false, child, permissionChecker,
executor, suggestionProvider).build()); executor, suggestionProvider
).build());
} }
return constructedRoot; return constructedRoot;
} }
@ -321,10 +341,10 @@ public final class CloudBrigadierManager<C, S> {
final CommandTree.@NonNull Node<CommandArgument<C, ?>> root, final CommandTree.@NonNull Node<CommandArgument<C, ?>> root,
final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker, final @NonNull BiPredicate<@NonNull S, @NonNull CommandPermission> permissionChecker,
final com.mojang.brigadier.@NonNull Command<S> executor, final com.mojang.brigadier.@NonNull Command<S> executor,
final SuggestionProvider<S> suggestionProvider) { final SuggestionProvider<S> suggestionProvider
) {
if (root.getValue() instanceof CompoundArgument) { if (root.getValue() instanceof CompoundArgument) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final CompoundArgument<?, C, ?> compoundArgument = (CompoundArgument<?, C, ?>) root.getValue();
final CompoundArgument<?, C, ?> compoundArgument = (CompoundArgument<?, C, ?>) root.getValue();
final Object[] parsers = compoundArgument.getParserTuple().toArray(); final Object[] parsers = compoundArgument.getParserTuple().toArray();
final Object[] types = compoundArgument.getTypes().toArray(); final Object[] types = compoundArgument.getTypes().toArray();
final Object[] names = compoundArgument.getNames().toArray(); final Object[] names = compoundArgument.getNames().toArray();
@ -334,18 +354,24 @@ public final class CloudBrigadierManager<C, S> {
for (int i = parsers.length - 1; i >= 0; i--) { for (int i = parsers.length - 1; i >= 0; i--) {
@SuppressWarnings("unchecked") final ArgumentParser<C, ?> parser = (ArgumentParser<C, ?>) parsers[i]; @SuppressWarnings("unchecked") final ArgumentParser<C, ?> parser = (ArgumentParser<C, ?>) parsers[i];
final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(TypeToken.get((Class<?>) types[i]), final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(
TypeToken.get((Class<?>) types[i]),
TypeToken.get(parser.getClass()), TypeToken.get(parser.getClass()),
parser); parser
);
final SuggestionProvider<S> provider = pair.getSecond() ? null : suggestionProvider; final SuggestionProvider<S> provider = pair.getSecond() ? null : suggestionProvider;
final ArgumentBuilder<S, ?> fragmentBuilder = RequiredArgumentBuilder final ArgumentBuilder<S, ?> fragmentBuilder = RequiredArgumentBuilder
.<S, Object>argument((String) names[i], (ArgumentType<Object>) pair.getFirst()) .<S, Object>argument((String) names[i], (ArgumentType<Object>) pair.getFirst())
.suggests(provider) .suggests(provider)
.requires(sender -> permissionChecker.test(sender, .requires(sender -> permissionChecker.test(
sender,
(CommandPermission) root.getNodeMeta() (CommandPermission) root.getNodeMeta()
.getOrDefault("permission", .getOrDefault(
Permission.empty()))); "permission",
Permission.empty()
)
));
argumentBuilders[i] = fragmentBuilder; argumentBuilders[i] = fragmentBuilder;
if (forceExecutor || (i == parsers.length - 1) && (root.isLeaf() || !root.getValue().isRequired())) { if (forceExecutor || (i == parsers.length - 1) && (root.isLeaf() || !root.getValue().isRequired())) {
@ -369,24 +395,33 @@ public final class CloudBrigadierManager<C, S> {
if (root.getValue() instanceof StaticArgument) { if (root.getValue() instanceof StaticArgument) {
argumentBuilder = LiteralArgumentBuilder.<S>literal(root.getValue().getName()) argumentBuilder = LiteralArgumentBuilder.<S>literal(root.getValue().getName())
.requires(sender -> permissionChecker.test(sender, (CommandPermission) root.getNodeMeta() .requires(sender -> permissionChecker.test(sender, (CommandPermission) root.getNodeMeta()
.getOrDefault("permission", .getOrDefault(
Permission.empty()))) "permission",
Permission.empty()
)))
.executes(executor); .executes(executor);
} else { } else {
final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(root.getValue().getValueType(), final Pair<ArgumentType<?>, Boolean> pair = this.getArgument(
root.getValue().getValueType(),
TypeToken.get(root.getValue().getParser().getClass()), TypeToken.get(root.getValue().getParser().getClass()),
root.getValue().getParser()); root.getValue().getParser()
);
final SuggestionProvider<S> provider = pair.getSecond() final SuggestionProvider<S> provider = pair.getSecond()
? null ? null
: (context, builder) -> this.buildSuggestions(root.getValue(), : (context, builder) -> this.buildSuggestions(root.getValue(),
context, builder); context, builder
);
argumentBuilder = RequiredArgumentBuilder argumentBuilder = RequiredArgumentBuilder
.<S, Object>argument(root.getValue().getName(), (ArgumentType<Object>) pair.getFirst()) .<S, Object>argument(root.getValue().getName(), (ArgumentType<Object>) pair.getFirst())
.suggests(provider) .suggests(provider)
.requires(sender -> permissionChecker.test(sender, .requires(sender -> permissionChecker.test(
sender,
(CommandPermission) root.getNodeMeta() (CommandPermission) root.getNodeMeta()
.getOrDefault("permission", .getOrDefault(
Permission.empty()))); "permission",
Permission.empty()
)
));
} }
if (forceExecutor || root.isLeaf() || !root.getValue().isRequired()) { if (forceExecutor || root.isLeaf() || !root.getValue().isRequired()) {
argumentBuilder.executes(executor); argumentBuilder.executes(executor);
@ -400,7 +435,8 @@ public final class CloudBrigadierManager<C, S> {
private @NonNull CompletableFuture<Suggestions> buildSuggestions( private @NonNull CompletableFuture<Suggestions> buildSuggestions(
final @NonNull CommandArgument<C, ?> argument, final @NonNull CommandArgument<C, ?> argument,
final com.mojang.brigadier.context.@NonNull CommandContext<S> s, final com.mojang.brigadier.context.@NonNull CommandContext<S> s,
final @NonNull SuggestionsBuilder builder) { final @NonNull SuggestionsBuilder builder
) {
final CommandContext<C> commandContext = this.dummyContextProvider.get(); final CommandContext<C> commandContext = this.dummyContextProvider.get();
final LinkedList<String> inputQueue = new LinkedList<>(Collections.singletonList(builder.getInput())); final LinkedList<String> inputQueue = new LinkedList<>(Collections.singletonList(builder.getInput()));
final CommandPreprocessingContext<C> commandPreprocessingContext = final CommandPreprocessingContext<C> commandPreprocessingContext =

View file

@ -61,8 +61,10 @@ public final class BukkitBrigadierMapper<C> {
* @param commandManager The {@link BukkitCommandManager} to use for mapping * @param commandManager The {@link BukkitCommandManager} to use for mapping
* @param brigadierManager The {@link CloudBrigadierManager} to use for mapping * @param brigadierManager The {@link CloudBrigadierManager} to use for mapping
*/ */
public BukkitBrigadierMapper(final @NonNull BukkitCommandManager<C> commandManager, public BukkitBrigadierMapper(
final @NonNull CloudBrigadierManager brigadierManager) { final @NonNull BukkitCommandManager<C> commandManager,
final @NonNull CloudBrigadierManager brigadierManager
) {
this.commandManager = commandManager; this.commandManager = commandManager;
this.brigadierManager = brigadierManager; this.brigadierManager = brigadierManager;
@ -100,8 +102,10 @@ public final class BukkitBrigadierMapper<C> {
* @param playersOnly Whether the selector is for players only (true), or for all entities (false) * @param playersOnly Whether the selector is for players only (true), or for all entities (false)
* @return The NMS ArgumentType * @return The NMS ArgumentType
*/ */
private Supplier<ArgumentType<?>> getEntitySelectorArgument(final boolean single, private Supplier<ArgumentType<?>> getEntitySelectorArgument(
final boolean playersOnly) { final boolean single,
final boolean playersOnly
) {
return () -> { return () -> {
try { try {
final Constructor<?> constructor = this.getNMSArgument("Entity").getDeclaredConstructors()[0]; final Constructor<?> constructor = this.getNMSArgument("Entity").getDeclaredConstructors()[0];
@ -132,8 +136,10 @@ public final class BukkitBrigadierMapper<C> {
* @param type Type to map * @param type Type to map
* @param constructor Constructor that construct the NMS argument type * @param constructor Constructor that construct the NMS argument type
*/ */
public void mapSimpleNMS(final @NonNull Class<?> type, public void mapSimpleNMS(
final @NonNull Constructor<?> constructor) { final @NonNull Class<?> type,
final @NonNull Constructor<?> constructor
) {
try { try {
this.brigadierManager.registerDefaultArgumentTypeSupplier(type, () -> { this.brigadierManager.registerDefaultArgumentTypeSupplier(type, () -> {
try { try {
@ -146,8 +152,10 @@ public final class BukkitBrigadierMapper<C> {
} catch (final Exception e) { } catch (final Exception e) {
this.commandManager.getOwningPlugin() this.commandManager.getOwningPlugin()
.getLogger() .getLogger()
.warning(String.format("Failed to map '%s' to a Mojang serializable argument type", .warning(String.format(
type.getCanonicalName())); "Failed to map '%s' to a Mojang serializable argument type",
type.getCanonicalName()
));
} }
} }
@ -157,15 +165,20 @@ public final class BukkitBrigadierMapper<C> {
* @param type Type to map * @param type Type to map
* @param argumentTypeSupplier Supplier of the NMS argument type * @param argumentTypeSupplier Supplier of the NMS argument type
*/ */
public void mapComplexNMS(final @NonNull Class<?> type, public void mapComplexNMS(
final @NonNull Supplier<ArgumentType<?>> argumentTypeSupplier) { final @NonNull Class<?> type,
final @NonNull Supplier<ArgumentType<?>> argumentTypeSupplier
) {
try { try {
this.brigadierManager.registerDefaultArgumentTypeSupplier(type, argumentTypeSupplier); this.brigadierManager.registerDefaultArgumentTypeSupplier(type, argumentTypeSupplier);
} catch (final Exception e) { } catch (final Exception e) {
this.commandManager.getOwningPlugin() this.commandManager.getOwningPlugin()
.getLogger() .getLogger()
.warning(String.format("Failed to map '%s' to a Mojang serializable argument type", .warning(String.format(
type.getCanonicalName())); "Failed to map '%s' to a Mojang serializable argument type",
type.getCanonicalName()
));
} }
} }
} }

View file

@ -51,32 +51,40 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
private final Command<C> cloudCommand; private final Command<C> cloudCommand;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
BukkitCommand(final @NonNull String label, BukkitCommand(
final @NonNull String label,
final @NonNull List<@NonNull String> aliases, final @NonNull List<@NonNull String> aliases,
final @NonNull Command<C> cloudCommand, final @NonNull Command<C> cloudCommand,
final @NonNull CommandArgument<C, ?> command, final @NonNull CommandArgument<C, ?> command,
final @NonNull BukkitCommandManager<C> manager) { final @NonNull BukkitCommandManager<C> manager
super(label, ) {
super(
label,
cloudCommand.getCommandMeta().getOrDefault("description", ""), cloudCommand.getCommandMeta().getOrDefault("description", ""),
"", "",
aliases); aliases
);
this.command = command; this.command = command;
this.manager = manager; this.manager = manager;
this.cloudCommand = cloudCommand; this.cloudCommand = cloudCommand;
} }
@Override @Override
public boolean execute(final @NonNull CommandSender commandSender, public boolean execute(
final @NonNull CommandSender commandSender,
final @NonNull String s, final @NonNull String s,
final @NonNull String @NonNull [] strings) { final @NonNull String @NonNull [] strings
) {
/* Join input */ /* Join input */
final StringBuilder builder = new StringBuilder(this.command.getName()); final StringBuilder builder = new StringBuilder(this.command.getName());
for (final String string : strings) { for (final String string : strings) {
builder.append(" ").append(string); builder.append(" ").append(string);
} }
final C sender = this.manager.getCommandSenderMapper().apply(commandSender); final C sender = this.manager.getCommandSenderMapper().apply(commandSender);
this.manager.executeCommand(sender, this.manager.executeCommand(
builder.toString()) sender,
builder.toString()
)
.whenComplete(((commandResult, throwable) -> { .whenComplete(((commandResult, throwable) -> {
if (throwable != null) { if (throwable != null) {
if (throwable instanceof CompletionException) { if (throwable instanceof CompletionException) {
@ -137,16 +145,20 @@ final class BukkitCommand<C> extends org.bukkit.command.Command implements Plugi
} }
@Override @Override
public List<String> tabComplete(final @NonNull CommandSender sender, public List<String> tabComplete(
final @NonNull CommandSender sender,
final @NonNull String alias, final @NonNull String alias,
final @NonNull String @NonNull [] args) final @NonNull String @NonNull [] args
)
throws IllegalArgumentException { throws IllegalArgumentException {
final StringBuilder builder = new StringBuilder(this.command.getName()); final StringBuilder builder = new StringBuilder(this.command.getName());
for (final String string : args) { for (final String string : args) {
builder.append(" ").append(string); builder.append(" ").append(string);
} }
return this.manager.suggest(this.manager.getCommandSenderMapper().apply(sender), return this.manager.suggest(
builder.toString()); this.manager.getCommandSenderMapper().apply(sender),
builder.toString()
);
} }
@Override @Override

View file

@ -89,11 +89,13 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
* @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender} * @param backwardsCommandSenderMapper Function that maps the command sender type to {@link CommandSender}
* @throws Exception If the construction of the manager fails * @throws Exception If the construction of the manager fails
*/ */
public BukkitCommandManager(final @NonNull Plugin owningPlugin, public BukkitCommandManager(
final @NonNull Plugin owningPlugin,
final @NonNull Function<@NonNull CommandTree<C>, final @NonNull Function<@NonNull CommandTree<C>,
@NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator, @NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator,
final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper, final @NonNull Function<@NonNull CommandSender, @NonNull C> commandSenderMapper,
final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper) final @NonNull Function<@NonNull C, @NonNull CommandSender> backwardsCommandSenderMapper
)
throws Exception { throws Exception {
super(commandExecutionCoordinator, new BukkitPluginRegistrationHandler<>()); super(commandExecutionCoordinator, new BukkitPluginRegistrationHandler<>());
((BukkitPluginRegistrationHandler<C>) this.getCommandRegistrationHandler()).initialize(this); ((BukkitPluginRegistrationHandler<C>) this.getCommandRegistrationHandler()).initialize(this);
@ -110,8 +112,10 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
final Matcher matcher = Pattern.compile("\\(MC: (\\d)\\.(\\d+)\\.?(\\d+?)?\\)") final Matcher matcher = Pattern.compile("\\(MC: (\\d)\\.(\\d+)\\.?(\\d+?)?\\)")
.matcher(Bukkit.getVersion()); .matcher(Bukkit.getVersion());
if (matcher.find()) { if (matcher.find()) {
version = Integer.parseInt(matcher.toMatchResult().group(2), version = Integer.parseInt(
VERSION_RADIX); matcher.toMatchResult().group(2),
VERSION_RADIX
);
} }
} catch (final Exception e) { } catch (final Exception e) {
this.owningPlugin.getLogger().severe("Failed to determine Minecraft version " this.owningPlugin.getLogger().severe("Failed to determine Minecraft version "
@ -132,13 +136,17 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
/* Register Bukkit Parsers */ /* Register Bukkit Parsers */
this.getParserRegistry().registerParserSupplier(TypeToken.get(World.class), params -> new WorldArgument.WorldParser<>()); this.getParserRegistry().registerParserSupplier(TypeToken.get(World.class), params -> new WorldArgument.WorldParser<>());
this.getParserRegistry().registerParserSupplier(TypeToken.get(Material.class), this.getParserRegistry().registerParserSupplier(
params -> new MaterialArgument.MaterialParser<>()); TypeToken.get(Material.class),
params -> new MaterialArgument.MaterialParser<>()
);
this.getParserRegistry() this.getParserRegistry()
.registerParserSupplier(TypeToken.get(Player.class), params -> new PlayerArgument.PlayerParser<>()); .registerParserSupplier(TypeToken.get(Player.class), params -> new PlayerArgument.PlayerParser<>());
this.getParserRegistry() this.getParserRegistry()
.registerParserSupplier(TypeToken.get(OfflinePlayer.class), .registerParserSupplier(
params -> new OfflinePlayerArgument.OfflinePlayerParser<>()); TypeToken.get(OfflinePlayer.class),
params -> new OfflinePlayerArgument.OfflinePlayerParser<>()
);
/* Register Entity Selector Parsers */ /* Register Entity Selector Parsers */
this.getParserRegistry().registerParserSupplier(TypeToken.get(SingleEntitySelector.class), parserParameters -> this.getParserRegistry().registerParserSupplier(TypeToken.get(SingleEntitySelector.class), parserParameters ->
new SingleEntitySelectorArgument.SingleEntitySelectorParser<>()); new SingleEntitySelectorArgument.SingleEntitySelectorParser<>());
@ -195,18 +203,20 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission); return this.backwardsCommandSenderMapper.apply(sender).hasPermission(permission);
} }
protected final void setSplitAliases(final boolean value) {
this.splitAliases = value;
}
protected final boolean getSplitAliases() { protected final boolean getSplitAliases() {
return this.splitAliases; return this.splitAliases;
} }
protected final void setSplitAliases(final boolean value) {
this.splitAliases = value;
}
protected final void checkBrigadierCompatibility() throws BrigadierFailureException { protected final void checkBrigadierCompatibility() throws BrigadierFailureException {
if (!this.queryCapability(CloudBukkitCapabilities.BRIGADIER)) { if (!this.queryCapability(CloudBukkitCapabilities.BRIGADIER)) {
throw new BrigadierFailureException(BrigadierFailureReason.VERSION_TOO_LOW, throw new BrigadierFailureException(
new IllegalArgumentException("Version: " + this.minecraftVersion)); BrigadierFailureReason.VERSION_TOO_LOW,
new IllegalArgumentException("Version: " + this.minecraftVersion)
);
} }
} }
@ -229,21 +239,27 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
if (this.paper) { if (this.paper) {
if (this.minecraftVersion >= ASYNC_TAB_MINIMUM_VERSION) { if (this.minecraftVersion >= ASYNC_TAB_MINIMUM_VERSION) {
if (this.minecraftVersion >= PAPER_BRIGADIER_VERSION) { if (this.minecraftVersion >= PAPER_BRIGADIER_VERSION) {
return EnumSet.of(CloudBukkitCapabilities.NATIVE_BRIGADIER, return EnumSet.of(
CloudBukkitCapabilities.NATIVE_BRIGADIER,
CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION,
CloudBukkitCapabilities.BRIGADIER); CloudBukkitCapabilities.BRIGADIER
);
} else if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) { } else if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) {
return EnumSet.of(CloudBukkitCapabilities.COMMODORE_BRIGADIER, return EnumSet.of(
CloudBukkitCapabilities.COMMODORE_BRIGADIER,
CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION, CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION,
CloudBukkitCapabilities.BRIGADIER); CloudBukkitCapabilities.BRIGADIER
);
} else { } else {
return EnumSet.of(CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION); return EnumSet.of(CloudBukkitCapabilities.ASYNCHRONOUS_COMPLETION);
} }
} }
} else { } else {
if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) { if (this.minecraftVersion >= BRIGADIER_MINIMUM_VERSION) {
return EnumSet.of(CloudBukkitCapabilities.COMMODORE_BRIGADIER, return EnumSet.of(
CloudBukkitCapabilities.BRIGADIER); CloudBukkitCapabilities.COMMODORE_BRIGADIER,
CloudBukkitCapabilities.BRIGADIER
);
} }
} }
return EnumSet.noneOf(CloudBukkitCapabilities.class); return EnumSet.noneOf(CloudBukkitCapabilities.class);
@ -320,9 +336,11 @@ public class BukkitCommandManager<C> extends CommandManager<C> {
@Override @Override
public String getMessage() { public String getMessage() {
return String.format("Could not initialize Brigadier mappings. Reason: %s (%s)", return String.format(
"Could not initialize Brigadier mappings. Reason: %s (%s)",
this.reason.name().toLowerCase().replace("_", " "), this.reason.name().toLowerCase().replace("_", " "),
this.getCause() == null ? "" : this.getCause().getMessage()); this.getCause() == null ? "" : this.getCause().getMessage()
);
} }
} }

View file

@ -41,4 +41,5 @@ final class BukkitPlayerSender extends BukkitCommandSender {
public @NonNull Player asPlayer() { public @NonNull Player asPlayer() {
return (Player) this.getInternalSender(); return (Player) this.getInternalSender();
} }
} }

View file

@ -79,7 +79,8 @@ public class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHa
final String label; final String label;
final String prefixedLabel = String.format("%s:%s", this.bukkitCommandManager.getOwningPlugin().getName(), final String prefixedLabel = String.format("%s:%s", this.bukkitCommandManager.getOwningPlugin().getName(),
commandArgument.getName()).toLowerCase(); commandArgument.getName()
).toLowerCase();
if (!(this.bukkitCommandManager.getCommandRegistrationHandler() instanceof CloudCommodoreManager) if (!(this.bukkitCommandManager.getCommandRegistrationHandler() instanceof CloudCommodoreManager)
&& bukkitCommands.containsKey(commandArgument.getName())) { && bukkitCommands.containsKey(commandArgument.getName())) {
label = prefixedLabel; label = prefixedLabel;
@ -87,8 +88,7 @@ public class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHa
label = commandArgument.getName(); label = commandArgument.getName();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final List<String> aliases = new ArrayList<>(((StaticArgument<C>) commandArgument).getAlternativeAliases());
final List<String> aliases = new ArrayList<>(((StaticArgument<C>) commandArgument).getAlternativeAliases());
if (!label.contains(":")) { if (!label.contains(":")) {
aliases.add(prefixedLabel); aliases.add(prefixedLabel);
@ -99,11 +99,14 @@ public class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHa
(this.bukkitCommandManager.getSplitAliases() ? Collections.<String>emptyList() : aliases), (this.bukkitCommandManager.getSplitAliases() ? Collections.<String>emptyList() : aliases),
(Command<C>) command, (Command<C>) command,
(CommandArgument<C, ?>) commandArgument, (CommandArgument<C, ?>) commandArgument,
this.bukkitCommandManager); this.bukkitCommandManager
);
this.registeredCommands.put(commandArgument, bukkitCommand); this.registeredCommands.put(commandArgument, bukkitCommand);
this.commandMap.register(label, this.commandMap.register(
label,
this.bukkitCommandManager.getOwningPlugin().getName().toLowerCase(), this.bukkitCommandManager.getOwningPlugin().getName().toLowerCase(),
bukkitCommand); bukkitCommand
);
this.registerExternal(label, command, bukkitCommand); this.registerExternal(label, command, bukkitCommand);
this.recognizedAliases.add(label); this.recognizedAliases.add(label);
@ -115,10 +118,12 @@ public class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHa
Collections.emptyList(), Collections.emptyList(),
(Command<C>) command, (Command<C>) command,
(CommandArgument<C, ?>) commandArgument, (CommandArgument<C, ?>) commandArgument,
this.bukkitCommandManager); this.bukkitCommandManager
);
this.commandMap.register(alias, this.bukkitCommandManager.getOwningPlugin() this.commandMap.register(alias, this.bukkitCommandManager.getOwningPlugin()
.getName().toLowerCase(), .getName().toLowerCase(),
bukkitCommand); bukkitCommand
);
this.registerExternal(alias, command, aliasCommand); this.registerExternal(alias, command, aliasCommand);
this.recognizedAliases.add(alias); this.recognizedAliases.add(alias);
} }
@ -138,9 +143,11 @@ public class BukkitPluginRegistrationHandler<C> implements CommandRegistrationHa
return this.recognizedAliases.contains(alias); return this.recognizedAliases.contains(alias);
} }
protected void registerExternal(final @NonNull String label, protected void registerExternal(
final @NonNull String label,
final @NonNull Command<?> command, final @NonNull Command<?> command,
final @NonNull BukkitCommand<C> bukkitCommand) { final @NonNull BukkitCommand<C> bukkitCommand
) {
} }
} }

View file

@ -27,5 +27,8 @@ package cloud.commandframework.bukkit;
* Capabilities for the Bukkit module * Capabilities for the Bukkit module
*/ */
public enum CloudBukkitCapabilities { public enum CloudBukkitCapabilities {
BRIGADIER, COMMODORE_BRIGADIER, NATIVE_BRIGADIER, ASYNCHRONOUS_COMPLETION BRIGADIER,
COMMODORE_BRIGADIER,
NATIVE_BRIGADIER,
ASYNCHRONOUS_COMPLETION
} }

View file

@ -59,21 +59,27 @@ class CloudCommodoreManager<C> extends BukkitPluginRegistrationHandler<C> {
} }
@Override @Override
protected void registerExternal(final @NonNull String label, protected void registerExternal(
final @NonNull String label,
final @NonNull Command<?> command, final @NonNull Command<?> command,
final @NonNull BukkitCommand<C> bukkitCommand) { final @NonNull BukkitCommand<C> bukkitCommand
) {
this.registerWithCommodore(label, command); this.registerWithCommodore(label, command);
this.registerWithCommodore(String.format("%s:%s", bukkitCommand.getPlugin().getName(), label).toLowerCase(), command); this.registerWithCommodore(String.format("%s:%s", bukkitCommand.getPlugin().getName(), label).toLowerCase(), command);
} }
private void registerWithCommodore(final @NonNull String label, private void registerWithCommodore(
final @NonNull Command<?> command) { final @NonNull String label,
final @NonNull Command<?> command
) {
final com.mojang.brigadier.Command<?> cmd = o -> 1; final com.mojang.brigadier.Command<?> cmd = o -> 1;
final LiteralCommandNode<?> literalCommandNode = this.brigadierManager final LiteralCommandNode<?> literalCommandNode = this.brigadierManager
.<Object>createLiteralCommandNode(label, command, (o, p) -> { .<Object>createLiteralCommandNode(label, command, (o, p) -> {
final CommandSender sender = this.commodore.getBukkitSender(o); final CommandSender sender = this.commodore.getBukkitSender(o);
return this.commandManager.hasPermission(this.commandManager.getCommandSenderMapper().apply(sender), return this.commandManager.hasPermission(
(CommandPermission) p); this.commandManager.getCommandSenderMapper().apply(sender),
(CommandPermission) p
);
}, false, cmd); }, false, cmd);
final CommandNode existingNode = this.commodore.getDispatcher().findNode(Collections.singletonList(label)); final CommandNode existingNode = this.commodore.getDispatcher().findNode(Collections.singletonList(label));
if (existingNode != null) { if (existingNode != null) {

View file

@ -43,8 +43,10 @@ public abstract class EntitySelector {
* @param selector The input string used to create this selector * @param selector The input string used to create this selector
* @param entities The List of Bukkit {@link Entity entities} to construct the {@link EntitySelector} from * @param entities The List of Bukkit {@link Entity entities} to construct the {@link EntitySelector} from
*/ */
public EntitySelector(final @NonNull String selector, public EntitySelector(
final @NonNull List<@NonNull Entity> entities) { final @NonNull String selector,
final @NonNull List<@NonNull Entity> entities
) {
this.selector = selector; this.selector = selector;
this.entities = entities; this.entities = entities;
} }

Some files were not shown because too many files have changed in this diff Show more