diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 93f0acd6..3c3aabc8 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -510,7 +510,7 @@ or removing a command fails until the table changes in the same commit. | `toolchains.instantiateLaunch` | Expand an enabled tool definition's `launch` template for a selected executable, entry, runtime arguments and arguments; a part the template cannot carry is `plugin.toolchain.launchMismatch`; performs no I/O | | `run.decodeStart` | Validate a plugin backend's `lithe/host/run/start` params against its manifest and the workspace, and return the normalized start with temporary-file paths substituted | | `debug.decodeBackendConfiguration` | Validate a plugin backend's `lithe/host/debug/start` params against its manifest and return the qualified adapter, request, label and configuration | -| `outputLinks.match` | Find the links plugin `outputLinkMatchers` declare in Run or Test console lines, as UTF-16 ranges with candidate paths or a backend function to resolve them | +| `outputLinks.match` | Find the links plugin `outputLinkMatchers` declare in Run or Test console lines, as UTF-16 ranges with candidate paths or a backend function to resolve them, and the web addresses the lines print, as `url` links the host opens in the browser | | `outputLinks.decodeResolution` | Check a matcher's `resolve` function reply and return the 1-based file location to open, or `null` | | `build.detect` | Find every build-system instance the enabled plugins declare in a workspace, with models that need no process | | `build.projectOptions` | Validate a native team's persisted Build options | diff --git a/rust/crates/plugin-output-links/src/lib.rs b/rust/crates/plugin-output-links/src/lib.rs index 9b221dfc..3130f0dd 100644 --- a/rust/crates/plugin-output-links/src/lib.rs +++ b/rust/crates/plugin-output-links/src/lib.rs @@ -3,7 +3,9 @@ //! //! Core owns the whole decision. It checks declarations, finds matches in //! console lines, and turns a match into a workspace location, or into the -//! groups a plugin backend resolves. A host only shows links and opens them. +//! groups a plugin backend resolves. It also links the web addresses a line +//! prints, which no plugin declares, so a server's URL opens in the browser. +//! A host only shows links and opens them. use lithe_plugin_model::{invalid, Validation}; use lithe_protocol::{CoreError, ErrorCode}; @@ -208,12 +210,15 @@ fn request_error(message: &str) -> CoreError { } /// `outputLinks.match`: finds links in console lines with the matchers of -/// every installed plugin, in source order and then declaration order. +/// every installed plugin, in source order and then declaration order, and +/// then the web addresses the lines print. /// -/// Each link reports its line index, its UTF-16 `start` and `length`, the -/// plugin and matcher, and either `location` with `paths` the host opens the -/// first existing one of, or `resolve` with the groups the backend function -/// receives. Matches overlapping an earlier link on the line are skipped. +/// Each link reports its line index and its UTF-16 `start` and `length`. A +/// plugin's link names the plugin and matcher and has either `location` with +/// `paths` the host opens the first existing one of, or `resolve` with the +/// groups the backend function receives; a web address has `url` alone, which +/// the host opens in the browser. Matches overlapping an earlier link on the +/// line are skipped, so a plugin's link wins over an address inside it. pub fn match_lines(payload: Value) -> Result { let request: MatchRequest = serde_json::from_value(payload).map_err(|error| { request_error("Invalid output link match request.").with_details(error.to_string()) @@ -299,10 +304,71 @@ pub fn match_lines(payload: Value) -> Result { links.push(link); } } + for (start, end) in web_addresses(scanned) { + if taken.len() >= MAX_LINKS_PER_LINE { + break; + } + if taken + .iter() + .any(|(taken_start, taken_end)| start < *taken_end && *taken_start < end) + { + continue; + } + taken.push((start, end)); + links.push(json!({ + "line": line_index, + "start": utf16_len(&scanned[..start]), + "length": utf16_len(&scanned[start..end]), + "url": &scanned[start..end], + })); + } } + // A line's plugin links come first and its addresses after them, so the + // links of a line are ordered by where they start. + links.sort_by_key(|link| (link["line"].as_u64(), link["start"].as_u64())); Ok(json!({ "links": links })) } +/// The byte ranges of the `http` and `https` addresses in `line`. An address +/// runs until whitespace or a character URLs do not contain unencoded; the +/// punctuation that ends a sentence after it, and a closing bracket it did +/// not open, are not part of it. +fn web_addresses(line: &str) -> Vec<(usize, usize)> { + static ADDRESS: OnceLock = OnceLock::new(); + let address = ADDRESS.get_or_init(|| { + Regex::new(r#"(?i)\bhttps?://[^\s<>"'`\x00-\x1f\x7f]+"#) + .expect("the address pattern is valid") + }); + let mut ranges = Vec::new(); + for found in address.find_iter(line) { + let text = found.as_str(); + let mut end = text.len(); + while let Some(last) = text[..end].chars().next_back() { + let unbalanced = |open: char, close: char| { + last == close + && text[..end].matches(close).count() > text[..end].matches(open).count() + }; + if ".,;:!?".contains(last) + || unbalanced('(', ')') + || unbalanced('[', ']') + || unbalanced('{', '}') + { + end -= last.len_utf8(); + } else { + break; + } + } + // An address needs a host after the scheme. + if text[..end] + .split_once("://") + .is_some_and(|(_, rest)| !rest.is_empty()) + { + ranges.push((found.start(), found.start() + end)); + } + } + ranges +} + /// The longest prefix of `line` within `limit` bytes that ends on a /// character boundary. fn prefix(line: &str, limit: usize) -> &str { @@ -444,6 +510,49 @@ pub fn decode_resolution(payload: Value) -> Result { mod tests { use super::*; + fn addresses(line: &str) -> Vec<&str> { + web_addresses(line) + .into_iter() + .map(|(start, end)| &line[start..end]) + .collect() + } + + #[test] + fn web_addresses_end_before_trailing_punctuation_and_unopened_brackets() { + assert_eq!( + addresses("Local: http://localhost:8080/, see (https://example.org/a_(b)) now."), + ["http://localhost:8080/", "https://example.org/a_(b)"] + ); + assert_eq!( + addresses("Swagger UI: HTTP://127.0.0.1:8080/swagger-ui/index.html?x=1&y=[2]"), + ["HTTP://127.0.0.1:8080/swagger-ui/index.html?x=1&y=[2]"] + ); + // Quotes, angle brackets and the scheme alone end or are no address. + assert_eq!( + addresses(" \"https://b.test\" http:// ftp://c.test mailto:x"), + ["http://a.test/x", "https://b.test"] + ); + // A scheme inside a word is not the start of an address. + assert!(addresses("nothttp://a.test").is_empty()); + } + + #[test] + fn a_plugin_link_wins_over_an_address_it_contains() { + let reply = match_lines(json!({ + "scope": "run", "platform": "linux", "workspaceRoots": ["/w"], + "sources": [{"pluginID": "p", "matchers": [{ + "id": "m", "pattern": r"see (?P\S+) \S+", "resolve": {"function": "f"} + }]}], + "lines": ["see a.txt https://x.test/ then https://y.test/"] + })) + .unwrap(); + let links = reply["links"].as_array().unwrap(); + assert_eq!(links.len(), 2, "{links:?}"); + assert_eq!(links[0]["matcherID"], "m"); + assert_eq!(links[1]["url"], "https://y.test/"); + assert_eq!(links[1]["start"], 31); + } + fn matcher(value: Value) -> OutputLinkMatcher { serde_json::from_value(value).unwrap() } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 0c8ca9a1..3aa46044 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -2743,9 +2743,15 @@ Core owns the decision, so every host links the same text: line?, column?}`: the host opens the first existing path) or `resolve` (`{function, groups}`). `start` and `length` count UTF-16 code units of the line. Matches are found in source order and then declaration order, and a match - overlapping an earlier link is skipped. A request carries at most 256 lines, - 64 sources and 16 roots; a line is scanned up to 4096 bytes and links at most - 8 times. + overlapping an earlier link is skipped. Core then links the `http` and + `https` addresses a line prints, which no plugin declares: such a link is + `{line, start, length, url}` with no plugin, the host opens `url` in the + browser, and an address inside a plugin's link stays part of that link. An + address ends at whitespace, a quote or an angle bracket, without the + sentence punctuation after it or a closing bracket it did not open. The links + of a line are returned in the order they start. A request carries at most 256 + lines, 64 sources and 16 roots; a line is scanned up to 4096 bytes and links + at most 8 times. - `outputLinks.decodeResolution` takes `{reply}` (what the function answered) and returns the location to open, `{path, line?, column?}` with 1-based positions, or `null`. A reply opens only a `file:` URI and only the members diff --git a/shared/plugins/contract/v1/fixtures/run/output-link-matchers.json b/shared/plugins/contract/v1/fixtures/run/output-link-matchers.json index 1370b78e..5ea31a6e 100644 --- a/shared/plugins/contract/v1/fixtures/run/output-link-matchers.json +++ b/shared/plugins/contract/v1/fixtures/run/output-link-matchers.json @@ -1,6 +1,39 @@ { - "description": "Requests of outputLinks.match and the links Core returns, and replies of a matcher's resolve function with what outputLinks.decodeResolution returns. `start` and `length` count UTF-16 code units of the console line. A relative path yields one candidate per workspace root, and a path outside every root yields no link.", + "description": "Requests of outputLinks.match and the links Core returns, and replies of a matcher's resolve function with what outputLinks.decodeResolution returns. `start` and `length` count UTF-16 code units of the console line. A relative path yields one candidate per workspace root, and a path outside every root yields no link. Web addresses are linked without a matcher, as `url` links, unless a plugin link covers them.", "match": [ + { + "name": "a web address links without a matcher and stops before trailing punctuation", + "request": { + "scope": "run", + "platform": "macos", + "workspaceRoots": ["/work/app"], + "sources": [ + { + "pluginID": "example.script", + "matchers": [ + { "id": "frame", "pattern": "File \"(?P[^\"]+)\", line (?P\\d+)" } + ] + } + ], + "lines": [ + "Tomcat started on http://localhost:8080/ (see https://example.org/docs_(v2)).", + " File \"/work/app/main.script\", line 12, from https://example.org/x" + ] + }, + "links": [ + { "line": 0, "start": 18, "length": 22, "url": "http://localhost:8080/" }, + { "line": 0, "start": 46, "length": 29, "url": "https://example.org/docs_(v2)" }, + { + "line": 1, + "start": 2, + "length": 37, + "pluginID": "example.script", + "matcherID": "frame", + "location": { "paths": ["/work/app/main.script"], "line": 12 } + }, + { "line": 1, "start": 46, "length": 21, "url": "https://example.org/x" } + ] + }, { "name": "a frame in the workspace links to its line", "request": { diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 53b8a91b..12497129 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -138,6 +138,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#84](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/84) | [@1lck](https://github.com/1lck) | — | `outputLinkMatchers` 0 内的补充 | 运行和测试控制台里的网址可点击([1lck/Lithe-IDEA#1822](https://github.com/1lck/Lithe-IDEA/issues/1822)):`outputLinks.match` 跑完插件匹配器后,再识别行内的 `http`/`https` 网址,返回不带插件的 `{line, start, length, url}`,宿主在浏览器中打开。网址止于空白、引号、尖括号,不含句末标点和未配对的右括号;和插件链接重叠时插件链接优先;一行内的链接按起点排序。fixture `output-link-matchers.json` 新增一例。清单格式和能力版本不变,插件无需改动;没有新增宿主方法或通知。 | | [#83](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/83) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `languages` 0 内的补充 | 编辑器的 TextMate 引擎按 vscode-textmate 的方式运行语法的 `injections`([1lck/Lithe-IDEA#2112](https://github.com/1lck/Lithe-IDEA/issues/2112)):只有给文档分词的那个语法应用自己的 `injections`,被它包含的语法的不生效;某个位置的 scope 符合选择器时,注入规则和当前规则一起尝试,起点更靠前的匹配胜出,起点相同时当前规则胜出,除非选择器带 `L:` 前缀。Core 随之校验它:`injections` 是以 scope 选择器为键的规则对象,最多 64 项,选择器 1–1024 字节,每条规则和其他规则一样检查并计入 16384 条上限,违反时以 `plugin.grammar.invalid`(字段 `grammar.injections[.<选择器>…]`)拒绝。`injectionSelector` 仍不运行、不检查。清单格式和能力版本不变,不运行 `injections` 的旧宿主照常加载这些语法;没有新增宿主方法或通知。 | | [#79](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/79) | [@1lck](https://github.com/1lck) | API-19 | **`sourceSettings` 1** | 原生来源设置可以做成“项目结构”页([1lck/Lithe-IDEA#2086](https://github.com/1lck/Lithe-IDEA/issues/2086)):分组布局 `sidebar` 把来源列成左侧模块列表,来源用 `parent` 嵌套(同组、在前、最多 8 层);字段 `section` 在 `sidebar` 中是标签页、在 `form` 中是小标题;新字段类型 `entryList` 是有序的类型化条目列表,`entryKinds` 声明添加菜单(`file` 可带扩展名、`directory`、`choice` 带可选项),`attributes` 声明至多 4 个布尔或枚举列。条目的 `title`、`detail` 只用于显示,比较和写回时忽略;新增的 `choice` 条目必须来自当前可选项或原值。`SourceInput` 新增 `entries`,`effectiveDisplays` 对条目列表给出 `count`。快照 `version` 仍为 0;用到这些成员的插件声明 `sourceSettings: 1`,只支持 0 的宿主不会安装。新增 fixture `settings-sources-modules.json`。没有新增宿主方法或通知。 | | [#77](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/77) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | `buildSystems` 0 内的说明修正 | Core 不再内置运行发现探测器([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856) 第 4 项):原来按 `Cargo.toml`、`go.mod`、`package.json`、`pyproject.toml`、`Makefile`、`justfile`、`Procfile`、`compose.yaml` 自己生成的 Run 配置、指纹输入和工具链要求全部删除。Run 列表里自动生成的条目只来自已启用构建插件声明的 `buildSystems[].run`,模型何时过期只由插件的 `sync.watch` 决定。插件想让项目出现在 Run 列表里,就要声明 `run`。契约 README 只改了一句措辞(不再提“探测器生成的 Run 配置”);清单字段、校验、fixture 和能力版本都没有变,没有新增宿主方法或通知。 |