Skip to content

Commit

Permalink
mplement version checking and update functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
catallo committed Dec 19, 2023
1 parent 2d17c87 commit b5dceff
Show file tree
Hide file tree
Showing 5 changed files with 157 additions and 8 deletions.
20 changes: 18 additions & 2 deletions bin/ht.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
// THE SOFTWARE.

import 'dart:io';
import 'package:compute/compute.dart';

import 'package:ht/cache.dart';
import 'package:ht/ansi_codes.dart';
Expand Down Expand Up @@ -59,18 +60,33 @@ void initialize() {
apiKey = config.readApiKey();
}

Future<bool> checkLatestRelease() async {
// Wrap the call in another function that takes a dummy argument
bool result = await compute(wrapperLatestVersionCheck, null);
return result;
}

bool updateAvailable() {
if (File("$htPath/update_available").existsSync()) {
return true;
}
return false;
}

void main(List<String> arguments) async {
dbg("ht started");

checkForLatestVersion();

// install ───────────────────────────────────────────────────────────────────
if (arguments.isNotEmpty &&
(arguments[0] == '-i' || arguments[0] == '--install')) {
checkInstallation();
exit(0);
}

if (updateAvailable()) await downloadUpdate();

checkLatestRelease();

initialize();

if (apiKey == null) {
Expand Down
130 changes: 127 additions & 3 deletions lib/get_latest_version.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as path;

import 'globals.dart';
import 'package:http/http.dart' as http;
import 'package:ht/installation_and_update.dart';
import 'package:ht/debug.dart';

Future<String> getLatestReleaseVersion() async {
var url =
Expand All @@ -14,11 +20,129 @@ Future<String> getLatestReleaseVersion() async {
}
}

void checkForLatestVersion() async {
// Wrapper function that matches the expected signature for compute
Future<bool> wrapperLatestVersionCheck(void _) async {
return await checkForLatestVersion();
}

Future<bool> checkForLatestVersion() async {
var latestVersion = 'v0.0.0';
try {
var latestVersion = await getLatestReleaseVersion();
print('Latest Release Version: $latestVersion');
latestVersion = await getLatestReleaseVersion();
dbg('Latest Release Version: $latestVersion, this version: $version');
} catch (e) {
print(e);
}
if (latestVersion.startsWith('v')) latestVersion = latestVersion.substring(1);
// use isSemVerHigher() from installation_and_update.dart
if (isSemVerHigher(version, latestVersion)) {
dbg('New version available');
// write an empty file "update_available" to ~/.config/ht
try {
File("$htPath/update_available").createSync(recursive: false);
// write the latest version to ~/.config/ht/update_available
File("$htPath/update_available")
.writeAsStringSync('$latestVersion\n', mode: FileMode.append);
} catch (e) {
print("Error creating update_available file: $e");
return false;
}
} else {
dbg('No new version available');
}
return true;
}

downloadUpdate() async {
dbg('downloadUpdate started');

print(" 🤖 There is an updated version available. Downloading ...");

// if it doesn't exist, create ~/.config/ht/download
if (!Directory("$htPath/download").existsSync()) {
try {
Directory("$htPath/download").createSync(recursive: false);
} catch (e) {
print("Error creating directory: $e");
return false;
}
}

// Identify the platform
String platformKey =
Platform.isLinux ? 'linux_x64' : (Platform.isMacOS ? 'MacOS_ARM64' : '');

// Fetch the latest release data from GitHub
var url =
Uri.parse('https://api.github.com/repos/catallo/ht/releases/latest');
var response = await http.get(url);

if (response.statusCode == 200) {
var jsonResponse = jsonDecode(response.body);
var body = jsonResponse['body'];

// Regular expression to find download links
RegExp regExp = RegExp(
r'\[ht_[^\]]*_' +
platformKey.replaceAll('_', r'_') +
r'\.zip\]\((https?[^\)]+)\)',
caseSensitive: false);

var matches = regExp.allMatches(body);
if (matches.isNotEmpty) {
var downloadUrl = matches.first.group(1);
print('Download URL: $downloadUrl');

// Download the file
var client = HttpClient();
var request = await client.getUrl(Uri.parse(downloadUrl!));
var response = await request.close();

// Read the response and write it to a file
String fileName = path.basename(downloadUrl);
String filePath = '$htPath/download/$fileName';
var file = File(filePath);
var fileSink = file.openWrite();
await response.pipe(fileSink);
fileSink.close();

print('File downloaded to $filePath. Extracting ...');

// Proceed to unzip the file
await unzipFile(filePath);

// Delete the downloaded zip
file.deleteSync();
// get file name of extracted file, it's the only file in the directory
var extractedFileName = Directory("$htPath/download").listSync()[0].path;
dbg("extractedFileName: $extractedFileName");
// run the extracted file with -i to install
var installOutput = Process.runSync(extractedFileName, ['-i']);
dbg("Process.runSync finished");
print(installOutput.stdout);
// delete the extracted file
//File(extractedFileName).deleteSync();
// delete the update_available file
//File("$htPath/update_available").deleteSync();
exit(0);
} else {
print('No matching asset found for platform $platformKey');
}
} else {
print('Failed to load latest release version');
}

exit(0);
}

Future<void> unzipFile(String filePath) async {
var destinationPath = "$htPath/download";
var result =
await Process.run('unzip', ['-o', filePath, '-d', destinationPath]);

if (result.exitCode != 0) {
print('Error unzipping file: ${result.stderr}');
} else {
print('File unzipped to $destinationPath');
}
}
6 changes: 3 additions & 3 deletions lib/globals.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import 'dart:io';
import 'package:ht/config.dart';

bool debug = true;
bool debug = false;

const version = "2.0.15"; // SemVer
const compileDate = "2023-11-27";
const version = "2.0.5"; // SemVer
const compileDate = "2023-12-19";

String os = "Linux";
String distro = "Debian derivate";
Expand Down
8 changes: 8 additions & 0 deletions pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.18.0"
compute:
dependency: "direct main"
description:
name: compute
sha256: b70190d59352a267a9765a77b97d0f619874c84d30c5193ae71050ee22ab2ef7
url: "https://pub.dev"
source: hosted
version: "1.0.2"
convert:
dependency: transitive
description:
Expand Down
1 change: 1 addition & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ dev_dependencies:
lints: ^2.0.0
test: ^1.16.0
dependencies:
compute: ^1.0.2
http: ^1.1.0

0 comments on commit b5dceff

Please # to comment.