Skip to content

Commit

Permalink
feat: read platform specific tauri configs (#399)
Browse files Browse the repository at this point in the history
  • Loading branch information
FabianLars committed Mar 21, 2023
1 parent d2f4919 commit 4c72e78
Show file tree
Hide file tree
Showing 13 changed files with 241 additions and 121 deletions.
5 changes: 5 additions & 0 deletions .changes/platform-configs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'action': patch
---

Automatically read platform specific tauri config files.
4 changes: 2 additions & 2 deletions dist/index.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"glob-gitignore": "^1.0.14",
"ignore": "5.2.4",
"json5": "2.2.3",
"lodash.merge": "^4.6.2",
"string-argv": "0.3.1",
"tslib": "2.5.0"
},
Expand Down
3 changes: 2 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

40 changes: 23 additions & 17 deletions src/build.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { platform } from 'os';
import { readFileSync, existsSync, copyFileSync, writeFileSync } from 'fs';
import { join } from 'path';

import { initProject } from './init-project';
import { getRunner } from './runner';
import { getInfo, getTargetDir, getWorkspaceDir, hasDependency } from './utils';
import {
getInfo,
getTargetDir,
getTargetInfo,
getWorkspaceDir,
hasDependency,
} from './utils';

import type { Artifact, BuildOptions } from './types';

