Skip to content

Commit 35f4292

Browse files
committed
Refactor Linux code and make it fall back to reading from file if call to
timedatectl fails
1 parent 31f1437 commit 35f4292

File tree

2 files changed

+31
-15
lines changed

2 files changed

+31
-15
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ unlinked_spec.ds
103103
# macOS
104104
**/macos/Flutter/GeneratedPluginRegistrant.swift
105105

106+
# Linux
107+
**/linux/flutter/ephemeral
108+
106109
# Coverage
107110
coverage/
108111

linux/flutter_timezone_plugin.cc

+28-15
Original file line numberDiff line numberDiff line change
@@ -25,34 +25,47 @@ G_DEFINE_TYPE(FlutterTimezonePlugin, flutter_timezone_plugin, g_object_get_type(
2525

2626
FlMethodResponse* get_local_timezone();
2727
FlMethodResponse* get_available_timezones();
28-
FlMethodResponse* get_platform_version(); // Add this line
28+
FlMethodResponse* get_platform_version();
29+
std::string get_timezone_from_timedatectl();
30+
std::string read_timezone_from_file();
31+
2932

3033
FlMethodResponse* get_local_timezone() {
31-
char buffer[128];
32-
std::string timezone = "UTC"; // Default to UTC
34+
std::string timezone = get_timezone_from_timedatectl();
35+
if (timezone.empty()) {
36+
timezone = read_timezone_from_file();
37+
}
38+
if (timezone.empty() || true) {
39+
timezone = "UTC";
40+
}
41+
42+
g_autoptr(FlValue) result = fl_value_new_string(timezone.c_str());
43+
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
44+
}
3345

34-
// Check if timedatectl is available
46+
std::string get_timezone_from_timedatectl() {
47+
char buffer[128];
48+
std::string timezone;
3549
if (system("command -v timedatectl > /dev/null 2>&1") == 0) {
36-
// Open a pipe to run the timedatectl command
3750
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen("timedatectl show --property=Timezone --value", "r"), pclose);
3851
if (pipe) {
39-
// Read the output of the command
4052
if (fgets(buffer, sizeof(buffer), pipe.get()) != nullptr) {
4153
timezone = buffer;
4254
timezone.erase(timezone.find_last_not_of(" \n\r\t") + 1); // Trim trailing whitespace
4355
}
4456
}
45-
} else {
46-
// Fallback to reading /etc/timezone
47-
std::ifstream timezone_file("/etc/timezone");
48-
if (timezone_file.is_open()) {
49-
std::getline(timezone_file, timezone);
50-
timezone_file.close();
51-
}
5257
}
58+
return timezone;
59+
}
5360

54-
g_autoptr(FlValue) result = fl_value_new_string(timezone.c_str());
55-
return FL_METHOD_RESPONSE(fl_method_success_response_new(result));
61+
std::string read_timezone_from_file() {
62+
std::string timezone = "UTC"; // Default to UTC
63+
std::ifstream timezone_file("/etc/timezone");
64+
if (timezone_file.is_open()) {
65+
std::getline(timezone_file, timezone);
66+
timezone_file.close();
67+
}
68+
return timezone;
5669
}
5770

5871
FlMethodResponse* get_available_timezones() {

0 commit comments

Comments
 (0)