1 /**
2 Copyright: Copyright (c) 2018, Joakim Brännström. All rights reserved.
3 License: MPL-2
4 Author: Joakim Brännström (joakim.brannstrom@gmx.com)
5 
6 This Source Code Form is subject to the terms of the Mozilla Public License,
7 v.2.0. If a copy of the MPL was not distributed with this file, You can obtain
8 one at http://mozilla.org/MPL/2.0/.
9 */
10 module autoformat.format_rust;
11 
12 import std.algorithm;
13 import std.array;
14 import std.exception;
15 import std.file;
16 import std.string : join;
17 import std.process;
18 import logger = std.experimental.logger;
19 
20 import std.typecons : Flag;
21 
22 import autoformat.types;
23 
24 // Thread local optimization that reduced the console spam when the program
25 // isn't installed.
26 private bool installed = true;
27 
28 auto runRustFormatter(AbsolutePath fname, Flag!"backup" backup, Flag!"dryRun" dry_run) nothrow {
29     if (!installed) {
30         return FormatterResult(Unchanged.init);
31     }
32 
33     string[] opts;
34 
35     if (dry_run)
36         opts ~= "--check";
37     else if (backup)
38         opts ~= "--backup";
39 
40     auto rval = FormatterResult(FormatError.init);
41 
42     try {
43         auto arg = ["rustfmt"] ~ opts ~ (cast(string) fname);
44         logger.trace(arg.join(" "));
45         auto res = execute(arg);
46         logger.trace(res.output);
47 
48         rval = FormattedOk.init;
49     } catch (ProcessException ex) {
50         // rustfmt isn't installed
51         rval = FailedWithUserMsg(ex.msg);
52         installed = false;
53     } catch (Exception ex) {
54         rval = FailedWithUserMsg(ex.msg);
55     }
56 
57     return rval;
58 }