summaryrefslogtreecommitdiff
path: root/scm/mu-scm.cc
blob: ac016045c6fdc61476742a6205956d2de4ce4c1b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
** Copyright (C) 2025 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by the
** Free Software Foundation; either version 3, or (at your option) any
** later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**
*/
#include "config.h"

#include "mu-scm.hh"

#include <thread>
#include <unistd.h>
#include <errno.h>

#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include "mu-utils.hh"

#include "mu-scm-types.hh"

#ifdef HAVE_PTHREAD_SETNAME_NP
#include <pthread.h>
#endif

using namespace Mu;
using namespace Mu::Scm;

namespace {
SCM mu_mod; // The mu module
}

/**
 * Create a plist for the relevant option items
 *
 * @param opts
 */
static void
init_options(const Options& opts)
{
	SCM scm_opts = alist_add(SCM_EOL,
				 make_symbol("verbose"), opts.verbose,
				 make_symbol("debug"), opts.debug,
				 make_symbol("quiet"), opts.quiet);

	if (opts.muhome.empty())
		scm_opts = alist_add(scm_opts, make_symbol("mu-home"), SCM_BOOL_F);
	else
		scm_opts = alist_add(scm_opts, make_symbol("mu-home"), opts.muhome);

	scm_c_define("%options", scm_opts);
}

static const Result<std::string>
make_mu_scm_path(const std::string& fname) {

	const std::string dir = []() {
		if (const char *altpath{::getenv("MU_SCM_DIR")}; altpath)
			return altpath;
		else
			return MU_SCM_DIR;
	}();

	auto fpath{join_paths(dir, fname)};
	if (::access(fpath.c_str(), R_OK) != 0)
		return Err(Error::Code::File, "cannot read {}: {}",
			   fpath, ::strerror(errno));
	else
		return Ok(std::move(fpath));
}

namespace {
std::string mu_scm_path;
std::string mu_scm_repl_path;
std::string mu_scm_socket_path;
constexpr auto SOCKET_PATH_ENV = "MU_SCM_SOCKET_PATH";
using StrVec = std::vector<std::string>;
StrVec scm_args;
std::thread scm_worker;
}

static Result<void>
prepare_run(const Mu::Options& opts)
{
	// do a checks _before_ entering guile, so we get a bit more civilized
	// error message.
	if (const auto path = make_mu_scm_path("mu-scm.scm"); path)
		mu_scm_path = *path;
	else
		return Err(path.error());

	if (const auto path = make_mu_scm_path("mu-scm-repl.scm"); path)
		mu_scm_repl_path = *path;
	else
		return Err(path.error());

	if (opts.scm.script_path) {
		const auto path{opts.scm.script_path->c_str()};
		if (const auto res = ::access(path, R_OK); res != 0) {
			return Err(Error::Code::InvalidArgument,
				   "cannot read '{}': {}", path, ::strerror(errno));
		}
	}

	return Ok();
}

static void
prepare_script(const Options& opts, StrVec& args)
{
	static std::string cmd; // keep alive

	// XXX: couldn't get another combination of -l/-s/-e/-c to work
	// a) invokes `main' with arguments, and
	// b) exits (rather than drop to a shell)
	// but, what works is to manually specify (main ....)
	cmd = "(main " + quote(*opts.scm.script_path);
	for (const auto& scriptarg : opts.scm.params)
		cmd += " " + quote(scriptarg);
	cmd += ")";

	args.emplace_back("-l");
	args.emplace_back(*opts.scm.script_path);
	args.emplace_back("-c");
	args.emplace_back(cmd);
}

static void
maybe_remove_socket_path()
{
	struct stat statbuf{};
	const auto sock{mu_scm_socket_path};

	// opportunistic, so no real warnings, but be careful deleting!

	if (const int res = ::stat(sock.c_str(), &statbuf); res != 0) {
		mu_debug("can't stat '{}'; err={}", sock, -res);
	} else if ((statbuf.st_mode & S_IFMT) != S_IFSOCK) {
		mu_debug("{} is not a socket", sock);
	} else if (const int ulres = ::unlink(sock.c_str()); ulres != 0) {
		mu_debug("failed to unlink '{}'; err={}", sock, -ulres);
	} else {
		mu_debug("unlinked {}", sock);
	}
}



