Skip to content

Commit f0ae7be

Browse files
committed
fix(ci): fix rolling build and nested header includes for modern ros2 distros
Signed-off-by: Thomas Chou <thomas@wytron.com.tw>
1 parent 5485e42 commit f0ae7be

3 files changed

Lines changed: 117 additions & 78 deletions

File tree

‎extra_script.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ def build_microros(*args, **kwargs):
110110

111111
python_env_path = env['PROJECT_CORE_DIR'] + "/penv/bin/activate"
112112
builder = library_builder.Build(library_folder=main_path, packages_folder=extra_packages_path, distro=microros_distro, python_env=python_env_path)
113+
builder.env = env.get("ENV", os.environ.copy())
113114
builder.run('{}/metas/{}'.format(main_path, selected_board_meta), cmake_toolchain.path, microros_user_meta)
114115

115116
#######################################################
@@ -131,11 +132,14 @@ def update_env():
131132
# Add required defines
132133
global_env.Append(CPPDEFINES=[("CLOCK_MONOTONIC", 1)])
133134

135+
import glob
136+
include_dirs = [main_path + "/libmicroros/include"] + [d for d in glob.glob(main_path + "/libmicroros/include/*") if os.path.isdir(d)]
137+
134138
# Add micro-ROS include path
135-
global_env.Append(CPPPATH=[main_path + "/libmicroros/include"])
139+
global_env.Append(CPPPATH=include_dirs)
136140

137141
# Add micro-ROS include path to library include path
138-
env.Append(CPPPATH=[main_path + "/libmicroros/include"])
142+
env.Append(CPPPATH=include_dirs)
139143

