project.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import type { Dirent } from "node:fs";
  2. import { access, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
  3. import path from "node:path";
  4. import { inside } from "../lib/path.js";
  5. import { androidApiLevel } from "./config.js";
  6. import { templateFiles } from "./project-template.js";
  7. import { sdkRoot } from "./sdk.js";
  8. type Found = {
  9. root?: string;
  10. gradleRoots: string[];
  11. modules: string[];
  12. variants: string[];
  13. applicationIds: string[];
  14. manifests: string[];
  15. apks: string[];
  16. hasWrapper: boolean;
  17. hasGradleProperties: boolean;
  18. hasLocalProperties: boolean;
  19. warnings: string[];
  20. };
  21. export async function discover(dir = process.cwd()): Promise<Found> {
  22. const gradleRoots: string[] = [];
  23. const manifests: string[] = [];
  24. await walkProjectFiles(dir, 5, async (file, item) => {
  25. if (item.isFile() && /^settings\.gradle(\.kts)?$/.test(item.name))
  26. gradleRoots.push(path.relative(dir, path.dirname(file)));
  27. if (item.isFile() && item.name === "AndroidManifest.xml")
  28. manifests.push(path.relative(dir, file));
  29. });
  30. const root = gradleRoots.find((item) => item === "") ?? gradleRoots[0];
  31. const absRoot = root === undefined ? undefined : path.join(dir, root);
  32. const modules = absRoot ? await modulesFor(absRoot) : [];
  33. const ids = absRoot ? await applicationIds(absRoot) : [];
  34. const apks = absRoot
  35. ? (await findApks(absRoot, modules)).map((file) => path.relative(dir, file))
  36. : [];
  37. const hasWrapper = absRoot
  38. ? await exists(path.join(absRoot, process.platform === "win32" ? "gradlew.bat" : "gradlew"))
  39. : false;
  40. const hasGradleProperties = absRoot
  41. ? await exists(path.join(absRoot, "gradle.properties"))
  42. : false;
  43. const hasLocalProperties = absRoot ? await exists(path.join(absRoot, "local.properties")) : false;
  44. const warnings = projectWarnings({ hasWrapper, hasGradleProperties, hasLocalProperties });
  45. return {
  46. root,
  47. gradleRoots,
  48. modules,
  49. variants: ["debug"],
  50. applicationIds: ids,
  51. manifests,
  52. apks,
  53. hasWrapper,
  54. hasGradleProperties,
  55. hasLocalProperties,
  56. warnings,
  57. };
  58. }
  59. function projectWarnings(input: {
  60. hasWrapper: boolean;
  61. hasGradleProperties: boolean;
  62. hasLocalProperties: boolean;
  63. }): string[] {
  64. const warnings: string[] = [];
  65. if (!input.hasGradleProperties) {
  66. warnings.push(
  67. "Missing gradle.properties. Add android.useAndroidX=true for AndroidX/Compose projects.",
  68. );
  69. }
  70. if (!input.hasLocalProperties) {
  71. warnings.push(
  72. "Missing local.properties. Add sdk.dir=<Android SDK path> when Gradle cannot infer the SDK from the environment.",
  73. );
  74. }
  75. if (!input.hasWrapper) {
  76. warnings.push("Missing Gradle wrapper. Install Gradle or generate ./gradlew before building.");
  77. }
  78. return warnings;
  79. }
  80. export async function create(input: {
  81. name: string;
  82. packageName?: string;
  83. dir?: string;
  84. minSdk?: number;
  85. compileSdk?: number;
  86. overwrite?: boolean;
  87. }) {
  88. const cwd = process.cwd();
  89. const name = cleanName(input.name);
  90. const root = inside(cwd, input.dir || name);
  91. const pkg = packageName(input.packageName || `com.example.${slug(name)}`);
  92. const minSdk = sdkLevel(input.minSdk ?? 23, "minSdk");
  93. const compileSdk = sdkLevel(input.compileSdk ?? androidApiLevel(), "compileSdk");
  94. const files = templateFiles(root, pkg, await sdkRoot());
  95. if (!input.overwrite) {
  96. const hits = await present(files.map((item) => item.path));
  97. if (hits.length) {
  98. throw new Error(
  99. `Refusing to overwrite existing Android app files: ${hits.map((file) => path.relative(cwd, file)).join(", ")}`,
  100. );
  101. }
  102. }
  103. for (const file of files) {
  104. await mkdir(path.dirname(file.path), { recursive: true });
  105. await writeFile(file.path, file.body({ name, pkg, minSdk, compileSdk }), "utf8");
  106. }
  107. return {
  108. root: path.relative(cwd, root) || ".",
  109. module: "app",
  110. variant: "debug",
  111. applicationId: pkg,
  112. files: files.map((file) => path.relative(cwd, file.path)),
  113. createdBy: "template",
  114. note: "Build uses ./gradlew when present. If the wrapper is missing, android_build_app can generate it with gradle from PATH.",
  115. };
  116. }
  117. async function modulesFor(root: string): Promise<string[]> {
  118. const settings =
  119. (await readFile(path.join(root, "settings.gradle.kts"), "utf8").catch(() => undefined)) ??
  120. (await readFile(path.join(root, "settings.gradle"), "utf8").catch(() => ""));
  121. const modules = [...settings.matchAll(/include\(([^)]+)\)/g)]
  122. .flatMap((match) =>
  123. [...String(match[1]).matchAll(/["'](:[^"']+)["']/g)].map((hit) => hit[1] ?? ""),
  124. )
  125. .filter(Boolean);
  126. return modules.length ? modules : ["app"];
  127. }
  128. async function applicationIds(root: string): Promise<string[]> {
  129. const ids = new Set<string>();
  130. await walkProjectFiles(root, 5, async (file, item) => {
  131. if (!item.isFile()) return;
  132. if (/build\.gradle(\.kts)?$/.test(item.name)) {
  133. const text = await readFile(file, "utf8").catch(() => "");
  134. for (const match of text.matchAll(
  135. /(?:applicationId|namespace)\s*(?:=|\s)\s*["']([^"']+)["']/g,
  136. )) {
  137. if (match[1]) ids.add(match[1]);
  138. }
  139. }
  140. if (item.name === "AndroidManifest.xml") {
  141. const text = await readFile(file, "utf8").catch(() => "");
  142. const match = text.match(/\bpackage=["']([^"']+)["']/);
  143. if (match?.[1]) ids.add(match[1]);
  144. }
  145. });
  146. return [...ids];
  147. }
  148. export async function findApks(root: string, modules: string[] = []): Promise<string[]> {
  149. const names = modules.length ? modules.map((item) => item.replace(/^:+/, "") || "app") : ["app"];
  150. const roots = [
  151. ...names.map((name) => path.join(root, name, "build", "outputs", "apk")),
  152. path.join(root, "build", "outputs", "apk"),
  153. ];
  154. const hits = await Promise.all(roots.map((dir) => walkApks(dir, 5)));
  155. return unique(hits.flat());
  156. }
  157. async function walkProjectFiles(
  158. dir: string,
  159. depth: number,
  160. cb: (file: string, item: Dirent) => Promise<void>,
  161. ): Promise<void> {
  162. if (depth < 0) return;
  163. const items: Dirent[] = await readdir(dir, { withFileTypes: true }).catch(() => []);
  164. await Promise.all(
  165. items
  166. .filter(
  167. (item) =>
  168. !item.name.startsWith(".") && !["node_modules", "build", ".gradle"].includes(item.name),
  169. )
  170. .map(async (item) => {
  171. const file = path.join(dir, item.name);
  172. await cb(file, item);
  173. if (item.isDirectory()) await walkProjectFiles(file, depth - 1, cb);
  174. }),
  175. );
  176. }
  177. async function walkApks(dir: string, depth: number): Promise<string[]> {
  178. if (depth < 0) return [];
  179. const items = await readdir(dir, { withFileTypes: true }).catch(() => []);
  180. return (
  181. await Promise.all(
  182. items
  183. .filter((item) => !item.name.startsWith("."))
  184. .map(async (item) => {
  185. const file = path.join(dir, item.name);
  186. if (item.isFile() && item.name.endsWith(".apk")) return [file];
  187. if (item.isDirectory()) return walkApks(file, depth - 1);
  188. return [];
  189. }),
  190. )
  191. ).flat();
  192. }
  193. async function present(files: string[]): Promise<string[]> {
  194. return (
  195. await Promise.all(
  196. files.map(async (file) => {
  197. const hit = await exists(file);
  198. return hit ? file : undefined;
  199. }),
  200. )
  201. ).filter((file): file is string => file !== undefined);
  202. }
  203. async function exists(file: string): Promise<boolean> {
  204. return access(file)
  205. .then(() => true)
  206. .catch(() => false);
  207. }
  208. function cleanName(value: string): string {
  209. const out = value.replace(/[^A-Za-z0-9_]/g, "");
  210. if (!out) throw new Error("App name must contain letters or numbers.");
  211. if (/^[0-9]/.test(out)) return `App${out}`;
  212. return out;
  213. }
  214. function packageName(value: string): string {
  215. const parts = value.split(".");
  216. const good = parts.length > 1 && parts.every((part) => /^[A-Za-z][A-Za-z0-9_]*$/.test(part));
  217. if (!good) throw new Error(`Invalid Android package name: ${value}`);
  218. return value;
  219. }
  220. function sdkLevel(value: number, field: string): number {
  221. if (!Number.isInteger(value) || value < 21 || value > 99)
  222. throw new Error(`Invalid ${field}: ${value}`);
  223. return value;
  224. }
  225. function slug(value: string): string {
  226. const out = value
  227. .replace(/[^A-Za-z0-9_]/g, "_")
  228. .replace(/_+/g, "_")
  229. .replace(/^_|_$/g, "")
  230. .toLowerCase();
  231. if (/^[0-9]/.test(out)) return `app_${out}`;
  232. return out || "app";
  233. }
  234. function unique(items: string[]): string[] {
  235. return [...new Set(items)];
  236. }