Skip to content
This repository has been archived by the owner on Nov 7, 2023. It is now read-only.

Commit

Permalink
refactor(database): switch to objectbox
Browse files Browse the repository at this point in the history
  • Loading branch information
zyrouge committed Oct 28, 2021
1 parent 1d8d3af commit 9f04017
Show file tree
Hide file tree
Showing 50 changed files with 826 additions and 856 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,5 @@ appimage-builder-cache/
builder.g.yml
assets/data/meta.json
certs
cli/.cache
cli/.cache
lib/**/*.g.dart
133 changes: 133 additions & 0 deletions cli/commands/build_runner/generate/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { dirname, join, relative } from "path";
import chalk from "chalk";
import {
pathExists,
copyFile,
rm,
ensureDir,
readFile,
writeFile,
} from "fs-extra";
import { SpawnError, spawn } from "../../../spawn";
import { config } from "../../../config";
import { Logger } from "../../../logger";

const logger = new Logger("build_runner:generate");

const generated = {
from: join(config.base, "lib"),
to: join(config.base, "lib/modules/database/objectbox"),
pre: {
files: ["objectbox-model.json"],
async do() {
logger.log(
`Restoring files to ${chalk.cyanBright(
relative(config.base, generated.from)
)}`
);

for (const x of generated.pre.files) {
const path = join(generated.to, x);
if (await pathExists(path)) {
await copyFile(path, join(generated.from, x));
}
}
},
},
post: {
files: ["objectbox.g.dart", "objectbox-model.json"],
async do(success: boolean) {
logger.log(
`Moving files to ${chalk.cyanBright(
relative(config.base, generated.to)
)}`
);

await ensureDir(generated.to);

for (const x of generated.post.files) {
const path = join(generated.from, x);

if (success) {
if (/\.g\.dart$/.test(x)) {
await writeFile(
path,
await generated.modifyImports(path, generated.to)
);
}

await copyFile(path, join(generated.to, x));
}

await rm(path);
}
},
},
async modifyImports(path: string, to: string) {
const from = dirname(path);
const content = (await readFile(path)).toString();

const importRegex = /import ['"](?!dart|package:)(.*)['"];/;
const modified = content.replace(RegExp(importRegex, "g"), (str) => {
const match = str.match(importRegex)!;
const importFromPath = join(from, match[1]);
const importToPath = relative(to, importFromPath).replace(
/\\/g,
"/"
);

return `import '${importToPath}';`;
});

return modified;
},
};

const execute = async (force: boolean) => {
try {
await generated.pre.do();

const flags: string[] = [];

if (force) {
flags.push("--delete-conflicting-outputs");
}

await spawn(
"flutter",
["packages", "pub", "run", "build_runner", "build", ...flags],
config.base
);

await generated.post.do(true);
} catch (err) {
await generated.post.do(false);
throw err;
}
};

export const generate = async () => {
logger.log("Running build_runner command...");

try {
await execute(process.argv.includes("-f"));
} catch (err: any) {
if (
err instanceof SpawnError &&
typeof err.result.code === "number" &&
err.result.code === 78
) {
logger.warn(
`Found conflicting outputs, retrying with ${chalk.redBright(
"--delete-conflicting-outputs"
)} flag`
);

await execute(true);
} else {
throw err;
}
}

logger.log("Finished running build_runner command");
};
46 changes: 0 additions & 46 deletions cli/commands/builder_runner/generate/index.ts

This file was deleted.

10 changes: 10 additions & 0 deletions cli/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ export const run = async (fn: () => Promise<void>) => {
);
} catch (err) {
console.error(chalk.redBright(err));

if (err instanceof Error && err.stack) {
const stackLines = err.stack.split("\n");
if (stackLines[0] === err.toString()) {
err.stack = stackLines.slice(1).join("\n");
}

console.error(chalk.gray(err.stack));
}

console.log(
`\n${logSymbols.error} Failed in ${chalk.redBright(
prettyMs(Date.now() - startedAt)
Expand Down
2 changes: 1 addition & 1 deletion cli/spawn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const spawn = async (
stdio: stdio,
env: process.env,
cwd: cwd,
shell: true,
// shell: true,
});

let stdout = "";
Expand Down
22 changes: 22 additions & 0 deletions lib/config/paths.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as path_provider;
import './app.dart';

abstract class PathDirs {
static late String documents;
static late String temp;

static Future<void> initialize() async {
documents = path.join(
(await path_provider.getApplicationDocumentsDirectory()).path,
Config.code,
);

temp = path.join(
(await path_provider.getTemporaryDirectory()).path,
Config.code,
);
}

static String get data => path.join(documents, 'data');
}
26 changes: 16 additions & 10 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import 'package:flutter/material.dart';
import './modules/app/lifecycle.dart';
import './modules/app/state.dart';
import './modules/database/database.dart';
import './modules/database/schemas/settings/settings.dart';
import './modules/helpers/logger.dart';
import './modules/helpers/ui.dart';
import './modules/translator/translator.dart';
import './modules/utils/list.dart';
import './ui/router.dart';

Future<void> main(final List<String> args) async {
Expand Down Expand Up @@ -50,9 +50,6 @@ class MainApp extends StatefulWidget {
}

class _MainAppState extends State<MainApp> {
bool useSystemPreferredTheme = DataStore.settings.useSystemPreferredTheme;
bool useDarkMode = DataStore.settings.useDarkMode;

@override
void initState() {
super.initState();
Expand All @@ -71,10 +68,17 @@ class _MainAppState extends State<MainApp> {
final SettingsSchema current,
final SettingsSchema previous,
) {
setState(() {
useSystemPreferredTheme = current.useSystemPreferredTheme;
useDarkMode = current.useDarkMode;
});
final List<List<dynamic>> changables = <List<dynamic>>[
<dynamic>[
current.useSystemPreferredTheme,
previous.useSystemPreferredTheme
],
<dynamic>[current.useDarkMode, previous.useDarkMode],
];

if (changables.some((final List<dynamic> x) => x.first != x.last)) {
setState(() {});
}
}

@override
Expand All @@ -87,9 +91,11 @@ class _MainAppState extends State<MainApp> {
],
theme: Palette.lightTheme,
darkTheme: Palette.darkTheme,
themeMode: useSystemPreferredTheme
themeMode: AppState.settings.value.useSystemPreferredTheme
? ThemeMode.system
: (useDarkMode ? ThemeMode.dark : ThemeMode.light),
: (AppState.settings.value.useDarkMode
? ThemeMode.dark
: ThemeMode.light),
initialRoute: RouteNames.initialRoute,
onGenerateRoute: (final RouteSettings settings) {
if (settings.name == null) {
Expand Down
16 changes: 8 additions & 8 deletions lib/modules/app/lifecycle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -91,21 +91,21 @@ abstract class AppLifecycle {
}

try {
await DataStore.initialize();
await DatabaseManager.initialize();
} catch (err, trace) {
Logger.of('DataStore').error(
Logger.of('DatabaseManager').error(
'"initialize" failed: $err',
trace,
);
}

final TranslationSentences? settingsLocale =
DataStore.settings.locale != null
? Translator.tryGetTranslation(DataStore.settings.locale!)
AppState.settings.value.locale != null
? Translator.tryGetTranslation(AppState.settings.value.locale!)
: null;
if (settingsLocale == null) {
DataStore.settings.locale = null;
await DataStore.settings.save();
AppState.settings.value.locale = null;
await SettingsBox.save(AppState.settings.value);
}

Translator.t = settingsLocale ?? Translator.getSupportedTranslation();
Expand Down Expand Up @@ -194,7 +194,7 @@ abstract class AppLifecycle {
await LocalServer.dispose();
Logger.of('LocalServer').info('Finished "dispose"');

await DataStore.dispose();
Logger.of('DataStore').info('Finished "dispose"');
await DatabaseManager.dispose();
Logger.of('DatabaseManager').info('Finished "dispose"');
}
}
3 changes: 1 addition & 2 deletions lib/modules/app/state.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import 'dart:io';
import '../database/database.dart';
import '../database/schemas/settings/settings.dart';
import '../state/eventer.dart';

abstract class AppState {
static final ReactiveEventer<SettingsSchema> settings =
ReactiveEventer<SettingsSchema>();

static Future<void> initialize() async {
AppState.settings.value = DataStore.settings;
AppState.settings.value = SettingsBox.get();
}

static bool get isDesktop =>
Expand Down

0 comments on commit 9f04017

Please sign in to comment.