140144
# Add platformio library general include path
141145
global_env.Append(CPPPATH=[

‎microros_utils/library_builder.py‎

Lines changed: 110 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def __init__(self, library_folder, packages_folder, distro, python_env):
5252
self.includes = self.library_path+ '/include'
5353
self.library_name = "microros"
5454
self.python_env = python_env
55-
self.env = {}
55+
self.env = None
5656

5757
def run(self, meta, toolchain, user_meta = ""):
5858
if os.path.exists(self.library):
@@ -84,53 +84,36 @@ def check_env(self):
8484
if (RMW_IMPLEMENTATION):
8585
os.environ['RMW_IMPLEMENTATION'] = "rmw_microxrcedds"
8686

87-
self.env = os.environ.copy()
88-
8987
def download_dev_environment(self):
90-
os.makedirs(self.dev_src_folder, exist_ok=True)
9188
print("Downloading micro-ROS dev dependencies")
92-
for repo in Sources.dev_environments[self.distro]:
93-
repo.clone(self.dev_src_folder)
94-
print("\t - Downloaded {}".format(repo.name))
95-
self.dev_packages.extend(repo.get_packages())
89+
self.dev_packages = Sources.dev_environments[self.distro]
90+
for p in self.dev_packages:
91+
p.clone(self.dev_src_folder)
92+
print("\t - Downloaded {}".format(p.name))
9693

9794
def build_dev_environment(self):
9895
print("Building micro-ROS dev dependencies")
99-
if self.distro == "lyrical":
96+
if self.distro in ("lyrical", "rolling"):
10097
self.patch_dev_sources()
101-
102-
# Fix build: Ignore rmw_test_fixture_implementation in rolling, kilted, lyrical
103-
touch_command = ''
104-
if self.distro in ('rolling', 'kilted', 'lyrical'):
105-
touch_command = 'touch src/ament_cmake_ros/rmw_test_fixture_implementation/COLCON_IGNORE src/ament_cmake_ros/rmw_test_fixture/COLCON_IGNORE && '
106-
107-
command = "cd {} && {} . {} && colcon build --cmake-args -DBUILD_TESTING=OFF -DPython3_EXECUTABLE=`which python`".format(self.dev_folder, touch_command, self.python_env)
108-
result = run_cmd(command, env=self.env)
98+
99+
colcon_command = '. {} && colcon build --merge-install --packages-ignore-regex=.*_cpp --cmake-args -DPython3_EXECUTABLE=`which python` -DBUILD_TESTING=OFF'.format(self.python_env)
100+
command = "cd {} && {}".format(self.dev_folder, colcon_command)
101+
result = run_cmd(command)
109102

110103
if 0 != result.returncode:
111-
print("Build dev micro-ROS environment failed: \n {}".format(result.stderr.decode("utf-8")))
104+
print("Build dev micro-ROS environment failed: \n{}".format(result.stderr.decode("utf-8")))
112105
sys.exit(1)
113106

114107
def download_mcu_environment(self):
115-
os.makedirs(self.mcu_src_folder, exist_ok=True)
116108
print("Downloading micro-ROS library")
117-
for repo in Sources.mcu_environments[self.distro]:
118-
repo.clone(self.mcu_src_folder)
119-
self.mcu_packages.extend(repo.get_packages())
120-
for package in repo.get_packages():
121-
if package.name in Sources.ignore_packages[self.distro] or package.name.endswith("_cpp"):
122-
package.ignore()
123-
124-
print('\t - Downloaded {}{}'.format(package.name, " (ignored)" if package.ignored else ""))
125-
126-
self.download_extra_packages()
127-
128-
def download_extra_packages(self):
129-
if not os.path.exists(self.packages_folder):
130-
print("\t - Extra packages folder not found, skipping...")
131-
return
132-
133-
print("Checking extra packages")
109+
self.mcu_packages = Sources.mcu_environments[self.distro]
110+
for p in self.mcu_packages:
111+
p.clone(self.mcu_src_folder)
112+
if p.name in Sources.ignore_packages[self.distro]:
113+
p.ignore()
114+
print("\t - Downloaded {} (ignored)".format(p.name))
115+
else:
116+
print("\t - Downloaded {}".format(p.name))
134117

135118
# Load and clone repositories from extra_packages.repos file
136119
extra_repos = self.get_repositories_from_yaml("{}/extra_packages.repos".format(self.packages_folder))
@@ -149,6 +132,12 @@ def download_extra_packages(self):
149132

150133
shutil.copytree(self.packages_folder, self.mcu_src_folder, ignore=shutil.ignore_patterns('extra_packages.repos'), dirs_exist_ok=True)
151134

135+
# Apply COLCON_IGNORE for ignored packages
136+
for root, dirs, files in os.walk(self.mcu_src_folder):
137+
if os.path.basename(root) in Sources.ignore_packages.get(self.distro, []):
138+
with open(os.path.join(root, "COLCON_IGNORE"), "w") as f:
139+
pass
140+
152141
def get_repositories_from_yaml(self, yaml_file):
153142
repos = {}
154143
try:
@@ -168,14 +157,13 @@ def get_repositories_from_yaml(self, yaml_file):
168157
except KeyError as e:
169158
continue
170159
repos[path] = repo
171-
except (yaml.YAMLError, KeyError, TypeError) as e:
172-
print("Error on {}: {}".format(yaml_file, e))
173-
finally:
174-
return repos
160+
except (yaml.YAMLError, KeyError, TypeError, FileNotFoundError) as e:
161+
pass
162+
return repos
175163

176164
def build_mcu_environment(self, meta_file, toolchain_file, user_meta = ""):
177165
print("Building micro-ROS library")
178-
if self.distro == "lyrical":
166+
if self.distro in ("lyrical", "rolling"):
179167
self.patch_mcu_sources()
180168

181169
common_meta_path = self.library_folder + '/metas/common.meta'
@@ -217,49 +205,72 @@ def package_mcu_library(self):
217205
# Copy includes
218206
shutil.copytree(self.build_folder + "/mcu/install/include", self.includes)
219207

220-
if self.distro == "lyrical":
208+
if self.distro in ("lyrical", "rolling"):
221209
timer_h = os.path.join(self.includes, "rclc", "timer.h")
222210
if os.path.exists(timer_h):
223211
with open(timer_h, "r") as f_t:
224212
ct = f_t.read()
225213
if "rclc_timer_init_default2" not in ct:
226-
ct = ct.replace(
227-
"#if __cplusplus\n}\n#endif",
228-
"static inline rcl_ret_t rclc_timer_init_default2(rcl_timer_t * timer, rclc_support_t * support, const uint64_t timeout_ns, const rcl_timer_callback_t callback, bool autostart) { (void)autostart; return rclc_timer_init_default(timer, support, timeout_ns, callback); }\n\n#if __cplusplus\n}\n#endif"
229-
)
214+
decl = """
215+
/**
216+
* Initializes a rcl timer with default clock.
217+
*
218+
* \\param[inout] timer a preallocated rcl_timer_t
219+
* \\param[in] support the rclc_support_t object
220+
* \\param[in] timeout_ns the time out in nanoseconds of the timer
221+
* \\param[in] callback the callback of the timer
222+
* \\return `RCL_RET_OK` if the timer was successfully initialized
223+
* \\return `RCL_RET_INVALID_ARGUMENT` if any null pointer as argument
224+
* \\return `RCL_RET_ERROR` in case of other error
225+
*/
226+
RCLC_PUBLIC
227+
rcl_ret_t
228+
rclc_timer_init_default(
229+
rcl_timer_t * timer,
230+
rclc_support_t * support,
231+
const uint64_t timeout_ns,
232+
const rcl_timer_callback_t callback);
233+
"""
234+
decl_compat = """
235+
#define rclc_timer_init_default(timer, support, timeout_ns, callback) \\
236+
rclc_timer_init_default2(timer, support, timeout_ns, (rcl_timer_callback_t)(callback), true)
237+
238+
#define rclc_timer_init_default2(timer, support, timeout_ns, callback, autostart) \\
239+
rcl_timer_init2(timer, &(support)->clock, &(support)->context, timeout_ns, (rcl_timer_callback_t)(callback), *(support)->allocator, autostart)
240+
"""
241+
ct = ct.replace(decl, decl_compat)
230242
with open(timer_h, "w") as f_t:
231243
f_t.write(ct)
232244

233-
# Fix include paths
234-
include_folders = os.listdir(self.includes)
235-
236-
for folder in include_folders:
237-
folder_path = self.includes + "/{}".format(folder)
238-
repeated_path = folder_path + "/{}".format(folder)
239-
240-
if os.path.exists(repeated_path):
241-
shutil.copytree(repeated_path, folder_path, copy_function=shutil.move, dirs_exist_ok=True)
242-
shutil.rmtree(repeated_path)
243-
244245
def resolve_binutils_path(self):
245246
if sys.platform == "darwin":
246247
homebrew_binutils_path = "/opt/homebrew/opt/binutils/bin/"
247248
if os.path.exists(homebrew_binutils_path):
248249
return homebrew_binutils_path
249-
250250
print("ERROR: GNU binutils not found. ({}) Please install binutils with homebrew: brew install binutils"
251251
.format(homebrew_binutils_path))
252252
sys.exit(1)
253253

254+
path = os.getenv('PATH', '')
255+
for p in path.split(':'):
256+
if p.endswith('arm-none-eabi/bin'):
257+
return p + "/"
254258
return ""
255259

256260
def patch_dev_sources(self):
257-
# 1. Relax C/C++ standards for embedded MCU cross-compilers (e.g. GCC 7.2.1 on Portenta)
261+
# 1. Ignore test packages in dev sources
262+
for p in ["rmw_test_fixture", "rmw_test_fixture_implementation", "domain_coordinator"]:
263+
p_dir = os.path.join(self.dev_src_folder, "ament_cmake_ros", p)
264+
if os.path.exists(p_dir):
265+
with open(os.path.join(p_dir, "COLCON_IGNORE"), "w") as f:
266+
pass
267+
268+
# 2. Relax C/C++ standards for embedded MCU cross-compilers (e.g. GCC 7.2.1 on Portenta)
258269
defaults_cmake = os.path.join(self.dev_src_folder, "ament_cmake_ros", "ament_cmake_ros_core", "cmake", "ament_ros_defaults.cmake")
259270
if os.path.exists(defaults_cmake):
260271
with open(defaults_cmake, "r") as f:
261272
dc = f.read()
262-
dc = dc.replace("cxx_std_20", "cxx_std_14").replace("c_std_17", "c_std_11")
273+
dc = dc.replace("cxx_std_20", "cxx_std_17").replace("c_std_17", "c_std_11")
263274
with open(defaults_cmake, "w") as f:
264275
f.write(dc)
265276

@@ -332,17 +343,39 @@ def patch_mcu_sources(self):
332343
with open(base64_c, "w") as f:
333344
f.write(bc)
334345

335-
# 2. Patch rosidl_buffer buffer.hpp for -fno-exceptions
336-
buffer_hpp = os.path.join(self.mcu_src_folder, "rosidl", "rosidl_buffer", "include", "rosidl_buffer", "buffer.hpp")
337-
if os.path.exists(buffer_hpp):
338-
with open(buffer_hpp, "r") as f:
339-
bh = f.read()
340-
if "__EXCEPTIONS" not in bh:
341-
orig_throw1 = ' throw std::invalid_argument("Buffer implementation must not be null");'
342-
patch_throw1 = '#if __EXCEPTIONS || defined(__cpp_exceptions)\n throw std::invalid_argument("Buffer implementation must not be null");\n#endif'
343-
bh = bh.replace(orig_throw1, patch_throw1)
344-
345-
orig_fn = """ void throw_if_not_cpu_backend() const
346+
# 2. Patch rosidl_buffer CMakeLists.txt and buffer.hpp
347+
for b_dir in ["rosidl", "rosidl_core"]:
348+
buffer_cmake = os.path.join(self.mcu_src_folder, b_dir, "rosidl_buffer", "CMakeLists.txt")
349+
if os.path.exists(buffer_cmake):
350+
with open(buffer_cmake, "r") as f:
351+
bc = f.read()
352+
bc_lines = []
353+
changed_cmake = False
354+
for line in bc.splitlines(True):
355+
if "target_link_libraries" in line and ("ament_cmake_ros_core::ament_ros_cxx_standard" in line or "ament_ros_cxx_standard" in line or "PRIVATE )" in line or "PRIVATE )" in line):
356+
bc_lines.append("target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17)\n")
357+
changed_cmake = True
358+
else:
359+
bc_lines.append(line)
360+
if changed_cmake:
361+
with open(buffer_cmake, "w") as f:
362+
f.write("".join(bc_lines))
363+
364+
buffer_hpp = os.path.join(self.mcu_src_folder, b_dir, "rosidl_buffer", "include", "rosidl_buffer", "buffer.hpp")
365+
if os.path.exists(buffer_hpp):
366+
with open(buffer_hpp, "r") as f:
367+
bh = f.read()
368+
modified_bh = False
369+
if "std::is_same_v" in bh:
370+
bh = bh.replace("if constexpr (std::is_same_v<Allocator, std::allocator<T>>)", "if (std::is_same<Allocator, std::allocator<T>>::value)")
371+
bh = bh.replace("std::is_same_v<Allocator, std::allocator<T>>", "std::is_same<Allocator, std::allocator<T>>::value")
372+
modified_bh = True
373+
if "__EXCEPTIONS" not in bh:
374+
orig_throw1 = ' throw std::invalid_argument("Buffer implementation must not be null");'
375+
patch_throw1 = '#if __EXCEPTIONS || defined(__cpp_exceptions)\n throw std::invalid_argument("Buffer implementation must not be null");\n#endif'
376+
bh = bh.replace(orig_throw1, patch_throw1)
377+
378+
orig_fn = """ void throw_if_not_cpu_backend() const
346379
{
347380
if (!cpu_impl_) {
348381
throw std::runtime_error(
@@ -351,7 +384,7 @@ def patch_mcu_sources(self):
351384
". Use to_vector() for explicit conversion to CPU.");
352385
}
353386
}"""
354-
patch_fn = """ void throw_if_not_cpu_backend() const
387+
patch_fn = """ void throw_if_not_cpu_backend() const
355388
{
356389
#if __EXCEPTIONS || defined(__cpp_exceptions)
357390
if (!cpu_impl_) {
@@ -362,9 +395,11 @@ def patch_mcu_sources(self):
362395
}
363396
#endif
364397
}"""
365-
bh = bh.replace(orig_fn, patch_fn)
366-
with open(buffer_hpp, "w") as f:
367-
f.write(bh)
398+
bh = bh.replace(orig_fn, patch_fn)
399+
modified_bh = True
400+
if modified_bh:
401+
with open(buffer_hpp, "w") as f:
402+
f.write(bh)
368403

369404
# 3. Patch rclc timer.c for rcl_timer_init2
370405
timer_c = os.path.join(self.mcu_src_folder, "rclc", "rclc", "src", "rclc", "timer.c")

‎microros_utils/repositories.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,5 +276,5 @@ class Sources:
276276
'jazzy': ['test_tracetools', 'rcl_logging_spdlog', 'rcl_yaml_param_parser', 'rclc_examples', 'lttngpy'],
277277
'kilted': ['test_tracetools', 'rcl_logging_spdlog', 'rcl_yaml_param_parser', 'rclc_examples', 'lttngpy', 'rmw_security_common'],
278278
'lyrical': ['test_tracetools', 'rcl_logging_spdlog', 'rcl_logging_implementation', 'rcl_yaml_param_parser', 'rclc_examples', 'lttngpy', 'rmw_security_common', 'rosidl_buffer_py', 'test_rmw_implementation', 'rosidl_buffer_backend_registry'],
279-
'rolling': ['test_tracetools', 'rcl_logging_spdlog', 'rcl_yaml_param_parser', 'rclc_examples', 'lttngpy', 'rmw_security_common']
279+
'rolling': ['test_tracetools', 'rcl_logging_spdlog', 'rcl_logging_implementation', 'rcl_yaml_param_parser', 'rclc_examples', 'lttngpy', 'rmw_security_common', 'rosidl_buffer_py', 'test_rmw_implementation', 'rosidl_buffer_backend_registry']
280280
}

0 commit comments

Comments
 (0)