static void
prepare_shell(const Options& opts, StrVec& args)
{
	// drop us into an interactive shell/repl or start listening on a domain socket.
	if (opts.scm.listen && opts.scm.socket_path) {
		mu_scm_socket_path = *opts.scm.socket_path;
		g_setenv(SOCKET_PATH_ENV, mu_scm_socket_path.c_str(), 1);
		mu_info("setting up socket-path {}", mu_scm_socket_path);
		::atexit(maybe_remove_socket_path); //opportunistic cleanup
	}
	else
		g_unsetenv(SOCKET_PATH_ENV);

	args.emplace_back("--no-auto-compile");
	args.emplace_back("-l");
	args.emplace_back(mu_scm_repl_path);
}


struct ModMuData { const Mu::Store& store; const Mu::Options& opts; };

static void
init_module_mu(void* data)
{
	const ModMuData& conf{*reinterpret_cast<ModMuData*>(data)};

	init_options(conf.opts);
	init_store(conf.store);
	init_message();
	init_mime();
}

static void
run_scm(const Mu::Store& store, const Mu::Options& opts)
{
	static ModMuData mu_data{store, opts};

	scm_boot_guile(0, {},
		       [](auto _data, auto _argc, auto _argv) {
			       mu_mod = scm_c_define_module ("mu", init_module_mu, &mu_data);
		std::vector<char*> args;
		std::transform(scm_args.begin(),
			       scm_args.end(), std::back_inserter(args),
			       [&](const std::string& strarg){
				       /* ahem...*/
				       return const_cast<char*>(strarg.c_str());
		});
		scm_shell(args.size(), args.data());

	}, {}); // never returns.
}

Result<void>
Mu::Scm::run(const Mu::Store& store, const Mu::Options& opts, bool blocking)
{
	if (const auto res = prepare_run(opts); !res)
		return Err(res.error());

	scm_args = {"mu", "-l", mu_scm_path};

	// do env stuff _before_ starting guile / threads.
	if (opts.scm.script_path)
		prepare_script(opts, scm_args);
	else
		prepare_shell(opts, scm_args);

	// in the non-blocking case, we start guile in a
	// background thread; otherwise it will block.
	if (!blocking) {
		auto worker = std::thread([&](){
#ifdef HAVE_PTHREAD_SETNAME_NP
			pthread_setname_np(pthread_self(), "mu-scm");
#endif /*HAVE_PTHREAD_SETNAME_NP*/
			run_scm(store, opts);
		});
		worker.detach();
	} else
		run_scm(store, opts);

	return Ok();

}


#ifdef BUILD_TESTS

/*
 * Tests.
 *
 */
#include <config.h>
#include <mu-store.hh>
#include "utils/mu-test-utils.hh"

static void
test_scm_script()
{
	TempDir tempdir{};
	const auto MuTestMaildir{ Mu::canonicalize_filename(MU_TESTMAILDIR, "/")};

	::setenv("MU_TESTTEMPDIR", tempdir.path().c_str(), 1);

	auto store{Store::make_new(tempdir.path(), MuTestMaildir)};
	assert_valid_result(store);

	{
		const auto res = store->indexer().start({}, true/*block*/);
		g_assert_true(res);
	}

	// add some label for testing
	{
		auto res = store->run_query("optimization");
		const Labels::DeltaLabelVec labels{*Labels::parse_delta_label("+performance")};
		assert_valid_result(res);
		g_assert_cmpuint(res->size(), ==, 4);
		for (auto& it: *res) {
			auto msg{it.message()};
			g_assert_true(!!msg);
			const auto updateres{store->update_labels(*msg, labels)};
			assert_valid_result(updateres);
		}
	}

	Mu::Options opts{};
	opts.scm.script_path = join_paths(MU_SCM_SRCDIR, "mu-scm-test.scm");

	{
		const auto res = Mu::Scm::run(*store, opts, false /*blocks*/);
		assert_valid_result(res);
	}
}

int
main(int argc, char* argv[])
{
	::setenv("MU_SCM_DIR", MU_SCM_SRCDIR, 1);
	::setenv("MU_TESTDATADIR", MU_TESTDATADIR, 1);

	mu_test_init(&argc, &argv);

	g_test_add_func("/scm/script", test_scm_script);

	return g_test_run();
}

#endif /*BUILD_TESTS*/