Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlice.lua
More file actions
Latest commit
383 lines (339 loc) · 12.9 KB
/
Copy pathlice.lua
File metadata and controls
383 lines (339 loc) · 12.9 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
-- =========================================
-- Lice-Lua, A license generator for Lua
-- Copyright (c) 2013 Roland Y., MIT License
-- version 0.1.1 - Uses Lua 5.1, 5.2
-- =========================================
-- =========================================
-- Internals declaration
-- =========================================
-- Catch the passed in root path (handling calls out from the root folder)
localROOT_PATH= (arg[0]:match('(.+)[/\\]%w+%.*%w*') or'')
localtemplates_list=require (ROOT_PATH..'.lice-tpl')
-- Check for dependencies
locallfs
do
assert(pcall(require, 'lfs'),
'Dependency LuaFileSystem not found.\nCannot execute Lice-Lua')
lfs=require'lfs'
end
-- Local binding to global native variables
localpackage=package
localos_getenv=os.getenv
localio_open=io.open
localpairs=pairs
localipairs=ipairs
localtonumber=tonumber
localtable_sort=table.sort
localtable_concat=table.concat
localassert=assert
localerror=error
localprint=print
-- Pattern-matching templates
localTPL_VARS_PATTERN='{{%s([^{}]+)%s}}'
localGET_OPT_PATTERN='(%-%-?)(%a+)%s*([^%-]*)'
localGET_OPT_LIC_PATTERN='^([a-zA-Z0-9%_]+)'
localGET_OPT_DASHES='^%-%-?$'
localOUT_FILE_NAME='^([^.]+)%.*'
localOUT_FILE_EXT='%.([^.]+)$'
localLIC_YEAR_RANGE='^[%d]+[%D+]*[%d+]*$'
-- Default License template
localDEFAULT_LIC_TEMPLATE='bsd3'
-- Binds file exts to LANGS dict
localLANGS_EXT= {}
-- Languages, comment style and file extensions
localLANGS_CMT_STYLE= {}
-- =========================================
-- Os's facilities
-- =========================================
-- Get directory separator
localfunctionget_dir_sep()
return (package.config:sub(1,1))
end
-- Is the actual Windows
localfunctionis_windows()
return (get_dir_sep():match('\\')~=nil)
end
-- Parses major & minor from _VERSION
localfunctionget_lua_version()
localmajor, minor=_VERSION:match('^Lua%s(%d)%.(%d)%.*%d*$')
returntonumber(major), tonumber(minor)
end
-- Executes command (Lua 5.1 & 5.2 compatible)
localfunctionexecute(cmd)
localcode=os.execute(cmd)
local_, lua_v_minor=get_lua_version()
if (lua_v_minor==1) then
return (code==0)
elseif (lua_v_minor==2) then
returncode
end
end
-- To be visible from `silent_execute`
localget_file_contents
-- Executes a command
-- Output is redirected to temporary file
-- Taken from S. Donovan's Penlight
-- See https://github.com/stevedonovan/Penlight/blob/master/lua/pl/utils.lua#L229)
functionsilent_execute(cmd)
localoutfile=os.tmpname()
localerrfile=os.tmpname()
ifis_windows() then
outfile=os_getenv('TEMP')..outfile
errfile=os_getenv('TEMP')..errfile
end
cmd=cmd..' >"'..outfile..'" 2>"'..errfile..'"'
localsuccess=execute(cmd)
localcontents=successandget_file_contents(outfile)
os.remove(outfile)
os.remove(errfile)
returncontents
end
-- Get username from Git, if found in the path.
localfunctionget_username_from_git()
returnsilent_execute('git config user.name')
end
-- Infers the username
localfunctionget_username()
-- Tries to infer from Git
localusername=get_username_from_git()
ifnotusernamethen
username=is_windows() and
os_getenv('USERNAME') or
os_getenv('USER') or ('')
end
returnusername
end
-- Returns the current folder name.
-- Uses Os's directory separator
localfunctionget_current_folder_name()
returnlfs.currentdir():match(('([^%s]+)$')
:format(get_dir_sep()))
end
-- =========================================
-- Internal functions
-- =========================================
-- Collects and returns an array of keys from a given table
localfunctioncollect_keys(list, sorted)
locall= {}
forvinpairs(list) dol[#l+1] =vend
ifsortedthen
table_sort(l)
end
returnl
end
-- Lookup value in table
localfunctiontable_find(t, v)
fork,_vinpairs(t) do
if (_v==v) then
returntrue
end
end
returnfalse
end
-- File extensions to comment style binding helper
localfunctionadd_exts(lang, style, ...)
localexts= {...}
LANGS_CMT_STYLE[lang] =style-- Set the style
for_,extinipairs(exts) do
LANGS_EXT[ext] =lang-- set extensions
end
end
-- Returns the contents of a file
functionget_file_contents(file_path, flag)
localfhandle=assert(io_open(file_path, 'r'),
('Error on attempt to open <%s>'):format(file_path))
localcontents=fhandle:read(flagor'*a')
fhandle:close()
returncontents
end
-- Writes contents to file
localfunctionwrite_to_file(f, contents, append)
ifappendthen
localprevious_contents=get_file_contents(f)
contents=contents..'\n\n' ..previous_contents
end
localfhandle=assert(io_open(f, 'w+'),
('Cannot open file <%s>'):format(f))
fhandle:write(contents)
fhandle:close()
end
-- Returns a list of available templates vars
localfunctionget_template_vars(template_name)
localcontents=templates_list[template_name]
localvars= {}
forvarincontents:gmatch(TPL_VARS_PATTERN) do
vars[#vars+1] =var
end
returnvars
end
-- Applies language specific comment-style to template contents
localfunctionapply_comment_style(input, lang)
localcmt_style=LANGS_CMT_STYLE[lang]
input=input:gsub('([^\n\r]*[\n\r])', function(match)
returncmt_style[2] ..match
end)
return (cmt_style[1] ..'\n' ..input..cmt_style[3])
end
-- Interpolates template variables with the provided set of options
localfunctionwrite_license(opts)
localsource=templates_list[opts.fname]
locallicense_text= (source:gsub(TPL_VARS_PATTERN,opts))
-- File extension has precedence for language and comment-style inference
ifopts.file_extthen
assert((opts.lang==opts.file_ext) or (notopts.lang),
('Inconsistency error: <-l %s> and <-f *.%s>'):format((opts.langor''), opts.file_ext))
-- Apply formatting if extension is featured, otherwise leave it in plain text style.
ifLANGS_EXT[opts.file_ext] then
license_text=apply_comment_style(license_text, LANGS_EXT[opts.file_ext])
end
-- If no file extension was provided, use language
elseifopts.langthen
license_text=apply_comment_style(license_text, opts.lang)
end
ifopts.outthen
localoutput_file=opts.out..
(opts.file_extand ('.' ..opts.file_ext) or'')
-- Does an object with a similar name already exists ?
localis_item=lfs.attributes(output_file)
-- If it is a file, we should append the license inside as a header
localappend=is_itemand (is_item.mode=='file') orfalse
write_to_file(output_file, license_text, append)
else
print(license_text)
end
end
-- =============================================
-- Very minimal (and ugly) GetOpt implementation
-- =============================================
-- Checker for input opt
localfunctioncheck_opt_style(dash, opt)
assert(notdash:match('[^%-]'), 'Input is not valid')
assert(dash:match(GET_OPT_DASHES), 'Input is not valid')
ifdash=='-' then
assert(opt:len() ==1,
('The following was probably mistyped : <%s>'):format(dash..opt))
elseif (dash=='--') then
assert(opt:len() >1,
('The following was probably mistyped : <%s>'):format(dash..opt))
end
end
-- Processes input opt
localfunctionprocess_opt(cfg, template, opt, value)
if (opt=='help' oropt=='h') then
print([[usage: lua lice.lua license [-h] [-o ORGANIZATION] [-p PROJECT]
[-t TEMPLATE_PATH] [-y YEAR]
[--vars] [--header]
positional arguments:
license the license to generate. Defaults to
bsd3 when not given.
optional arguments:
-h, --help show this help message and exit.
-o, --org ORGANIZATION organization. Defaults to
"git config user.name", then environment
variable "USERNAME" (Windows) or "USER"
(on Unix and OSX).
-p, --proj PROJECT name of project, defaults to name of current
directory.
-l, --lang LANGUAGE format output with language comment style,
if available. Mostly meant for shell output.
-y, --year YEAR copyright year, defaults to current date read
from system locale.
-f, --file OFILEPATH path to the output source file. Extension, if
provided, is used to infer a language specific
formatting style for the license header,
if supported.
optional arguments taking no values (no args)
--vars list template variables for the specified
license and exit.
--header will only use the header license (if available).
--list list all available licenses templates and exit
]])
os.exit()
elseifopt=='vars' then
localvars=get_template_vars(template)
print(('License <%s> vars:\n'):format(template))
for_, varinipairs(vars) do
print(' >> ' ..var)
end
os.exit()
elseif (opt=='list') then
localsort_list=true
locallist=collect_keys(templates_list, sort_list)
print(('Available licenses templates:\n'):format(template))
for_,templateinpairs(list) do
print(' >> ' ..template)
end
os.exit()
elseif (opt=='org' oropt=='o') then
cfg.organization=value
elseif (opt=='proj' oropt=='p') then
cfg.project=value
elseif (opt=='year' oropt=='y') then
localyear=value
assert(year:match(LIC_YEAR_RANGE),
('Wrong year: <%s>'):format(value))
cfg.year= (year:gsub('[^%d]+','-'))
elseif (opt=='file' oropt=='f') then
cfg.out=cfg.outorvalue:match(OUT_FILE_NAME)
localfile_ext=value:lower():match(OUT_FILE_EXT)
iffile_extthen
locallang=LANGS_EXT[file_ext]
cfg.file_ext=value:match(OUT_FILE_EXT)
end
elseif (opt=='lang' oropt=='l') then
locallang=value:lower()
localsupported_lang=LANGS_CMT_STYLE[lang] andlangorfalse
ifnotsupported_langthen
supported_lang=LANGS_EXT[lang]
end
assert(supported_lang,('Language <%s> is not supported'):format(lang))
cfg.lang=supported_lang
else
error(
([[Could not resolved unknown opt: <%s>
Use -h (or --help) to print help]]):format(opt))
end
end
-- Main routine, catch and process args
localfunctionmain(_args)
localtemplate= (_args:match(GET_OPT_LIC_PATTERN) orDEFAULT_LIC_TEMPLATE):lower()
-- Handle headers template name auto-completion
if_args:match('%-%-header') andnottemplate:match('%-header$') then
template=template..'-header'
end
-- Asserts the required license is available
assert(templates_list[template],
('License <%s> is not available'):format(template))
-- Default config
localcfg= {
fname=template, -- The template
organization=get_username(), -- Defaults to USERNAME or USER
project=get_current_folder_name(), -- Defaults to current directory
year=os.date('%Y'), -- Defaults to current year
}
-- Catch, check and resolve options
fordash, _opt, valuein_args:gmatch(GET_OPT_PATTERN) do
localopt=_opt:lower()
check_opt_style(dash, opt)
process_opt(cfg, template, opt, (value:gsub('%s$','')))
end
-- Write license to output
write_license(cfg)
end
-- Creates the list of templates
do
-- Registering styles and extensions
add_exts('c', { '/*', ' * ', ' */'}, 'c', 'cc', 'cpp', 'h', 'hpp', 'js', 'css', 'm')
add_exts('fortran', {'! ', '! ', '!'}, 'f' )
add_exts('fortran90', {'!* ', '!* ', '!* '}, 'f90' )
add_exts('java', {'/**', ' * ',' */'}, 'java' )
add_exts('erlang', {'%% ', '% ', '%% '}, 'erl' )
add_exts('html', {'<!--', '', '-->'}, 'html' )
add_exts('lua', {('-'):rep(80), '-- ', ('-'):rep(80)}, 'lua' )
add_exts('perl', {'=item', '', '=cut'}, 'pl' )
add_exts('ruby', {'=begin', '', '=end'}, 'rb' )
add_exts('text', {'', '', ''}, 'txt' )
add_exts('unix', {'', '# ',''}, 'py', 'sh' )
end
-- Calls main and process input
main(table_concat(arg,''))