Skip to content

Commit

Permalink
Merge pull request #439 from cunarist/organize-flutter-deps
Browse files Browse the repository at this point in the history
Organize Dart dependencies and introduce `rinf server` command
  • Loading branch information
temeddix authored Sep 18, 2024
2 parents 18c98e6 + 71f7c15 commit c7f497a
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 82 deletions.
49 changes: 33 additions & 16 deletions flutter_package/bin/rinf.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'src/internet.dart';
import 'src/common.dart';

Future<void> main(List<String> args) async {
// After running `dart run rinf`,
// When running `dart run rinf`,
// Unnecessary two lines of
//`Building package executable...\nBuilt rinf:rinf.` appear.
// Remove those before proceeding.
Expand All @@ -18,18 +18,19 @@ Future<void> main(List<String> args) async {
await checkConnectivity();

// Parse CLI arguments and run the corresponding function.
final runner = CommandRunner(
final commandRunner = CommandRunner(
'rinf',
'Helper commands for building apps with Rust in Flutter.',
'Helper commands for building apps using Rust in Flutter.',
usageLineLength: 80,
)
..addCommand(ConfigCommand())
..addCommand(TemplateCommand())
..addCommand(MessageCommand())
..addCommand(WasmCommand());
);
commandRunner.addCommand(ConfigCommand());
commandRunner.addCommand(TemplateCommand());
commandRunner.addCommand(MessageCommand());
commandRunner.addCommand(WasmCommand());
commandRunner.addCommand(ServerCommand());

try {
await runner.run(args);
await commandRunner.run(args);
} catch (error) {
// Print the error gracefully without backtrace.
print(error.toString().trim().red);
Expand All @@ -38,8 +39,7 @@ Future<void> main(List<String> args) async {

class ConfigCommand extends Command {
final name = 'config';
final description = 'Shows current Rinf configuration' +
' resolved from `pubspec.yaml` with defaults applied.';
final description = 'Show Rinf configuration resolved from `pubspec.yaml`.';

ConfigCommand() {}

Expand All @@ -51,7 +51,7 @@ class ConfigCommand extends Command {

class TemplateCommand extends Command {
final name = 'template';
final description = 'Applies Rust template to the current Flutter project.';
final description = 'Apply Rust template to the current Flutter project.';

TemplateCommand() {}

Expand All @@ -63,13 +63,13 @@ class TemplateCommand extends Command {

class MessageCommand extends Command {
final name = 'message';
final description = 'Generates message code from `.proto` files.';
final description = 'Generate message code from `.proto` files.';

MessageCommand() {
argParser.addFlag(
'watch',
abbr: 'w',
help: 'Continuously watches `.proto` files.',
help: 'Continuously watches `.proto` files',
);
}

Expand All @@ -90,13 +90,13 @@ class MessageCommand extends Command {

class WasmCommand extends Command {
final name = 'wasm';
final description = 'Builds the webassembly module for the web.';
final description = 'Build the webassembly module for the web.';

WasmCommand() {
argParser.addFlag(
'release',
abbr: 'r',
help: 'Builds in release mode.',
help: 'Builds in release mode',
);
}

Expand All @@ -109,3 +109,20 @@ class WasmCommand extends Command {
await buildWebassembly(release);
}
}

class ServerCommand extends Command {
final name = 'server';
final description = 'Show how to run Flutter web server with web headers.';

ServerCommand() {}

Future<void> run() async {
final commandParts = [
'flutter',
'run',
'--web-header=Cross-Origin-Opener-Policy=same-origin',
'--web-header=Cross-Origin-Embedder-Policy=require-corp'
];
print(commandParts.join(' ').dim);
}
}
2 changes: 1 addition & 1 deletion flutter_package/bin/src/common.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ void removeCliLines(int lines) {
for (var i = 0; i < lines; i++) {
stdout.write('\x1B[1A'); // Move the cursor up one line
stdout.write('\x1B[2K'); // Clear the line
stdout.write('\r'); // Return the cursor to the front
stdout.write('\r'); // Move the cursor to the front
}
}
28 changes: 1 addition & 27 deletions flutter_package/bin/src/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'dart:io';

import 'package:package_config/package_config.dart';
import 'package:yaml/yaml.dart';
import 'package:chalkdart/chalkstrings.dart';

import 'config.dart';
import 'message.dart';
Expand Down Expand Up @@ -286,30 +285,5 @@ Future<void> buildWebassembly(bool isReleaseMode) async {
fillingBar.increment();

// Guide the developer how to run Flutter web server with web headers.
print('To run the Flutter web server, use:');
final commandLineDivider = await getCommandLineDivider();
final commandLines = [
'flutter run',
'--web-header=Cross-Origin-Opener-Policy=same-origin',
'--web-header=Cross-Origin-Embedder-Policy=require-corp'
];
print(commandLines.join(' ${commandLineDivider}\n').dim);
}

Future<String> getCommandLineDivider() async {
if (Platform.isWindows) {
// Windows environment, check further for PowerShell or CMD
if (Platform.environment['SHELL'] == null) {
// Likely PowerShell environment
return '`';
// // Likely Command Prompt (cmd.exe)
// return "^";
} else {
// Bash or some other shell
return '\\';
}
} else {
// Bash or some other shell
return '\\';
}
print('To get the Flutter web server command, run `rinf server`');
}
11 changes: 9 additions & 2 deletions flutter_package/bin/src/internet.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import 'package:internet_connection_checker/internet_connection_checker.dart';
import 'dart:io';

var isInternetConnected = false;

Future<void> checkConnectivity() async {
isInternetConnected = await InternetConnectionChecker().hasConnection;
try {
final result = await InternetAddress.lookup('pub.dev');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
isInternetConnected = true;
}
} on SocketException catch (_) {
isInternetConnected = false;
}
}
51 changes: 17 additions & 34 deletions flutter_package/bin/src/progress.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// CLI progress bar copied from
// CLI progress bar copied and modified from
// https://github.com/RohitEdathil/ConsoleBars

import 'dart:async';
import 'dart:io';
import 'common.dart';

class ProgressBar {
Expand All @@ -13,7 +12,7 @@ class ProgressBar {
int _progress = 0;
late int max;

// Time
/// Tracks time
final _clock = Stopwatch();

/// Whether a timer should be present
Expand All @@ -22,8 +21,6 @@ class ProgressBar {
/// Percentage should be displayed or not
bool percentage;

// Decorations

/// The description of the bar
String _desc;

Expand All @@ -33,11 +30,8 @@ class ProgressBar {
/// The character to used as fill
String fill;

/// Scale of the bar relative to the terminal width
double scale;

/// Width of the bar
int? width;
int width;

/// Whether the instance should print nothing
bool silent;
Expand All @@ -56,33 +50,25 @@ class ProgressBar {
}

/// Arguments:
/// - total : Total number of steps
/// - desc : Simple text shown before the bar (optional)
/// - space : Character denoting empty space (default : '.')
/// - fill : Character denoting filled space (default : '█')
/// - time : Toggle timing mode (default : false)
/// - percentage : Toggle percentage display (default : false)
/// - scale : Scale of the bar relative to width (between: 0 and 1, default: 0.5, Irrelavant if width is specified)
/// - width : Width of the bar drawn in the CLI
/// - `total` : Total number of steps
/// - `desc` : Simple text shown after the bar (optional)
/// - `space` : Character denoting empty space (default : '.')
/// - `fill` : Character denoting filled space (default : '█')
/// - `time` : Toggle timing mode (default : false)
/// - `percentage` : Toggle percentage display (default : false)
/// - `width` : Width of the bar drawn in the CLI (default: 40)
ProgressBar({
required int total,
String desc = '',
this.space = '.',
this.fill = '█',
this.time = false,
this.percentage = false,
this.scale = 0.5,
this.width = 40,
this.silent = false,
}) : _desc = desc,
_total = total {
// Handles width of the bar, throws an error if it's not specified and the terminal width is not available
try {
max = width ?? ((stdout.terminalColumns - _desc.length) * scale).toInt();
} on StdoutException {
throw StdoutException(
'Could not get terminal width, try specifying a width manually');
}
max = width;
if (time) {
_clock.start();
scheduleMicrotask(autoRender);
Expand Down Expand Up @@ -128,24 +114,21 @@ class ProgressBar {
_clock.stop();
}
}
String timeStr = '';
String? timeStr = null;
if (time) {
final rate = _clock.elapsedMicroseconds / (_current == 0 ? 1 : _current);
final eta = Duration(microseconds: ((_total - _current) * rate).toInt());
timeStr = '[ ' +
_clock.elapsed.toString().substring(0, 10) +
' / ' +
eta.toString().substring(0, 10) +
' ]';
final elpsedStr = _clock.elapsed.toString().substring(0, 10);
final etaStr = eta.toString().substring(0, 10);
timeStr = '[ $elpsedStr / $etaStr ]';
}
String perc = '';
String? perc = null;
if (percentage) {
perc = '${(_current * 100 / _total).toStringAsFixed(1)}%';
}
final bar = '${fill * _progress}${space * (max - _progress)}';
final frameParts = [bar, '$_current/$_total', perc, timeStr, ':', _desc];
final filteredParts = frameParts.where((v) => v.isNotEmpty).toList();
final frame = filteredParts.join(' ');
final frame = frameParts.where((v) => v != null).toList().join(' ');
removeCliLines(1);
print(frame);
}
Expand Down
3 changes: 1 addition & 2 deletions flutter_package/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ dependencies:
watcher: ^1.1.0
ffi: ^2.1.0
yaml: ^3.1.2
internet_connection_checker: ^1.0.0
args: ^2.5.0
chalkdart: ^2.2.1

dev_dependencies:
lints: ">=3.0.0 <5.0.0"
lints: ">=4.0.0 <5.0.0"

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
Expand Down

0 comments on commit c7f497a

Please sign in to comment.