-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlingth
executable file
·323 lines (278 loc) · 8.84 KB
/
lingth
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
#!/usr/bin/php
<?php
/**
* lingth
*
* Identify lines longer than a given character length.
*
* This script provides a command-line interface to the check_line_lengths
* function, and supports various options, multiple files, input redirection,
* configuration, and usage info.
*/
// Stop if we're trying to run via a non-cli interface such as a web server.
if (php_sapi_name() != "cli") {
exit("cli only");
}
// Store the name of the binary for use in errors, etc.
define("NAME", basename(array_shift($argv)));
// Exit status error values
define("ERR_BAD_USAGE", 1);
define("ERR_BAD_CONFIG", 2);
define("ERR_BAD_FILE", 3);
// Extract options from config file and command line arguments.
$opts = read_config();
$opts = proc_options($argv, $opts);
// If not specified, this option depends on the number of files
if (!array_key_exists("show_filenames", $opts)
|| $opts["show_filenames"] == null
) {
$opts["show_filenames"] = count($argv) > 1;
}
if (count($argv)) {
// Handle filenames passed as parameters.
foreach ($argv as $filename) {
if (($path = realpath($filename)) === false) {
fwrite(STDERR, NAME.": $filename: No such file\n");
exit(ERR_BAD_FILE);
} elseif (is_dir($path)) {
fwrite(STDERR, NAME.": $filename: Is a directory\n");
exit(ERR_BAD_FILE);
}
$results = check_line_lengths(
$filename,
file_get_contents($path),
$opts
);
echo cli_report($filename, $results, $opts);
}
} else if (!posix_isatty(STDIN)) {
// Handle any input piped or redirected here.
$line_number = 1;
while (($line = fgets(STDIN)) !== false) {
if (($result = check_line_length(trim($line), $line_number++, $opts)) !== false) {
echo cli_report("(standard input)", array($result), $opts);
}
}
exit(0);
} else {
fwrite(STDERR, usage());
exit(ERR_BAD_USAGE);
}
/**
* Read configuration from json file. Search locations according to the XDG
* Base Directory Specification.
*
* @return Array A map of configuration values.
*/
function read_config()
{
$config_dirs = getenv('XDG_CONFIG_DIRS');
if ($config_dirs === false) {
$config_dirs = array('/etc/xdg');
} else {
$config_dirs = explode(':', $config_dirs);
}
$config_home = getenv('XDG_CONFIG_HOME');
if ($config_home === false) {
$config_home = getenv('HOME').'/.config';
}
$config_dirs[] = $config_home;
foreach ($config_dirs as $dir) {
if (file_exists($file = $dir."/".NAME."/config.json")) {
return json_decode(file_get_contents($file), true);
}
}
fwrite(STDERR, "bad error: no config file. install one.\n");
exit(ERR_BAD_CONFIG);
}
/**
* Process options from arguments passed to the script.
*
* @param Array $args Set of strings representing command line arguments.
* @param Array $opts Map of options to overwrite/augment.
*
* @return Array New map of options.
*/
function proc_options(&$args, $opts)
{
while (count($args) && $args[0][0] == '-') {
if (($arg = array_shift($args)) == '--') {
break;
}
if ($arg == "--help") {
fwrite(STDOUT, usage(true));
exit(0);
}
for ($ch = 1; $ch < strlen($arg); $ch++) {
switch ($arg[$ch]) {
case 'c': $opts['show_content'] = false; break;
case 'H': $opts['show_filenames'] = true; break;
case 'h': $opts['show_filenames'] = false; break;
case 'l': $opts['show_length'] = false; break;
case 'm': $opts['max_length'] = handle_arg(substr($arg, $ch), $args); break;
case 'n': $opts['show_line_numbers'] = false; break;
case 'p': $opts['replace_tabs'] = false; break;
case 't': $opts['tab_width'] = handle_arg(substr($arg, $ch), $args); break;
default:
if (!is_numeric($arg[$ch])) {
fwrite(
STDERR,
NAME.": illegal option -- ".$arg[$ch]."\n"
);
fwrite(STDERR, usage());
exit(ERR_BAD_USAGE);
}
}
}
}
return $opts;
}
/**
* Process a command-line option that requires an argument
*
* @param String $arg Argument to process.
* @param Array $args Full list of unprocessed arguments.
*
* @return int Argument value
*/
function handle_arg($arg, &$args)
{
if (strlen($arg) > 2) {
$argval = substr($arg, 2);
} elseif (count($args)) {
$argval = array_shift($args);
} else {
fwrite(STDERR, NAME.": Option requires an argument -- ".$arg[1]."\n");
fwrite(STDERR, usage());
exit(ERR_BAD_USAGE);
}
if (!is_numeric($argval)) {
fwrite(
STDERR,
NAME.": Invalid argument; must be numeric -- ".$argval."\n"
);
fwrite(STDERR, usage());
exit(ERR_BAD_USAGE);
}
return (int)$argval;
}
/**
* Check line lengths.
*
* This is the main functionality of lingth, reporting on lines that are
* longer than the specified maximum, and including details such as line
* numbers.
*
* @param String $filename Name representing the file being checked
* @param String $contents Contents of the file
* @param Array $options Options/flags to control behaviour
*
* @return string Report containing info for each instance of a long line
*/
function check_line_lengths($filename, $contents, $options)
{
$lines = explode("\n", $contents);
$options["encoding"] = mb_detect_encoding($contents);
$out = array();
foreach ($lines as $line_number => $line) {
if ($result = check_line_length($line, $line_number + 1, $options)) {
$out[] = $result;
}
}
return $out;
}
/**
* @param String $line
* @param int $line_number
*/
function check_line_length($line, $line_number, $options)
{
if ($options["replace_tabs"]) {
$line_tr = retab_front($line, $options["tab_width"]);
} else {
$line_tr = $line;
}
$result = false;
$encoding = array_key_exists("encoding", $options)
? $options["encoding"]
: mb_detect_encoding($line);
if (($len = mb_strlen($line_tr, $encoding)) > $options["max_length"]) {
$result = array("line" => $line);
if ($options["show_line_numbers"]) {
$result["line_number"] = $line_number;
}
if ($options["show_length"]) {
$result["length"] = $len;
}
}
return $result;
}
/**
* Format line-length results for terminal output.
*
* @param String $filename Name of file that produced these results
* @param Array $results Results obtained from check_line_lengths()
* @param Array $options Options/flags to control behaviour (see above)
*
* @return string Results formatted for terminal output
*/
function cli_report($filename, $results, $options)
{
$out = "";
foreach ($results as $result) {
$out .= ($options['show_filenames'] ? $filename.':' : '')
.($options['show_line_numbers'] ? $result['line_number'].' ' : '')
.($options['show_content'] ? $result["line"] : '')
.($options['show_length'] ? " ".$result["length"] : '')
."\n";
}
return $out;
}
/**
* Replace leading tabs with equivalent spaces.
*
* @param string $str String to replace tabs in
* @param int $tab_width Number of spaces to replace each tab with
*
* @return String after any and all replacements have been made
*/
function retab_front($str, $tab_width)
{
return preg_replace_callback(
'/^\t+/',
function($matches) use($tab_width) {
return str_repeat(' ', $tab_width * strlen($matches[0]));
},
$str
);
}
/**
* Get usage string.
*
* @todo Should the description for display booleans be "Don't show" or "Hide"?
*
* @return string usage
*/
function usage($long = false)
{
$out = sprintf("usage: %s [-chHlnp] [-m num] [-t num] [file ...]\n", NAME)
.sprintf(" %s [--help]\n", NAME);
if ($long) {
$out .= ""
." -c don't show content\n"
." -h don't show filenames\n"
." -H show filenames\n"
." -l don't show length\n"
." -L show length\n"
." -m num set length limit\n"
." -n don't show line numbers\n"
." -N show line numbers\n"
." -p don't replace tabs with spaces\n"
." -P replace tabs with spaces\n"
." -t num set tab width in spaces\n\n"
." --help display this help and exit\n";
} else {
$out .= sprintf("Try `%s --help' for more information.\n", NAME);
}
return $out;
}