Expand All @@ -15,7 +20,16 @@ export async function buildProject(
): Promise<Artifact[]> {
const runner = await getRunner(root, buildOpts.tauriScript);

const info = getInfo(root, buildOpts.configPath);
const tauriArgs = debug
? ['--debug', ...(buildOpts.args ?? [])]
: buildOpts.args ?? [];

const found = [...tauriArgs].findIndex((e) => e === '-t' || e === '--target');
const targetPath = found >= 0 ? [...tauriArgs][found + 1] : undefined;

const targetInfo = getTargetInfo(targetPath);

const info = getInfo(root, buildOpts.configPath, targetInfo);

const app = info.tauriPath
? {
Expand All @@ -38,10 +52,6 @@ export async function buildProject(
writeFileSync(tauriConfPath, JSON.stringify(tauriConf));
}

const tauriArgs = debug
? ['--debug', ...(buildOpts.args ?? [])]
: buildOpts.args ?? [];

let buildCommand;
if (hasDependency('vue-cli-plugin-tauri', root)) {
buildCommand = 'tauri:build';
Expand All @@ -53,7 +63,7 @@ export async function buildProject(

let fileAppName = app.name;
// on Linux, the app product name is converted to kebab-case
if (!['darwin', 'win32'].includes(platform())) {
if (targetInfo.platform === 'linux') {
fileAppName = fileAppName
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
.replace(/([A-Z])([A-Z])(?=[a-z])/g, '$1-$2')
Expand All @@ -63,21 +73,17 @@ export async function buildProject(

const cratePath = getWorkspaceDir(app.tauriPath) ?? app.tauriPath;

const found = [...tauriArgs].findIndex((e) => e === '-t' || e === '--target');
const targetPath = found >= 0 ? [...tauriArgs][found + 1] : '';

const artifactsPath = join(
getTargetDir(cratePath),
targetPath,
targetPath ?? '',
debug ? 'debug' : 'release'
);

let arch =
targetPath.search('-') >= 0 ? targetPath.split('-')[0] : process.arch;

let artifacts: Artifact[] = [];

if (platform() === 'darwin') {
let arch = targetInfo.arch;

if (targetInfo.platform === 'macos') {
if (arch === 'x86_64') {
arch = 'x64';
}
Expand All @@ -91,7 +97,7 @@ export async function buildProject(
join(artifactsPath, `bundle/macos/${fileAppName}.app.tar.gz`),
join(artifactsPath, `bundle/macos/${fileAppName}.app.tar.gz.sig`),
].map((path) => ({ path, arch }));
} else if (platform() === 'win32') {
} else if (targetInfo.platform === 'windows') {
arch = arch.startsWith('i') ? 'x86' : 'x64';

// If multiple Wix languages are specified, multiple installers (.msi) will be made
Expand Down
137 changes: 137 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { existsSync, readFileSync } from 'fs';
import path, { join } from 'path';

import { parse as parseToml } from '@iarna/toml';
import JSON5 from 'json5';
import merge from 'lodash.merge';

import { TauriConfig } from './types';

function _tryParseJsonConfig(contents: string): TauriConfig | null {
try {
const config = JSON.parse(contents) as TauriConfig;
return config;
} catch (e) {
// @ts-ignore
console.error(e.message);
return null;
}
}

function _tryParseJson5Config(contents: string): TauriConfig | null {
try {
const config = JSON5.parse(contents) as TauriConfig;
return config;
} catch (e) {
// @ts-ignore
console.error(e.message);
return null;
}
}

function _tryParseTomlConfig(contents: string): TauriConfig | null {
try {
const config = parseToml(contents) as TauriConfig;
return config;
} catch (e) {
// @ts-ignore
console.error(e.message);
return null;
}
}

function readPlatformConfig(
tauriDir: string,
platform: string
): TauriConfig | null {
let path = join(tauriDir, `tauri.${platform}.conf.json`);
if (existsSync(path)) {
const contents = readFileSync(path).toString();
const config = _tryParseJsonConfig(contents);
if (config) return config;
}

path = join(tauriDir, `tauri.${platform}.conf.json5`);
if (existsSync(path)) {
const contents = readFileSync(path).toString();
const config = _tryParseJson5Config(contents);
if (config) return config;
}

path = join(tauriDir, `Tauri.${platform}.toml`);
if (existsSync(path)) {
const contents = readFileSync(path).toString();
const config = _tryParseTomlConfig(contents);
if (config) return config;
}

return null;
}

/// This modifies baseConfig in-place!
export function mergePlatformConfig(
baseConfig: TauriConfig,
tauriDir: string,
target: string
) {
const config = readPlatformConfig(tauriDir, target);

if (config) {
merge(baseConfig, config);
}
}

export function getConfig(tauriDir: string, customPath?: string): TauriConfig {
if (customPath) {
if (!existsSync(customPath)) {
throw `Provided config path \`${customPath}\` does not exist.`;
}

const contents = readFileSync(customPath).toString();
const ext = path.extname(customPath);

if (ext === '.json') {
const config = _tryParseJsonConfig(contents);
if (config) return config;
}

if (ext === '.json5') {
const config = _tryParseJson5Config(contents);
if (config) return config;
}

if (ext === '.toml') {
const config = _tryParseTomlConfig(contents);
if (config) return config;
}

throw `Couldn't parse \`${customPath}\` as ${ext.substring(1)}.`;
}

if (existsSync(join(tauriDir, 'tauri.conf.json'))) {
const contents = readFileSync(join(tauriDir, 'tauri.conf.json')).toString();
const config = _tryParseJsonConfig(contents);
if (config) return config;
console.error("Found tauri.conf.json file but couldn't parse it as JSON.");
}

if (existsSync(join(tauriDir, 'tauri.conf.json5'))) {
const contents = readFileSync(
join(tauriDir, 'tauri.conf.json5')
).toString();
const config = _tryParseJson5Config(contents);
if (config) return config;
console.error(
"Found tauri.conf.json5 file but couldn't parse it as JSON5."
);
}

if (existsSync(join(tauriDir, 'Tauri.toml'))) {
const contents = readFileSync(join(tauriDir, 'Tauri.toml')).toString();
const config = _tryParseTomlConfig(contents);
if (config) return config;
console.error("Found Tauri.toml file but couldn't parse it as TOML.");
}

throw "Couldn't locate or parse tauri config.";
}
1 change: 1 addition & 0 deletions src/external-modules.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
declare module 'glob-gitignore';
declare module 'lodash.merge';
12 changes: 9 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { createRelease } from './create-release';
import { uploadAssets as uploadReleaseAssets } from './upload-release-assets';
import { uploadVersionJSON } from './upload-version-json';
import { buildProject } from './build';
import { execCommand, getInfo, getPackageJson } from './utils';
import { execCommand, getInfo, getPackageJson, getTargetInfo } from './utils';

import type { Artifact, BuildOptions } from './types';

Expand Down Expand Up @@ -55,7 +55,12 @@ async function run(): Promise<void> {
args,
bundleIdentifier,
};
const info = getInfo(projectPath);

const _found = args.findIndex((e) => e === '-t' || e === '--target');
const targetPath = _found >= 0 ? args[_found + 1] : undefined;
const targetInfo = getTargetInfo(targetPath);
const info = getInfo(projectPath, undefined, targetInfo);

const artifacts: Artifact[] = [];
if (includeRelease) {
const releaseArtifacts = await buildProject(projectPath, false, options);
Expand Down Expand Up @@ -107,7 +112,7 @@ async function run(): Promise<void> {
}

if (releaseId) {
if (platform() === 'darwin') {
if (targetInfo.platform === 'macos') {
let i = 0;
for (const artifact of artifacts) {
// updater provide a .tar.gz, this will prevent duplicate and overwriting of
Expand Down Expand Up @@ -138,6 +143,7 @@ async function run(): Promise<void> {
tagName,
releaseId,
artifacts,
targetInfo,
});
}
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion src/init-project.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { writeFileSync } from 'fs';
import { join } from 'path';

import { getConfig } from './config';
import { Runner } from './runner';
import { getConfig, getPackageJson, getTauriDir } from './utils';
import { getPackageJson, getTauriDir } from './utils';

import type { Application, BuildOptions, Info } from './types';

Expand Down
6 changes: 6 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ export interface Info {
wixLanguage: string | string[] | { [language: string]: unknown };
}

export type TargetPlatform = 'android' | 'ios' | 'macos' | 'linux' | 'windows';
export interface TargetInfo {
arch: string;
platform: TargetPlatform;
}

export interface TauriConfig {
package?: {
productName?: string;
Expand Down
4 changes: 3 additions & 1 deletion src/upload-release-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ export async function uploadAssets(releaseId: number, assets: Artifact[]) {

const assetName = getAssetName(asset.path);

const existingAsset = existingAssets.find((a) => a.name === assetName);
const existingAsset = existingAssets.find(
(a) => a.name === assetName.trim().replace(/ /g, '.')
);
if (existingAsset) {
console.log(`Deleting existing ${assetName}...`);
await github.rest.repos.deleteReleaseAsset({
Expand Down
12 changes: 7 additions & 5 deletions src/upload-version-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { getOctokit, context } from '@actions/github';
import { uploadAssets } from './upload-release-assets';
import { getAssetName } from './utils';

import type { Artifact } from './types';
import type { Artifact, TargetInfo } from './types';

type Platform = {
signature: string;
Expand All @@ -29,12 +29,14 @@ export async function uploadVersionJSON({
tagName,
releaseId,
artifacts,
targetInfo,
}: {
version: string;
notes: string;
tagName: string;
releaseId: number;
artifacts: Artifact[];
targetInfo: TargetInfo;
}) {
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error('GITHUB_TOKEN is required');
Expand Down Expand Up @@ -89,7 +91,7 @@ export async function uploadVersionJSON({

const sigFile = artifacts.find((s) => s.path.endsWith('.sig'));
const assetNames = new Set(
artifacts.map((p) => getAssetName(p.path).trim().replace(' ', '.')) // GitHub replaces spaces in asset names with dots
artifacts.map((p) => getAssetName(p.path).trim().replace(/ /g, '.')) // GitHub replaces spaces in asset names with dots
);
let downloadUrl = assets.data
.filter((e) => assetNames.has(e.name))
Expand All @@ -103,9 +105,9 @@ export async function uploadVersionJSON({
tagName ? `/download/${tagName}/` : '/latest/download/'
);

let os = platform() as string;
if (os === 'win32') {
os = 'windows';
let os = targetInfo.platform as string;
if (os === 'macos') {
os = 'darwin';
}

if (downloadUrl && sigFile) {
Expand Down
Loading

0 comments on commit 4c72e78

Please sign in to comment.