### Example Generated Issue Description Source: https://www.rubydoc.info/gems/gitlab-triage This is an example of the description that would be generated by the 'Summarize action' snippet, including a list of issues and a deadline. ```text The following issues require labels: - [ ] [An example issue](http://example.com/group/project/issues/1) ~"label A", ~"label B" - [ ] [Another issue](http://example.com/group/project/issues/2) ~"label B", ~"label C" Please take care of them before the end of 2000-01-01 /label ~"needs attention" ``` -------------------------------- ### Example Summary Definition (YAML) Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine An example of an array of summary definitions, shown in YAML format for readability. This structure defines how to group and summarize resources. ```yaml - name: Newest and oldest issues summary rules: - name: New issues conditions: state: opened limits: most_recent: 2 actions: summarize: item: "- [ ] [{{title}}]({{web_url}}) {{labels}}" summary: | Please triage the following new {{type}}: {{items}} actions: summarize: title: "Newest and oldest {{type}} summary" summary: | Please triage the following {{type}}: {{items}} Please take care of them before the end of #{7.days.from_now.strftime('%Y-%m-%d')} /label ~"needs attention" ``` -------------------------------- ### started? Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Astarted%3F Checks if the milestone has started by comparing its start date with the provided date. ```APIDOC ## started? ### Description Checks if the milestone has started by comparing its start date with the provided date. ### Method Ruby Method ### Parameters #### Path Parameters - **today** (Date) - Optional - The date to compare against. Defaults to `Date.today`. #### Query Parameters None #### Request Body None ### Request Example ```ruby # Assuming milestone is an instance of Gitlab::Triage::Resource::Milestone milestone.started?(Date.new(2023, 1, 1)) ``` ### Response #### Success Response (Boolean) - **Boolean** - Returns `true` if the milestone has started, `false` otherwise. #### Response Example ```ruby true ``` ``` -------------------------------- ### Example Generated Issue Title Source: https://www.rubydoc.info/gems/gitlab-triage This is an example of the title that would be generated by the 'Summarize action' snippet when issues require labels. ```text Issues require labels ``` -------------------------------- ### Install GitLab Triage Gem Source: https://www.rubydoc.info/gems/gitlab-triage Install the gitlab-triage gem using the standard RubyGems command. This is the primary step to begin using the gem's functionalities. ```bash gem install gitlab-triage ``` -------------------------------- ### Example Summary Definition Hash (YAML) Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine An example of a single summary definition hash, presented in YAML for clarity. This hash outlines the structure for summarizing resources, including rules and actions. ```yaml name: Newest and oldest issues summary rules: - name: New issues conditions: state: opened limits: most_recent: 2 actions: summarize: item: "- [ ] [{{title}}]({{web_url}}) {{labels}}" summary: | Please triage the following new {{type}}: {{items}} actions: summarize: title: "Newest and oldest {{type}} summary" summary: | Please triage the following {{type}}: {{items}} Please take care of them before the end of #{7.days.from_now.strftime('%Y-%m-%d')} /label ~"needs attention" ``` -------------------------------- ### Custom Ruby Plugin Example Source: https://www.rubydoc.info/gems/gitlab-triage Extend `gitlab-triage` functionality by creating a Ruby file with custom methods and including it using the `-r` or `--require` option. This example defines methods to check for severity and priority labels. ```ruby module MyPlugin def has_severity_label? labels.grep(/^S\d+$/).any? end def has_priority_label? labels.grep(/^P\d+$/).any? end def labels resource[:labels] end end Gitlab::Triage::Resource::Context.include MyPlugin ``` -------------------------------- ### TestAdapter GET Method Implementation Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/NetworkAdapters/TestAdapter Implements the GET method for the TestAdapter. It simulates responses based on the provided URL, specifically for issue retrieval. This is useful for testing network adapter interactions without making actual HTTP requests. ```ruby def get(_token, url) results = case url when %r{\Ahttps://gitlab.com/v4/issues?per_page=100} [ { id: 1, title: 'First issue' } ] else [] end { more_pages: false, next_page_url: nil, results: results, ratelimit_remaining: 600, ratelimit_reset_at: Time.now } end ``` -------------------------------- ### Get Summary Destination Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder Returns the configured summary destination. ```ruby def destination @summary_destination end ``` -------------------------------- ### Example Rule Definition Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine An example of an array of rule definitions, typically provided in YAML format within a triage policy file. ```ruby [{ name: "New issues", conditions: { state: opened }, limits: { most_recent: 2 }, actions: { labels: ["needs attention"] } }] ``` -------------------------------- ### Milestone#all_active_with_start_date Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Aall_active_with_start_date Retrieves active milestones with a start date, sorted by start date. Uses memoization for efficiency. ```ruby def all_active_with_start_date @all_active_with_start_date ||= all_active.select(&:start_date).sort_by(&:start_date) end ``` -------------------------------- ### Example Rule Definition Hash Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Demonstrates the structure of a rule definition hash, including name, conditions, limits, and actions. ```ruby { name: "New issues", conditions: { state: opened }, limits: { most_recent: 2 }, actions: { labels: ["needs attention"] } } ``` -------------------------------- ### Get Summary Description Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder Retrieves the summary's description, building it using build_text with the summary template if it hasn't been generated yet. ```ruby def description @description ||= build_text(description_resource, @summary_template) end ``` -------------------------------- ### Get Full Resource Reference Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable Retrieves the full reference string for the resource, typically in the format 'group/project:id'. ```ruby # File 'lib/gitlab/triage/resource/shared/issuable.rb', line 63 def full_resource_reference @full_resource_reference ||= resource.dig(:references, :full) end ``` -------------------------------- ### CI/CD Pipeline for GitLab Triage Source: https://www.rubydoc.info/gems/gitlab-triage This example demonstrates how to set up a CI/CD pipeline to pre-fetch member data into a cache and then use that cache in a subsequent triage job. The 'pre-hygiene' stage writes the cache, and the 'hygiene' stage reads from it. ```yaml prefetch-members: stage: pre-hygiene script: - ruby bin/prefetch_members artifacts: paths: - tmp/members_cache/ expire_in: 1 hour triage-job: stage: hygiene script: - gitlab-triage --cache-dir tmp/members_cache --token $TOKEN --source groups --source-id 9970 -f policy.yml ``` -------------------------------- ### Get Instance Version Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/InstanceVersion%3Aversion Retrieves the version from the response object. This method is used to access the version attribute of the instance. ```ruby def version response[:version] end ``` -------------------------------- ### Date Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters resources updated more than 12 months ago. Use this for time-based filtering of resources. ```yaml conditions: date: attribute: updated_at condition: older_than interval_type: months interval: 12 ``` -------------------------------- ### Get Description Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/IssueBuilder Lazily builds and returns the description text using the description template. If the description has not been built yet, it calls build_text. ```ruby def description @description ||= build_text(@description_template) end ``` -------------------------------- ### Get Current Milestone Index Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Acurrent_index Finds the index of the current milestone within a collection of active milestones that have a start date. This method is private and intended for internal use. ```ruby def current_index all_active_with_start_date .index { |milestone| milestone.id == id } end ``` -------------------------------- ### Initialize GraphQL Network Adapter Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Initializes and returns a GraphQL network adapter, using options provided during initialization. ```ruby def graphql_network_adapter @graphql_network_adapter ||= @graphql_network_adapter_class.new(options) end ``` -------------------------------- ### Ruby Expression for Milestone Date Condition Source: https://www.rubydoc.info/gems/gitlab-triage Use this condition to filter resources based on a Ruby expression. This example checks if the current date is after the start date of the next active milestone. ```yaml conditions: ruby: Date.today > milestone.succ.start_date ``` -------------------------------- ### Initialize SummaryBuilder Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder%3Ainitialize Initializes a new instance of SummaryBuilder with various configuration options. Use this to set up the builder with specific action details, resource information, and network configurations. ```ruby def initialize( type:, action:, resources:, network:, policy_spec: {}, separator: "\n" ) @type = type @policy_spec = policy_spec @item_template = action[:item] @title_template = action[:title] @summary_template = action[:summary] @summary_destination = action[:destination] @redact_confidentials = action[:redact_confidential_resources] != false @resources = resources @network = network @separator = separator @is_custom = policy_spec[:type] == 'custom' end ``` -------------------------------- ### Build Get URL Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Constructs a URL for fetching resources based on resource type and conditions. This is a complex method with extensive logic for various resource types and filtering options. ```ruby def build_get_url(resource_type, conditions) # ... (implementation details omitted for brevity, as per source) ... end ``` -------------------------------- ### Initialize Resources Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Limiters/BaseLimiter Private instance method to initialize resources. Returns the resources as is by default, intended for subclass extension. ```ruby def initialize_resources(resources) resources end ``` -------------------------------- ### Initialize BaseAdapter Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/NetworkAdapters/BaseAdapter Initializes a new instance of the BaseAdapter with provided options. ```ruby def initialize(options) @options = options end ``` -------------------------------- ### Generate Newest and Oldest Issues Summary Source: https://www.rubydoc.info/gems/gitlab-triage This example demonstrates creating summaries for both the newest and oldest issues, incorporating dynamic date formatting and a project label. The `item` field defines the format for individual issues, while the `summary` field structures the overall report. ```yaml resource_rules: issues: summaries: - name: Newest and oldest issues summary rules: - name: New issues conditions: state: opened limits: most_recent: 2 actions: summarize: item: "- [ ] [{{title}}]({{web_url}}) {{labels}}" summary: | Please triage the following new {{type}}: {{items}} - name: Old issues conditions: state: opened limits: oldest: 2 actions: summarize: item: "- [ ] [{{title}}]({{web_url}}) {{labels}}" summary: | Please triage the following old {{type}}: {{items}} actions: summarize: title: "Newest and oldest {{type}} summary" summary: | Please triage the following {{type}}: {{items}} Please take care of them before the end of #{7.days.from_now.strftime('%Y-%m-%d')} /label ~"needs attention" ``` -------------------------------- ### Initialize Network Adapter Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Initializes and returns a network adapter instance based on the configured class and options. ```ruby def network_adapter @network_adapter ||= @network_adapter_class.new(options) end ``` -------------------------------- ### build_summary Method Implementation Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Policies/RulePolicy%3Abuild_summary This snippet shows the implementation of the build_summary method. It fetches the 'summarize' action and uses it to initialize a SummaryBuilder. ```ruby def build_summary action = actions.fetch(:summarize, {}) EntityBuilders::SummaryBuilder.new( type: type, policy_spec: policy_spec, action: action, resources: resources, network: network) end ``` -------------------------------- ### Get Title Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/IssueBuilder Lazily builds and returns the title text using the title template. If the title has not been built yet, it calls build_text. ```ruby def title @title ||= build_text(@title_template) end ``` -------------------------------- ### Display Help Message Source: https://www.rubydoc.info/gems/gitlab-triage Run `gitlab-triage --help` to display all available command-line options and their descriptions. ```bash gitlab-triage --help ``` -------------------------------- ### Check if Milestone has Started Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Astarted%3F Use this method to determine if a milestone has begun. It compares the milestone's start date with the provided date (defaults to today). ```ruby def started?(today = Date.today) start_date && start_date <= today end ``` -------------------------------- ### UrlBuilder#initialize Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/UrlBuilders/UrlBuilder%3Ainitialize Initializes a new instance of UrlBuilder with provided options. It sets up network options, source details, and resource identifiers for constructing URLs. Use this when creating a new URL builder instance. ```ruby def initialize(options) @network_options = options.fetch(:network_options) @host_url = @network_options.host_url @api_version = @network_options.api_version @all = options.fetch(:all, false) @source = options.fetch(:source, 'projects') @source_id = options.fetch(:source_id) @resource_type = options.fetch(:resource_type, nil) @sub_resource_type = options.fetch(:sub_resource_type, nil) @resource_id = options.fetch(:resource_id, nil) @params = options.fetch(:params, []) @params = @params.merge(scope: :all) if @all end ``` -------------------------------- ### InstanceVersion#initialize Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/InstanceVersion%3Ainitialize Initializes a new instance of InstanceVersion. It calls the superclass initializer with an empty hash and the provided options. ```ruby def initialize(**options) super({}, **options) end ``` -------------------------------- ### Milestone Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters resources associated with the 'v1' milestone. This is useful for organizing and tracking work within specific release cycles. ```yaml conditions: milestone: v1 ``` -------------------------------- ### Check if Milestone is in Progress Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Ain_progress%3F Determines if a milestone is currently active. It returns true if the milestone has started and has not yet expired. Requires the `started?` and `expired?` methods to be defined. ```ruby def in_progress?(today = Date.today) started?(today) && !expired?(today) end ``` -------------------------------- ### initialize Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/RestAPINetwork Initializes a new instance of RestAPINetwork with the given adapter. ```APIDOC ## initialize(adapter) ### Description Initializes a new instance of RestAPINetwork. ### Parameters #### Path Parameters - **adapter** (Object) - Required - The adapter to use for API requests. ``` -------------------------------- ### Triaging an Entire Instance Source: https://www.rubydoc.info/gems/gitlab-triage Process all projects accessible by the API token by using the `--all-projects` option. This is useful for instance-wide operations. A token with sufficient permissions is required. ```bash gitlab-triage --dry-run --token $GITLAB_API_TOKEN --all-projects ``` -------------------------------- ### Initialize Base Action Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Action/Base%3Ainitialize Initializes a new instance of the Base class, setting the policy and network attributes from the provided arguments. ```ruby def initialize(**args) @policy = args[:policy] @network = args[:network] end ``` -------------------------------- ### GET Request Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/NetworkAdapters/HttpartyAdapter Performs an HTTP GET request to the specified URL with authentication. It handles rate limiting and returns parsed response data along with pagination information. ```APIDOC ## GET /url ### Description Performs an HTTP GET request to the specified URL with authentication. It handles rate limiting and returns parsed response data along with pagination information. ### Method GET ### Endpoint [URL provided by the user] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "token": "string", "url": "string" } ``` ### Response #### Success Response (200) - **more_pages** (boolean) - Indicates if there are more pages of results. - **next_page_url** (string) - The URL for the next page of results. - **results** (object) - The parsed JSON response from the server. - **ratelimit_remaining** (integer) - The number of remaining requests allowed by the rate limit. - **ratelimit_reset_at** (datetime) - The time at which the rate limit will reset. #### Response Example ```json { "more_pages": true, "next_page_url": "/api/v4/projects?page=2", "results": { ... }, "ratelimit_remaining": 4999, "ratelimit_reset_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Initialize Base Resource Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Base%3Ainitialize Initializes a new instance of the Base resource. Use this to set up a resource with its associated data and optional network/parent context. ```ruby def initialize( resource, parent: nil, network: nil, redact_confidentials: true ) @resource = resource @parent = parent @network = network @redact_confidentials = redact_confidentials end ``` -------------------------------- ### GraphQL Client Initialization Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/NetworkAdapters/GraphqlAdapter Initializes the GraphQL client with the schema and HTTP client. Allows dynamic queries. ```ruby def client @client ||= Client.new(schema: schema, execute: http_client).tap { |client| client.allow_dynamic_queries = true } end ``` -------------------------------- ### HTTPartyAdapter GET Request Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/NetworkAdapters/HttpartyAdapter Performs GET requests to a specified URL with authentication and content type. It includes logic to check for next page availability and handles various HTTP errors. Returns pagination info, results, and rate limit details. ```ruby def get(token, url) response = HTTParty.get( url, headers: { 'User-Agent' => USER_AGENT, 'Content-type' => 'application/json', 'PRIVATE-TOKEN' => token } ) raise_on_unauthorized_error!(response) raise_on_internal_server_error!(response) raise_on_too_many_requests!(response) { more_pages: (response.headers["x-next-page"].to_s != ""), next_page_url: next_page_url(url, response), results: response.parsed_response, ratelimit_remaining: response.headers["ratelimit-remaining"].to_i, ratelimit_reset_at: Time.at(response.headers["ratelimit-reset"].to_i) } end ``` -------------------------------- ### GraphqlNetwork Constructor Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlNetwork Initializes a new instance of GraphqlNetwork with an adapter and its options. ```ruby def initialize(adapter) @adapter = adapter @options = adapter.options end ``` -------------------------------- ### Gitlab::Triage::GraphqlNetwork#initialize Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlNetwork Initializes a new instance of GraphqlNetwork with a given adapter. The adapter is used for making GraphQL queries and accessing options. ```APIDOC ## Gitlab::Triage::GraphqlNetwork#initialize ### Description Initializes a new instance of GraphqlNetwork with a given adapter. The adapter is used for making GraphQL queries and accessing options. ### Method constructor ### Parameters * **adapter** (Object) - The adapter to use for network requests. ``` -------------------------------- ### Get With Quotes Attribute Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlQueries/QueryParamBuilders/BaseParamBuilder Returns the value of the with_quotes attribute. ```ruby def with_quotes @with_quotes end ``` -------------------------------- ### Get Negated Attribute Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlQueries/QueryParamBuilders/BaseParamBuilder Returns the value of the negated attribute. ```ruby def negated @negated end ``` -------------------------------- ### Gitlab::Triage::GraphqlNetwork#options Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlNetwork Returns the options object associated with the adapter. ```APIDOC ## Gitlab::Triage::GraphqlNetwork#options ### Description Returns the options object associated with the adapter. ### Method options ### Returns * **Object** - The options object. ``` -------------------------------- ### Initialize Engine Instance Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Initializes a new Engine instance with policies, options, and network adapter classes. It processes and deletes specific options from the policies hash, sets default values for API version and dry run, and asserts the validity of the options. ```ruby def initialize(policies:, options:, network_adapter_class: DEFAULT_NETWORK_ADAPTER, graphql_network_adapter_class: DEFAULT_GRAPHQL_ADAPTER) options.host_url = policies.delete(:host_url) { options.host_url } options.api_version = policies.delete(:api_version) { 'v4' } options.dry_run = ENV['TEST'] == 'true' if options.dry_run.nil? @per_page = policies.delete(:per_page) { 100 } @policies = policies @options = options @network_adapter_class = network_adapter_class @graphql_network_adapter_class = graphql_network_adapter_class assert_options! @options.source = @options.source.to_s require_ruby_files end ``` -------------------------------- ### Get Summary Attribute Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Action/CommentOnSummary Retrieves the summary attribute of the CommentOnSummary object. ```ruby def summary @summary end ``` -------------------------------- ### Running from Source Source: https://www.rubydoc.info/gems/gitlab-triage Execute the `gitlab-triage` script directly from the `./bin` directory after cloning the project. This is useful for development or testing. ```bash bundle exec bin/gitlab-triage --dry-run --token $GITLAB_API_TOKEN --source-id gitlab-org/triage ``` -------------------------------- ### Get Project Path Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable Retrieves the namespaced path of the project associated with the resource. ```ruby # File 'lib/gitlab/triage/resource/shared/issuable.rb', line 58 def project_path @project_path ||= request_project(resource[:project_id])[:path_with_namespace] end ``` -------------------------------- ### Initialize Network Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Initializes and returns a Network object, using provided REST API and GraphQL network configurations. ```ruby def network @network ||= Network.new(restapi: restapi_network, graphql: graphql_network) end ``` -------------------------------- ### MultiQueryParamBuilder#initialize Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/APIQueryBuilders/MultiQueryParamBuilder%3Ainitialize Initializes a new instance of MultiQueryParamBuilder. Use this to set up a builder for constructing multi-value API query parameters. ```ruby def initialize(param_name, param_contents, separator, allowed_values: nil) @separator = separator super(param_name, Array(param_contents), allowed_values: allowed_values) end ``` -------------------------------- ### Get link_type Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/LinkedIssue%3Alink_type Retrieves the link type from the resource. This method caches the result. ```ruby def link_type @link_type ||= resource.dig(:link_type) end ``` -------------------------------- ### Initialize GraphqlNetwork Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine%3Agraphql_network Initializes a new GraphqlNetwork object using a graphql_network_adapter. This method is memoized, meaning it will only create the GraphqlNetwork object once. ```ruby def graphql_network @graphql_network ||= GraphqlNetwork.new(graphql_network_adapter) end ``` -------------------------------- ### Get Destination Attribute Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/IssueBuilder Retrieves the value of the destination attribute for the IssueBuilder instance. ```ruby def destination @destination end ``` -------------------------------- ### Get Param Name Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/APIQueryBuilders/BaseQueryParamBuilder Returns the value of the param_name attribute. This attribute is read-only. ```ruby def param_name @param_name end ``` -------------------------------- ### Instance Method: graphql_options Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Network Retrieves the options for the GraphQL client. ```ruby # File 'lib/gitlab/triage/network.rb', line 28 def graphql_options graphql.options end ``` -------------------------------- ### Get Param Contents Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/APIQueryBuilders/BaseQueryParamBuilder Returns the value of the param_contents attribute. This attribute is read-only. ```ruby def param_contents @param_contents end ``` -------------------------------- ### Initialize InstanceVersion Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Context%3Ainstance_version Initializes and returns a new InstanceVersion object. This method is private and uses memoization to ensure the InstanceVersion object is created only once. ```ruby def instance_version @instance_version ||= InstanceVersion.new(parent: self) end ``` -------------------------------- ### Get Allowed Values Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/APIQueryBuilders/BaseQueryParamBuilder Returns the value of the allowed_values attribute. This attribute is read-only. ```ruby def allowed_values @allowed_values end ``` -------------------------------- ### Get Parameter Content Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/APIQueryBuilders/SingleQueryParamBuilder Returns the content of the query parameter. This method is inherited from BaseQueryParamBuilder. ```ruby def param_content param_contents end ``` -------------------------------- ### Fetch Source Full Path Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Fetches and caches the full path of the source file. Initializes the path if it has not been fetched yet. ```ruby # File 'lib/gitlab/triage/engine.rb', line 658 def source_full_path @source_full_path ||= fetch_source_full_path end ``` -------------------------------- ### Get Milestone Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable Retrieves the milestone associated with the resource, creating a Milestone object if one exists. ```ruby # File 'lib/gitlab/triage/resource/shared/issuable.rb', line 15 def milestone @milestone ||= resource[:milestone] && Milestone.new(resource[:milestone], parent: self) end ``` -------------------------------- ### BaseCommandBuilder#initialize Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/CommandBuilders/BaseCommandBuilder%3Ainitialize Initializes a new instance of BaseCommandBuilder. It wraps the provided items in an array, removes empty strings, and processes resource and network parameters. ```ruby def initialize(items, resource: nil, network: nil) @items = Array.wrap(items) @items.delete('') @resource = resource&.with_indifferent_access @network = network end ``` -------------------------------- ### Get Labels Chronologically Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable Returns labels sorted by their addition date. This method relies on `labels_with_details`. ```ruby # File 'lib/gitlab/triage/resource/shared/issuable.rb', line 46 def labels_chronologically @labels_chronologically ||= labels_with_details.sort_by(&:added_at) end ``` -------------------------------- ### Get All Filter Names Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/BaseConditionsFilter.params_filter_names Class method to retrieve all available filter names by calling `params_filter_names`. ```ruby def self.all_params_filter_names params_filter_names end ``` -------------------------------- ### Instance Methods Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Network This section details the instance methods available in the Gitlab::Triage::Network class for interacting with APIs. ```APIDOC ## Instance Methods ### #delete_api ⇒ Object Performs a DELETE request using the REST API. ### #graphql_options ⇒ Object Retrieves the options for the GraphQL client. ### #post_api ⇒ Object Performs a POST request using the REST API. ### #query_api(url) ⇒ Object Queries the REST API with the given URL. ### #query_api_cached(url) ⇒ Object Queries the REST API with the given URL and caches the result. ### #query_graphql ⇒ Object Queries the GraphQL API. ### #restapi_options ⇒ Object Retrieves the options for the REST API client. ``` -------------------------------- ### Build URL with Parameters and Options Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Base%3Abuild_url Constructs a URL using provided parameters and options, merging them with default per_page settings. This method is private and intended for internal use. ```ruby def build_url(params: {}, options: {}) UrlBuilders::UrlBuilder.new( url_opts .merge(options) .merge(params: { per_page: 100 }.merge(params)) ).build end ``` -------------------------------- ### Add Threaded Comment to Resource Source: https://www.rubydoc.info/gems/gitlab-triage Adds a comment as a resolvable thread on the resource. This can be used to start discussions. ```yaml actions: comment_type: thread comment: | {{author}} Are you still interested in finishing this merge request? ``` -------------------------------- ### Labels Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters resources that have the 'feature proposal' label. This requires the label to be present on the resource. ```yaml conditions: labels: - feature proposal ``` -------------------------------- ### Get Project Path Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Epic%3Aproject_path Retrieves the full path of the group associated with the epic. This method caches the result. ```ruby def project_path @project_path ||= request_group(resource[:group_id])[:full_path] end ``` -------------------------------- ### Initialize Resources for DateFieldLimiter Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Limiters/DateFieldLimiter Private instance method to sort resources by their creation date. ```ruby def initialize_resources(resources) resources.sort_by { |res| res[:created_at] } end ``` -------------------------------- ### InstanceVersion Methods Source: https://www.rubydoc.info/gems/gitlab-triage Details the methods available for InstanceVersion objects, providing information about the GitLab version and revision. ```APIDOC ## Methods for `InstanceVersion` ### version - **Return type**: String - **Description**: The full string of version. e.g. `11.3.0-rc11-ee`. ### version_short - **Return type**: String - **Description**: The short string of version. e.g. `11.3`. ### revision - **Return type**: String - **Description**: The revision of GitLab. e.g. `231b0c7`. ``` -------------------------------- ### Get Resource ID Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Base%3Aresource_id Retrieves the internal ID of the resource. This method is private and intended for internal use. ```ruby def resource_id resource[:iid] end ``` -------------------------------- ### Get policy_spec Attribute - Ruby Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Policies/BasePolicy%3Apolicy_spec Returns the value of the @policy_spec instance variable. This is a simple getter method. ```Ruby def policy_spec @policy_spec end ``` -------------------------------- ### Initialize RestAPINetwork Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/RestAPINetwork%3Ainitialize Initializes a new RestAPINetwork instance with the provided adapter. It sets up instance variables for the adapter, options, and caches. ```ruby def initialize(adapter) @adapter = adapter @options = adapter.options @cache = {} @file_cache = {} end ``` -------------------------------- ### Get Allowed Attributes for Date Filters Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/IssueDateConditionsFilter Returns a frozen array of attributes that can be used for date-based filtering. ```ruby def self.allowed_attributes @allowed_attributes ||= generate_allowed_attributes.freeze end ``` -------------------------------- ### Get Condition Name Value Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/NameConditionsFilter Returns the name that the filter is set to match against. This is the value set during initialization. ```ruby def condition_value @matching_name end ``` -------------------------------- ### Build Summary Method (Abstract) Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Policies/BasePolicy Abstract method to build a summary. Raises NotImplementedError, indicating it must be implemented by subclasses. ```ruby def build_summary raise NotImplementedError end ``` -------------------------------- ### Get Title Resource Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder Returns a hash containing the type of the summary, used as a resource for building the title. ```ruby def title_resource { type: @type } end ``` -------------------------------- ### Initialize CommentOnSummary Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Action/CommentOnSummary Initializes a new instance of CommentOnSummary with a policy and network object. It stores the summary from the policy. ```ruby def initialize(policy:, network:) super(policy: policy, network: network) @summary = policy.summary end ``` -------------------------------- ### Initialize RestAPINetwork Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Initializes and returns a RestAPINetwork instance, creating it if it doesn't exist. ```ruby # File 'lib/gitlab/triage/engine.rb', line 111 def restapi_network @restapi_network ||= RestAPINetwork.new(network_adapter) end ``` -------------------------------- ### Votes Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters resources with less than 10 upvotes. Use this to identify popular or under-voted items. ```yaml conditions: votes: attribute: upvotes condition: less_than threshold: 10 ``` -------------------------------- ### QueryBuilder Initialize Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlQueries/QueryBuilder Initializes a new QueryBuilder instance, setting up source type, resource type, conditions, and GraphQL-only flag. It also prepares the initial resource declarations, adding 'iids' if present in conditions. ```ruby # File 'lib/gitlab/triage/graphql_queries/query_builder.rb', line 11 def initialize(source_type, resource_type, conditions, graphql_only: false) @source_type = source_type.to_s.singularize @resource_type = resource_type @conditions = conditions @graphql_only = graphql_only @resource_declarations = [ '$source: ID!', '$after: String' ] has_any_iids = conditions.each_key.find { |key| key.to_s == 'iids' } @resource_declarations << '$iids: [String!]' if has_any_iids end ``` -------------------------------- ### build_command Method Implementation Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/CommandBuilders/LabelCommandBuilder%3Abuild_command This snippet shows the implementation of the build_command method. It first ensures that the specified labels exist and then calls the superclass's build_command method. ```ruby def build_command ensure_labels_exist! super end ``` -------------------------------- ### Fetch Source Full Path Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Retrieves the full path of the source, either directly from options or by querying the API. ```ruby def fetch_source_full_path return options.source_id unless /\A\d+\z/.match?(options.source_id) source_details = network.query_api(build_get_url(nil, {})).first full_path = source_details['full_path'] || source_details['path_with_namespace'] raise ArgumentError, 'A source with given source_id was not found!' if full_path.blank? full_path end ``` -------------------------------- ### Get Tries Value Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Retryable%3Atries Returns the value of the 'tries' attribute. This method is part of the Gitlab::Triage::Retryable module. ```ruby def tries @tries end ``` -------------------------------- ### Get Merge Requests Count for an Issue Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Issue Retrieves the count of merge requests associated with the issue. It caches the result. ```ruby @merge_requests_count ||= resource.dig(:merge_requests_count) ``` -------------------------------- ### Running on Self-Hosted GitLab Instance (Policy File) Source: https://www.rubydoc.info/gems/gitlab-triage Alternatively, you can configure the host URL for a self-hosted GitLab instance within the policy file using the `host_url` key. ```yaml host_url: https://gitlab.host.com resource_rules: ``` -------------------------------- ### Get Filter Names Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/BaseConditionsFilter.params_filter_names Class method to retrieve the names of filters. It defaults to using `filter_parameters` if no parameters are provided. ```ruby def self.params_filter_names(params = nil) params ||= filter_parameters params.pluck(:name) end ``` -------------------------------- ### State Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters for open issues or merge requests. This is a common condition for managing active work items. ```yaml conditions: state: opened ``` -------------------------------- ### Policy Name Field Example Source: https://www.rubydoc.info/gems/gitlab-triage Illustrates the basic structure for defining a policy name within a triage policy file. ```yaml name: Policy name ``` -------------------------------- ### Process Summary Method Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Processes a single summary definition. It sets up a policy and then processes the actions defined within the summary. ```ruby # File 'lib/gitlab/triage/engine.rb', line 310 def process_summary(resource_type, summary_definition) puts Gitlab::Triage::UI.header("Processing summary: **#{summary_definition[:name]}**", char: '~') puts summary_parts_for_rules(resource_type, summary_definition[:rules]) do |summary_resources| policy = Policies::SummaryPolicy.new( resource_type, summary_definition, summary_resources, network) process_action(policy) end end ``` -------------------------------- ### Get API Token Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/RestAPINetwork Retrieves the API token from the options object. This token is used for authenticating requests to the GitLab API. ```ruby # File 'lib/gitlab/triage/rest_api_network.rb', line 155 def token options.token end ``` -------------------------------- ### Get Labels Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable Retrieves an array of label names from the resource and maps them to Label objects. Assumes labels are simple names. ```ruby # File 'lib/gitlab/triage/resource/shared/issuable.rb', line 23 def labels @labels ||= resource[:labels] # an array of label names .map { |label| Label.new({ name: label }, parent: self) } end ``` -------------------------------- ### Get Author Username Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Shared/Issuable%3Aauthor Retrieves the author's username from the resource. It uses `resource.dig` to safely access nested data. ```ruby def author @author ||= resource.dig(:author, :username) end ``` -------------------------------- ### Get Limiter Parameter Names Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/LimiterValidator Retrieves the names of defined parameters for limiters. This is a private method used internally for validation. ```ruby # File 'lib/gitlab/triage/validators/limiter_validator.rb', line 10 def params_limiter_names @parameter_definitions.pluck(:name) end ``` -------------------------------- ### Build and join items Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder%3Aitems This private method builds a collection of items by mapping over resources and joining them with a separator. It uses memoization to ensure the items are built only once. ```ruby def items @items ||= @resources.map { |x| build_item(x) }.join(@separator) end ``` -------------------------------- ### Iteration Condition Example Source: https://www.rubydoc.info/gems/gitlab-triage Filters resources that are not part of any iteration. Use this when you need to identify items outside of defined sprints or cycles. ```yaml conditions: iteration: none ``` -------------------------------- ### Fetch Resources using REST and GraphQL APIs Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine%3Afetch_resources This snippet demonstrates the fetch_resources method, which handles fetching resources using either the REST API or GraphQL API. It includes logic for building GraphQL queries and decorating REST-fetched resources with GraphQL data. ```ruby def fetch_resources(resource_type, expanded_conditions, rule_definition) resources = [] if rule_definition[:api] == 'graphql' graphql_query_options = { source: source_full_path } if options.resource_reference expanded_conditions[:iids] = options.resource_reference[1..] graphql_query_options[:iids] = [expanded_conditions[:iids]] end graphql_query = build_graphql_query(resource_type, expanded_conditions, true) resources = graphql_network.query(graphql_query, **graphql_query_options) else # FIXME: Epics listing endpoint doesn't support filtering by `iids`, so instead we # get a single epic when `--resource-reference` is given for epics. # Because of that, the query could return a single epic, so we make sure we get an array. resources = Array(network.query_api(build_get_url(resource_type, expanded_conditions))) iids = resources.pluck('iid').map(&:to_s) expanded_conditions[:iids] = iids graphql_query = build_graphql_query(resource_type, expanded_conditions) graphql_resources = graphql_network.query(graphql_query, source: source_full_path, iids: iids) if graphql_query.any? decorate_resources_with_graphql_data(resources, graphql_resources) end resources end ``` -------------------------------- ### Get Condition Value (Member Usernames) Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/MemberConditionsFilter Retrieves the usernames of members associated with the condition. This is used to check against the resource's value. ```ruby def condition_value members.pluck(:username) end ``` -------------------------------- ### Get Filter Parameters Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/BaseConditionsFilter.params_filter_names Class method that returns an empty array, intended to be overridden by subclasses to define their specific filter parameters. ```ruby def self.filter_parameters [] end ``` -------------------------------- ### description_resource Method Implementation Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder%3Adescription_resource This snippet shows the implementation of the private description_resource method. It merges several attributes to create a resource object. ```ruby def description_resource title_resource.merge( title: title, items: items, resources: @resources) end ``` -------------------------------- ### Get Summary Title Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/EntityBuilders/SummaryBuilder Retrieves the summary's title, building it using build_text with the title template if it hasn't been generated yet. ```ruby def title @title ||= build_text(title_resource, @title_template) end ``` -------------------------------- ### Build URL Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/UrlBuilders/UrlBuilder%3Abuild Constructs a URL by appending resource ID, sub-resource type, and parameters to a base URL. Ensure resource_id and sub_resource_type are set before calling. ```ruby def build url = base_url url << "/#{percent_encode(@resource_id.to_s)}" if @resource_id url << "/#{@sub_resource_type}" if @sub_resource_type url << params_string if @params url end ``` -------------------------------- ### Assert Source Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Engine Ensures that a source is provided either via the --source option or the --all option. ```ruby def assert_source! return if options.source return if options.all raise ArgumentError, 'A source is needed (pass it with the `--source` option)!' end ``` -------------------------------- ### succ Method Implementation Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Resource/Milestone%3Asucc Returns the next active milestone in the sequence. It relies on the current index and a collection of all active milestones with start dates. ```ruby def succ index = current_index all_active_with_start_date[index.succ] if index end ``` -------------------------------- ### Builds the resource query string Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlQueries/QueryBuilder This method constructs the query string for various resource conditions, including date, author username, milestone, state, and iids. It delegates to specific builders for labels and other resource-specific queries based on the resource type. ```ruby def resource_query condition_queries = [] condition_queries << QueryParamBuilders::BaseParamBuilder.new('includeSubgroups', true, with_quotes: false) if source_type == 'group' conditions.each do |condition, condition_params| condition_queries << QueryParamBuilders::DateParamBuilder.new(condition_params) if condition.to_s == 'date' condition_queries << QueryParamBuilders::BaseParamBuilder.new('authorUsername', condition_params) if condition.to_s == 'author_username' condition_queries << QueryParamBuilders::BaseParamBuilder.new('milestoneTitle', condition_params) if condition.to_s == 'milestone' condition_queries << QueryParamBuilders::BaseParamBuilder.new('state', condition_params, with_quotes: false) if condition.to_s == 'state' condition_queries << QueryParamBuilders::BaseParamBuilder.new('iids', '$iids', with_quotes: false) if condition.to_s == 'iids' case resource_type when 'issues' condition_queries << issues_label_query(condition, condition_params) condition_queries << issues_type_query(condition, condition_params) when 'merge_requests' condition_queries << merge_requests_label_query(condition, condition_params) condition_queries << merge_requests_resource_query(condition, condition_params) end end condition_queries .compact .map(&:build_param) .join end ``` -------------------------------- ### Get Label Command String Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/CommandBuilders/LabelCommandBuilder%3Aslash_command_string Returns the string representation of the label slash command. This is used to identify and trigger the label command functionality. ```ruby def slash_command_string "/label" end ``` -------------------------------- ### Initialize Filter Variables Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/NoAdditionalLabelsConditionsFilter Initializes the filter with the attribute to check (labels) and the expected set of labels. This method is called during the filter's setup. ```ruby def initialize_variables(expected_labels) @attribute = :labels @expected_labels = expected_labels end ``` -------------------------------- ### GraphqlNetwork Options Attribute Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/GraphqlNetwork Returns the options object associated with the GraphqlNetwork instance. ```ruby def options @options end ``` -------------------------------- ### Get Resource Name Value Source: https://www.rubydoc.info/gems/gitlab-triage/Gitlab/Triage/Filters/NameConditionsFilter Retrieves the name attribute from the resource being filtered. This method accesses the resource's name based on the initialized attribute. ```ruby def resource_value @resource[@attribute] end ```