-
Notifications
You must be signed in to change notification settings - Fork 22
/
LibPQ.pq
328 lines (312 loc) · 12 KB
/
LibPQ.pq
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/**
LibPQ:
Access Power Query functions and queries stored in source code modules
on filesystem or on the Web.
Project website:
https://libpq.ml
This code was last modified on 2019-10-11
Timestamp in docstring is necessary for further updating, because this code
will be copied into the workbook and will be managed manually afterwards.
**/
let
/* Read LibPQ settings */
Sources.Local = LibPQPath[Local],
Sources.Web = LibPQPath[Web],
/* Constants */
EXTENSION = ".pq",
PATHSEPLOCAL = Text.Start("\\",1),
PATHSEPREMOTE = "/",
ERR_SOURCE_UNREADABLE = "LibPQ.ReadError",
DESCRIPTION_FOOTER = (path) =>
"<br><br>" &
"<i><div>" &
"This module was loaded with LibPQ: https://github.com/sio/LibPQ" &
"</div><div>" &
"Module source code: " &
path &
"</div></i>",
/* Load text content from local file or from web */
Read.Text = (destination as text, optional local as logical) =>
let
Local = if local is null then true else local,
Fetcher = if Local then File.Contents else Web.Contents
in
Text.FromBinary(
Binary.Buffer(
try
Fetcher(destination)
otherwise
error Error.Record(
ERR_SOURCE_UNREADABLE,
"Read.Text: can not fetch from destination",
destination
)
)
),
/*
Read the first multiline comment from the source code in Power Query
Formula language (also known as M language). That comment is considered a
docstring for LibPQ
*/
Read.Docstring = (source_code as text) =>
let
Docstring = [
start = "/*",
end = "*/"
],
DocstringDirty = Text.BeforeDelimiter(
source_code,
Docstring[end]
),
BeforeDocstring = Text.BeforeDelimiter(
DocstringDirty,
Docstring[start]
),
MustBeEmpty = Text.Trim(BeforeDocstring),
DocstringText =
if
Text.Length(MustBeEmpty) = 0
then
Text.Trim(DocstringDirty, {"*", "/", " ", "#(cr)", "#(lf)", "#(tab)"})
else
""
in
DocstringText,
/*
Load Power Query function or module from file,
return null if destination unreadable
*/
Module.FromPath = (path as text, optional local as logical, optional name as text) =>
let
SourceCode = try Read.Text(path, local)
otherwise "null",
LoadedObject = Expression.Evaluate(SourceCode, #shared),
LoadTry = try LoadedObject,
CustomError = Record.TransformFields(
LoadTry[Error],
{"Detail", each CustomErrorDetail}
),
CustomErrorDetail = [
Original = LoadTry[Error][Detail],
LibPQ = ExtraMetadata
],
ExtraMetadata = [
LibPQ.Module = name,
LibPQ.Source = path,
LibPQ.Docstring = Read.Docstring(SourceCode),
Documentation.Name = LibPQ.Module,
Documentation.Description =
Text.Replace(LibPQ.Docstring, "#(lf)", "<br>") &
DESCRIPTION_FOOTER(path)
],
OldMetadata = Value.Metadata(LoadedObject),
TypeMetadata = Value.Metadata(Value.Type(LoadedObject)),
Module = Value.ReplaceType(
try LoadedObject otherwise error CustomError,
Value.ReplaceMetadata(
Value.Type(LoadedObject),
Record.Combine({ExtraMetadata, TypeMetadata})
)
) meta Record.Combine({ExtraMetadata, OldMetadata})
in
Module,
/* Calculate where the function code is located */
Module.BuildPath = (funcname as text, directory as text, optional local as logical) =>
let
/* Defaults */
Local = if local is null then true else local,
PathSep = if Local then PATHSEPLOCAL else PATHSEPREMOTE,
/* Path building */
ProperDir = if Text.EndsWith(directory, PathSep)
then directory
else directory & PathSep,
ProperName = Module.NameToProper(funcname),
Return = ProperDir & ProperName & EXTENSION
in
Return,
/* Module name converters */
Module.NameToProper = (name) => Text.Replace(name, "_", "."),
Module.NameFromProper = (name) => Text.Replace(name, ".", "_"),
/* Find all modules in the list of directories */
Module.Explore = (directories as list) =>
let
Files = List.Generate(
() => [i = -1, results = 0],
each [i] < List.Count(directories),
each [
i = [i]+1,
folder = directories{i},
iserror = (try Table.RowCount(
Folder.Contents(folder)
))[HasError], // For some weird reason try does
// not catch DataSource error.
// Check "try Folder.Contents("C:\none")"
// it will return [HasError]=false
files = if iserror then
#table({"Name","Extension"},{})
else
Folder.Contents(folder),
filter = Table.SelectRows(
files,
each [Extension] = EXTENSION
),
results = Table.RowCount(filter),
module = List.Transform(
filter[Name],
each Text.BeforeDelimiter(
_,
EXTENSION,
{0,RelativePosition.FromEnd}
)
)
],
each [
folder = [folder],
module = [module],
results = [results]
]
),
Return = try
Table.ExpandListColumn(
Table.FromRecords(
List.Select(Files, each [results]>0)
),
"module"
)
otherwise
#table({"folder", "module", "results"},{})
in
Return,
/* Import module (first match) from the list of possible locations */
Module.ImportAny = (name as text, locations as list, optional local as logical) =>
let
Paths = List.Transform(
locations,
each Module.BuildPath(name, _, local)
),
Loop = List.Generate(
() => [
i = -1,
object = null,
lasterror = null
],
each [i] < List.Count(Paths),
each [
// `load` should be evaluated only if absolutely necessary.
// If path is unreadable, no error is raised but null value
// is returned (see Module.FromPath)
load = try Module.FromPath(Paths{i}, local, name),
object = if [object] is null and not load[HasError]
then load[Value]
else [object],
lasterror = if [object] is null and load[HasError]
then load[Error]
else [lasterror],
i = [i] + 1
]
),
Return = try
List.Select(Loop, each [object] <> null){0}[object]
otherwise
error if List.Last(Loop)[lasterror] <> null
then List.Last(Loop)[lasterror]
else Error.Record(
ERR_SOURCE_UNREADABLE,
"Module not found: " & name
)
in
Return,
/* Import a module from default locations (LibPQPath) */
Module.Import = (name as text) =>
let
Attempts = {
// {expression, silent errors}
{Record.Field(#shared, Module.NameFromProper(name)), true},
{Record.Field(#shared, Module.NameToProper(name)), true},
{Record.Field(Helpers, name), true},
{Module.ImportAny(name, Sources.Local), false},
{Module.ImportAny(name, Sources.Web, false), false}
},
Results = List.Last(List.Generate(
() => [
i = -1,
module = null,
error = null
],
each [i] < List.Count(Attempts),
each [
i = [i] + 1,
load = try Attempts{i}{0},
error = if
[module] is null and
not Attempts{i}{1} and
load[HasError] and
load[Error][Reason] <> ERR_SOURCE_UNREADABLE
then
load[Error]
else
[error],
module = if
[module] is null and
not load[HasError]
then
load[Value]
else
[module]
]
)),
Module = if Results[module] <> null
then Results[module]
else if Results[module] is null and Results[error] <> null
then error Results[error]
else error Error.Record(
ERR_SOURCE_UNREADABLE,
"Module not found: " & name
)
in
Module,
/* Last touch: export helper functions defined above */
Helpers = [
Read.Text = Read.Text,
Read.Docstring = Read.Docstring,
Module.FromPath = Module.FromPath,
Module.BuildPath = Module.BuildPath,
Module.NameToProper = Module.NameToProper,
Module.NameFromProper = Module.NameFromProper,
Module.Explore = Module.Explore,
Module.ImportAny = Module.ImportAny
],
Library.Names = List.Distinct(Module.Explore(Sources.Local)[module]),
Library = List.Last(
List.Generate(
() => [i=-1,record=[]],
each [i] < List.Count(Library.Names),
each [
i = [i] + 1,
record = Record.AddField(
[record],
Library.Names{i},
let
Try = try Module.Import(Library.Names{i}),
Return = if Try[HasError] then Try[Error] else Try[Value]
in
Return
)
],
each [record]
)
),
Module.Library = Record.Combine({Helpers, Library}),
/* Main function */
Main = (optional modulename as nullable text) =>
if modulename is null
or modulename = "Module.Library"
then
Module.Library
else if modulename = "Module.Import"
then
Module.Import
else
Module.Import(modulename)
in
Main