2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.jrubyscripting.internal.watch;
15 import java.nio.file.Path;
16 import java.util.Arrays;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.openhab.core.service.WatchService;
24 * @author Cody Cutrer - Initial contribution
25 * @author Jan N. Klug - Refactored to new WatchService
28 public class JRubyGemWatchService implements JRubyWatchService, WatchService.WatchEventListener {
30 private static final String GEMSPEC = ".gemspec";
31 private final WatchService watchService;
32 private final Path path;
34 private JRubyDependencyTracker dependencyTracker;
36 JRubyGemWatchService(WatchService watchService, String path, JRubyDependencyTracker dependencyTracker) {
37 this.watchService = watchService;
38 this.dependencyTracker = dependencyTracker;
39 this.path = Path.of(path);
43 public void activate() {
44 watchService.registerListener(this, path);
48 public void deactivate() {
49 watchService.unregisterListener(this);
53 public void processWatchEvent(WatchService.Kind kind, Path path) {
54 String file = path.toFile().getName();
55 if (file.endsWith(GEMSPEC)) {
56 // This seems really lazy, but you can't definitively tell the name
57 // of a gem from the gemspec's filename. It's simply too ambiguous with version
58 // numbers and platforms allowed to have `-` and `_` characters as well. RubyGems
59 // doesn't do it either - it either has the name already, and searches for
60 // `<name>-*.gemspec`, or it completely lists the all files on disk. Either way
61 // it then executes the gemspec to get full details. We can't do that here in
62 // pure Java and without a JRubyEngine available. So just punt and invalidate
63 // _all_ subsets of hyphens. Worst case we invalidate a "parent" gem that didn't
64 // need to be invalidated, but oh well, that just means a script reloads sometimes
65 // when it didn't absolutely need to.
66 String[] parts = file.split("-");
67 for (int i = 0; i < parts.length - 1; ++i) {
68 dependencyTracker.dependencyChanged("gem:" + String.join("-", Arrays.copyOf(parts, i + 1)));