|
| 1 | +/* |
| 2 | + * r-utils.ts |
| 3 | + * |
| 4 | + * Copyright (C) 2025 by Posit Software, PBC |
| 5 | + * |
| 6 | + * Unless you have received this program directly from Posit Software pursuant |
| 7 | + * to the terms of a commercial license agreement with Posit Software, then |
| 8 | + * this program is licensed to you under the terms of version 3 of the |
| 9 | + * GNU Affero General Public License. This program is distributed WITHOUT |
| 10 | + * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, |
| 11 | + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the |
| 12 | + * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. |
| 13 | + * |
| 14 | + */ |
| 15 | + |
| 16 | +import * as fs from "fs/promises"; |
| 17 | +import * as path from "path"; |
| 18 | +import { URI } from 'vscode-uri'; |
| 19 | + |
| 20 | +/** |
| 21 | + * Checks if the given folder contains an R package. |
| 22 | + * |
| 23 | + * Determined by: |
| 24 | + * - Presence of a `DESCRIPTION` file. |
| 25 | + * - Presence of `Package:` field. |
| 26 | + * - Presence of `Type: package` field and value. |
| 27 | + * |
| 28 | + * The fields are checked to disambiguate real packages from book repositories using a `DESCRIPTION` file. |
| 29 | + * |
| 30 | + * @param folderPath Folder to check for a `DESCRIPTION` file. |
| 31 | + */ |
| 32 | +export async function isRPackage(folderUri: URI): Promise<boolean> { |
| 33 | + // We don't currently support non-file schemes |
| 34 | + if (folderUri.scheme !== 'file') { |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + const descriptionLines = await parseRPackageDescription(folderUri.fsPath); |
| 39 | + if (!descriptionLines) { |
| 40 | + return false; |
| 41 | + } |
| 42 | + |
| 43 | + const packageLines = descriptionLines.filter(line => line.startsWith('Package:')); |
| 44 | + const typeLines = descriptionLines.filter(line => line.startsWith('Type:')); |
| 45 | + |
| 46 | + const typeIsPackage = (typeLines.length > 0 |
| 47 | + ? typeLines[0].toLowerCase().includes('package') |
| 48 | + : false); |
| 49 | + const typeIsPackageOrMissing = typeLines.length === 0 || typeIsPackage; |
| 50 | + |
| 51 | + return packageLines.length > 0 && typeIsPackageOrMissing; |
| 52 | +} |
| 53 | + |
| 54 | +async function parseRPackageDescription(folderPath: string): Promise<string[]> { |
| 55 | + const filePath = path.join(folderPath, 'DESCRIPTION'); |
| 56 | + |
| 57 | + try { |
| 58 | + const descriptionText = await fs.readFile(filePath, 'utf8'); |
| 59 | + return descriptionText.split(/\r?\n/); |
| 60 | + } catch { |
| 61 | + return ['']; |
| 62 | + } |
| 63 | +} |
0 commit comments