github-actions[bot] commented on code in PR #41860:
URL: https://github.com/apache/beam/pull/41860#discussion_r4761265122


##########
infra/gemini_code_review/prepare_context.js:
##########
@@ -0,0 +1,525 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+module.exports = async function prepareContext({ github, context, core }) {
+  const fs = require('fs');
+  const path = require('path');
+
+  const owner = context.repo.owner;
+  const repo = context.repo.repo;
+  const prNumber = Number(process.env.PR_NUMBER);
+
+  const ctxDir = path.resolve('pr_context');
+  const headFilesDir = path.join(ctxDir, 'head_files');
+  fs.rmSync(ctxDir, { recursive: true, force: true });
+  fs.mkdirSync(headFilesDir, { recursive: true });
+
+  function parseDiffHunks(patch) {
+    const right = [];
+    const left = [];
+    if (!patch) return { right, left };
+    let rCur = null;
+    let lCur = null;
+    let rHunk = null;
+    let lHunk = null;
+    const flush = () => {
+      if (rHunk && rHunk.length > 0) {
+        right.push([rHunk[0], rHunk[rHunk.length - 1]]);
+      }
+      if (lHunk && lHunk.length > 0) {
+        left.push([lHunk[0], lHunk[lHunk.length - 1]]);
+      }
+      rHunk = null;
+      lHunk = null;
+    };
+    for (const line of patch.split('\n')) {
+      const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
+      if (match) {
+        flush();
+        lCur = Number(match[1]);
+        rCur = Number(match[2]);
+        rHunk = [];
+        lHunk = [];
+        continue;
+      }
+      if (rCur === null) continue;
+      if (line.startsWith('+')) {
+        rHunk.push(rCur++);
+      } else if (line.startsWith('-')) {
+        lHunk.push(lCur++);
+      } else if (line.startsWith(' ')) {
+        rHunk.push(rCur++);
+        lHunk.push(lCur++);
+      }
+    }
+    flush();
+    return { right, left };
+  }
+
+  function truncateText(text, maxBytes, label) {
+    const buf = Buffer.from(text, 'utf8');
+    if (buf.length <= maxBytes) return text;
+    return (
+      buf.subarray(0, maxBytes).toString('utf8') +
+      `\n\n[... ${label} truncated at ${maxBytes} bytes (total ${buf.length} 
bytes) ...]\n`
+    );
+  }
+
+  const { data: pr } = await github.rest.pulls.get({
+    owner,
+    repo,
+    pull_number: prNumber,
+  });
+  const headSha = pr.head.sha;
+  fs.writeFileSync(path.join(ctxDir, 'head_sha.txt'), headSha, 'utf8');
+
+  const [commits, files, reviews, reviewComments, issueComments] = await 
Promise.all([
+    github.paginate(github.rest.pulls.listCommits, {
+      owner,
+      repo,
+      pull_number: prNumber,
+      per_page: 100,
+    }),
+    github.paginate(github.rest.pulls.listFiles, {
+      owner,
+      repo,
+      pull_number: prNumber,
+      per_page: 100,
+    }),
+    github.paginate(github.rest.pulls.listReviews, {
+      owner,
+      repo,
+      pull_number: prNumber,
+      per_page: 100,
+    }),
+    github.paginate(github.rest.pulls.listReviewComments, {
+      owner,
+      repo,
+      pull_number: prNumber,
+      per_page: 100,
+    }),
+    github.paginate(github.rest.issues.listComments, {
+      owner,
+      repo,
+      issue_number: prNumber,
+      per_page: 100,
+    }),
+  ]);
+
+  const validLines = {};
+  const longJavaLines = [];
+  for (const f of files) {
+    validLines[f.filename] = parseDiffHunks(f.patch);
+    if (f.filename.endsWith('.java') && f.patch) {
+      let rCur = null;
+      for (const line of f.patch.split('\n')) {
+        const match = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
+        if (match) {
+          rCur = Number(match[1]);
+          continue;
+        }
+        if (rCur === null) continue;
+        if (line.startsWith('+')) {
+          const content = line.slice(1).replace(/\r$/, '');
+          const trimmed = content.trim();
+          if (
+            content.length > 100 &&
+            !trimmed.startsWith('import ') &&
+            !trimmed.startsWith('package ') &&
+            !content.includes('http://') &&
+            !content.includes('https://')
+          ) {
+            longJavaLines.push(`${f.filename}:${rCur} (${content.length} 
chars): ${content}`);
+          }
+          rCur++;
+        } else if (line.startsWith(' ')) {
+          rCur++;
+        }
+      }
+    }
+  }
+  fs.writeFileSync(
+    path.join(ctxDir, 'valid_lines.json'),
+    JSON.stringify(validLines, null, 2),
+    'utf8'
+  );
+  fs.writeFileSync(
+    path.join(ctxDir, 'java_line_length.txt'),
+    longJavaLines.length ? longJavaLines.join('\n') + '\n' : '',
+    'utf8'
+  );
+
+  function addDiffLineNumbers(diffText) {
+    let lCur = null;
+    let rCur = null;
+    const out = [];
+    for (const line of diffText.split('\n')) {

Review Comment:
   **🟡 Medium**: `addDiffLineNumbers` only resets `lCur`/`rCur` on `diff --git 
`, `--- `, and `+++ ` headers, whereas `parseDiffHunks` flushes and ignores 
non-`+`/`-`/` ` lines. In unified diffs where a file lacks a newline at EOF (`\ 
No newline at end of file`) or where commit headers/extended diff headers 
appear between hunks, this is handled by the `else` branch, **except** if a 
trailing commit message or git signature line starting with a space (` `) 
appears after a hunk (for example in `format-patch` or multi-commit diffs), 
which would be mis-numbered as part of the preceding hunk. Resetting `lCur = 
null; rCur = null;` when encountering `\` or non-hunk lines (similar to 
`parseDiffHunks`) prevents stray lines from advancing `lCur`/`rCur`.



##########
infra/gemini_code_review/prepare_context.js:
##########
@@ -0,0 +1,525 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+'use strict';
+
+module.exports = async function prepareContext({ github, context, core }) {
+  const fs = require('fs');
+  const path = require('path');
+
+  const owner = context.repo.owner;
+  const repo = context.repo.repo;
+  const prNumber = Number(process.env.PR_NUMBER);
+
+  const ctxDir = path.resolve('pr_context');
+  const headFilesDir = path.join(ctxDir, 'head_files');
+  fs.rmSync(ctxDir, { recursive: true, force: true });
+  fs.mkdirSync(headFilesDir, { recursive: true });
+
+  function parseDiffHunks(patch) {
+    const right = [];
+    const left = [];
+    if (!patch) return { right, left };
+    let rCur = null;
+    let lCur = null;
+    let rHunk = null;
+    let lHunk = null;
+    const flush = () => {
+      if (rHunk && rHunk.length > 0) {
+        right.push([rHunk[0], rHunk[rHunk.length - 1]]);
+      }
+      if (lHunk && lHunk.length > 0) {
+        left.push([lHunk[0], lHunk[lHunk.length - 1]]);
+      }
+      rHunk = null;
+      lHunk = null;
+    };
+    for (const line of patch.split('\n')) {
+      const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
+      if (match) {
+        flush();
+        lCur = Number(match[1]);
+        rCur = Number(match[2]);
+        rHunk = [];
+        lHunk = [];
+        continue;
+      }
+      if (rCur === null) continue;
+      if (line.startsWith('+')) {
+        rHunk.push(rCur++);
+      } else if (line.startsWith('-')) {
+        lHunk.push(lCur++);
+      } else if (line.startsWith(' ')) {
+        rHunk.push(rCur++);
+        lHunk.push(lCur++);
+      }
+    }
+    flush();
+    return { right, left };
+  }
+
+  function truncateText(text, maxBytes, label) {
+    const buf = Buffer.from(text, 'utf8');
+    if (buf.length <= maxBytes) return text;
+    return (
+      buf.subarray(0, maxBytes).toString('utf8') +

Review Comment:
   **🟢 Nit**: `buf.subarray(0, maxBytes).toString('utf8')` can slice through 
the middle of a multi-byte UTF-8 character, producing a trailing `U+FFFD` 
replacement character before the truncation notice (which then gets serialized 
into `threads.json`, `checks.json`, or `metadata.json`). Consider using 
`TextDecoder` with `stream: true` (or trimming incomplete trailing continuation 
bytes) so truncated strings always end on a clean code-point boundary.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to