2 * Implements the file command for jim
4 * (c) 2008 Steve Bennett <steveb@workware.net.au>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials
15 * provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE JIM TCL PROJECT ``AS IS'' AND ANY
18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
19 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 * JIM TCL PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
22 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * The views and conclusions contained in the software and documentation
31 * are those of the authors and should not be interpreted as representing
32 * official policies, either expressed or implied, of the Jim Tcl Project.
34 * Based on code originally from Tcl 6.7:
36 * Copyright 1987-1991 Regents of the University of California
37 * Permission to use, copy, modify, and distribute this
38 * software and its documentation for any purpose and without
39 * fee is hereby granted, provided that the above copyright
40 * notice appear in all copies. The University of California
41 * makes no representations about the suitability of this
42 * software for any purpose. It is provided "as is" without
43 * express or implied warranty.
53 #include <sys/param.h>
57 #include "jimautoconf.h"
58 #include "jim-subcmd.h"
61 # define MAXPATHLEN JIM_PATH_LEN
65 *----------------------------------------------------------------------
69 * Given a mode word, returns a string identifying the type of a
73 * A static text string giving the file type from mode.
78 *----------------------------------------------------------------------
81 static const char *JimGetFileType(int mode
)
86 else if (S_ISDIR(mode
)) {
89 else if (S_ISCHR(mode
)) {
90 return "characterSpecial";
92 else if (S_ISBLK(mode
)) {
93 return "blockSpecial";
95 else if (S_ISFIFO(mode
)) {
99 else if (S_ISLNK(mode
)) {
104 else if (S_ISSOCK(mode
)) {
112 *----------------------------------------------------------------------
116 * This is a utility procedure that breaks out the fields of a
117 * "stat" structure and stores them in textual form into the
118 * elements of an associative array.
121 * Returns a standard Tcl return value. If an error occurs then
122 * a message is left in interp->result.
125 * Elements of the associative array given by "varName" are modified.
127 *----------------------------------------------------------------------
130 static int set_array_int_value(Jim_Interp
*interp
, Jim_Obj
*container
, const char *key
,
133 Jim_Obj
*nameobj
= Jim_NewStringObj(interp
, key
, -1);
134 Jim_Obj
*valobj
= Jim_NewWideObj(interp
, value
);
136 if (Jim_SetDictKeysVector(interp
, container
, &nameobj
, 1, valobj
, JIM_ERRMSG
) != JIM_OK
) {
137 Jim_FreeObj(interp
, nameobj
);
138 Jim_FreeObj(interp
, valobj
);
144 static int set_array_string_value(Jim_Interp
*interp
, Jim_Obj
*container
, const char *key
,
147 Jim_Obj
*nameobj
= Jim_NewStringObj(interp
, key
, -1);
148 Jim_Obj
*valobj
= Jim_NewStringObj(interp
, value
, -1);
150 if (Jim_SetDictKeysVector(interp
, container
, &nameobj
, 1, valobj
, JIM_ERRMSG
) != JIM_OK
) {
151 Jim_FreeObj(interp
, nameobj
);
152 Jim_FreeObj(interp
, valobj
);
158 static int StoreStatData(Jim_Interp
*interp
, Jim_Obj
*varName
, const struct stat
*sb
)
160 if (set_array_int_value(interp
, varName
, "dev", sb
->st_dev
) != JIM_OK
) {
161 Jim_SetResultFormatted(interp
, "can't set \"%#s(dev)\": variables isn't array", varName
);
164 set_array_int_value(interp
, varName
, "ino", sb
->st_ino
);
165 set_array_int_value(interp
, varName
, "mode", sb
->st_mode
);
166 set_array_int_value(interp
, varName
, "nlink", sb
->st_nlink
);
167 set_array_int_value(interp
, varName
, "uid", sb
->st_uid
);
168 set_array_int_value(interp
, varName
, "gid", sb
->st_gid
);
169 set_array_int_value(interp
, varName
, "size", sb
->st_size
);
170 set_array_int_value(interp
, varName
, "atime", sb
->st_atime
);
171 set_array_int_value(interp
, varName
, "mtime", sb
->st_mtime
);
172 set_array_int_value(interp
, varName
, "ctime", sb
->st_ctime
);
173 set_array_string_value(interp
, varName
, "type", JimGetFileType((int)sb
->st_mode
));
175 /* And also return the value */
176 Jim_SetResult(interp
, Jim_GetVariable(interp
, varName
, 0));
181 static int file_cmd_dirname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
183 const char *path
= Jim_String(argv
[0]);
184 const char *p
= strrchr(path
, '/');
187 Jim_SetResultString(interp
, ".", -1);
189 else if (p
== path
) {
190 Jim_SetResultString(interp
, "/", -1);
192 #if defined(__MINGW32__)
193 else if (p
[-1] == ':') {
195 Jim_SetResultString(interp
, path
, p
- path
+ 1);
199 Jim_SetResultString(interp
, path
, p
- path
);
204 static int file_cmd_rootname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
206 const char *path
= Jim_String(argv
[0]);
207 const char *lastSlash
= strrchr(path
, '/');
208 const char *p
= strrchr(path
, '.');
210 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
> p
)) {
211 Jim_SetResult(interp
, argv
[0]);
214 Jim_SetResultString(interp
, path
, p
- path
);
219 static int file_cmd_extension(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
221 const char *path
= Jim_String(argv
[0]);
222 const char *lastSlash
= strrchr(path
, '/');
223 const char *p
= strrchr(path
, '.');
225 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
>= p
)) {
228 Jim_SetResultString(interp
, p
, -1);
232 static int file_cmd_tail(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
234 const char *path
= Jim_String(argv
[0]);
235 const char *lastSlash
= strrchr(path
, '/');
238 Jim_SetResultString(interp
, lastSlash
+ 1, -1);
241 Jim_SetResult(interp
, argv
[0]);
246 static int file_cmd_normalize(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
249 const char *path
= Jim_String(argv
[0]);
250 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
252 if (realpath(path
, newname
)) {
253 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, -1));
257 Jim_SetResult(interp
, argv
[0]);
261 Jim_SetResultString(interp
, "Not implemented", -1);
266 static int file_cmd_join(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
269 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
270 char *last
= newname
;
274 /* Simple implementation for now */
275 for (i
= 0; i
< argc
; i
++) {
277 const char *part
= Jim_GetString(argv
[i
], &len
);
280 /* Absolute component, so go back to the start */
283 #if defined(__MINGW32__)
284 else if (strchr(part
, ':')) {
285 /* Absolute compontent on mingw, so go back to the start */
289 else if (part
[0] == '.') {
290 if (part
[1] == '/') {
294 else if (part
[1] == 0 && last
!= newname
) {
295 /* Adding '.' to an existing path does nothing */
300 /* Add a slash if needed */
301 if (last
!= newname
&& last
[-1] != '/') {
306 if (last
+ len
- newname
>= MAXPATHLEN
) {
308 Jim_SetResultString(interp
, "Path too long", -1);
311 memcpy(last
, part
, len
);
315 /* Remove a slash if needed */
316 if (last
> newname
+ 1 && last
[-1] == '/') {
323 /* Probably need to handle some special cases ... */
325 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, last
- newname
));
330 static int file_access(Jim_Interp
*interp
, Jim_Obj
*filename
, int mode
)
332 const char *path
= Jim_String(filename
);
333 int rc
= access(path
, mode
);
335 Jim_SetResultBool(interp
, rc
!= -1);
340 static int file_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
342 return file_access(interp
, argv
[0], R_OK
);
345 static int file_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
347 return file_access(interp
, argv
[0], W_OK
);
350 static int file_cmd_executable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
352 return file_access(interp
, argv
[0], X_OK
);
355 static int file_cmd_exists(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
357 return file_access(interp
, argv
[0], F_OK
);
360 static int file_cmd_delete(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
362 int force
= Jim_CompareStringImmediate(interp
, argv
[0], "-force");
364 if (force
|| Jim_CompareStringImmediate(interp
, argv
[0], "--")) {
370 const char *path
= Jim_String(argv
[0]);
372 if (unlink(path
) == -1 && errno
!= ENOENT
) {
373 if (rmdir(path
) == -1) {
374 /* Maybe try using the script helper */
375 if (!force
|| Jim_EvalPrefix(interp
, "file delete force", 1, argv
) != JIM_OK
) {
376 Jim_SetResultFormatted(interp
, "couldn't delete file \"%s\": %s", path
,
387 #ifdef HAVE_MKDIR_ONE_ARG
388 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
390 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
394 * Create directory, creating all intermediate paths if necessary.
396 * Returns 0 if OK or -1 on failure (and sets errno)
398 * Note: The path may be modified.
400 static int mkdir_all(char *path
)
404 /* First time just try to make the dir */
408 /* Must have failed the first time, so recursively make the parent and try again */
409 char *slash
= strrchr(path
, '/');
411 if (slash
&& slash
!= path
) {
413 if (mkdir_all(path
) != 0) {
419 if (MKDIR_DEFAULT(path
) == 0) {
422 if (errno
== ENOENT
) {
423 /* Create the parent and try again */
426 /* Maybe it already exists as a directory */
427 if (errno
== EEXIST
) {
430 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
442 static int file_cmd_mkdir(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
445 char *path
= Jim_StrDup(Jim_String(argv
[0]));
446 int rc
= mkdir_all(path
);
450 Jim_SetResultFormatted(interp
, "can't create directory \"%#s\": %s", argv
[0],
460 static int file_cmd_tempfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
464 const char *template = "/tmp/tcl.tmp.XXXXXX";
467 template = Jim_String(argv
[0]);
469 filename
= Jim_StrDup(template);
471 fd
= mkstemp(filename
);
473 Jim_SetResultString(interp
, "Failed to create tempfile", -1);
478 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, filename
, -1));
483 static int file_cmd_rename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
490 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-force")) {
498 source
= Jim_String(argv
[0]);
499 dest
= Jim_String(argv
[1]);
501 if (!force
&& access(dest
, F_OK
) == 0) {
502 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": target exists", argv
[0],
507 if (rename(source
, dest
) != 0) {
508 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
516 static int file_stat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
518 const char *path
= Jim_String(filename
);
520 if (stat(path
, sb
) == -1) {
521 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
531 static int file_lstat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
533 const char *path
= Jim_String(filename
);
535 if (lstat(path
, sb
) == -1) {
536 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
542 static int file_cmd_atime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
546 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
549 Jim_SetResultInt(interp
, sb
.st_atime
);
553 static int file_cmd_mtime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
560 struct timeval times
[2];
562 if (Jim_GetWide(interp
, argv
[1], &newtime
) != JIM_OK
) {
566 times
[1].tv_sec
= times
[0].tv_sec
= newtime
;
567 times
[1].tv_usec
= times
[0].tv_usec
= 0;
569 if (utimes(Jim_String(argv
[0]), times
) != 0) {
570 Jim_SetResultFormatted(interp
, "can't set time on \"%#s\": %s", argv
[0], strerror(errno
));
574 Jim_SetResultString(interp
, "Not implemented", -1);
578 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
581 Jim_SetResultInt(interp
, sb
.st_mtime
);
585 static int file_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
587 return Jim_EvalPrefix(interp
, "file copy", argc
, argv
);
590 static int file_cmd_size(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
594 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
597 Jim_SetResultInt(interp
, sb
.st_size
);
601 static int file_cmd_isdirectory(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
606 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
607 ret
= S_ISDIR(sb
.st_mode
);
609 Jim_SetResultInt(interp
, ret
);
613 static int file_cmd_isfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
618 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
619 ret
= S_ISREG(sb
.st_mode
);
621 Jim_SetResultInt(interp
, ret
);
626 static int file_cmd_owned(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
631 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
632 ret
= (geteuid() == sb
.st_uid
);
634 Jim_SetResultInt(interp
, ret
);
639 #if defined(HAVE_READLINK)
640 static int file_cmd_readlink(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
642 const char *path
= Jim_String(argv
[0]);
643 char *linkValue
= Jim_Alloc(MAXPATHLEN
+ 1);
645 int linkLength
= readlink(path
, linkValue
, MAXPATHLEN
);
647 if (linkLength
== -1) {
649 Jim_SetResultFormatted(interp
, "couldn't readlink \"%#s\": %s", argv
[0], strerror(errno
));
652 linkValue
[linkLength
] = 0;
653 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, linkValue
, linkLength
));
658 static int file_cmd_type(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
662 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
665 Jim_SetResultString(interp
, JimGetFileType((int)sb
.st_mode
), -1);
669 static int file_cmd_lstat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
673 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
676 return StoreStatData(interp
, argv
[1], &sb
);
679 static int file_cmd_stat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
683 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
686 return StoreStatData(interp
, argv
[1], &sb
);
689 static const jim_subcmd_type file_command_table
[] = {
692 .function
= file_cmd_atime
,
695 .description
= "Last access time"
698 .args
= "name ?time?",
699 .function
= file_cmd_mtime
,
702 .description
= "Get or set last modification time"
705 .args
= "?-force? source dest",
706 .function
= file_cmd_copy
,
709 .description
= "Copy source file to destination file"
713 .function
= file_cmd_dirname
,
716 .description
= "Directory part of the name"
720 .function
= file_cmd_rootname
,
723 .description
= "Name without any extension"
725 { .cmd
= "extension",
727 .function
= file_cmd_extension
,
730 .description
= "Last extension including the dot"
734 .function
= file_cmd_tail
,
737 .description
= "Last component of the name"
739 { .cmd
= "normalize",
741 .function
= file_cmd_normalize
,
744 .description
= "Normalized path of name"
747 .args
= "name ?name ...?",
748 .function
= file_cmd_join
,
751 .description
= "Join multiple path components"
755 .function
= file_cmd_readable
,
758 .description
= "Is file readable"
762 .function
= file_cmd_writable
,
765 .description
= "Is file writable"
767 { .cmd
= "executable",
769 .function
= file_cmd_executable
,
772 .description
= "Is file executable"
776 .function
= file_cmd_exists
,
779 .description
= "Does file exist"
782 .args
= "?-force|--? name ...",
783 .function
= file_cmd_delete
,
786 .description
= "Deletes the files or directories (must be empty unless -force)"
790 .function
= file_cmd_mkdir
,
793 .description
= "Creates the directories"
797 .args
= "?template?",
798 .function
= file_cmd_tempfile
,
801 .description
= "Creates a temporary filename"
805 .args
= "?-force? source dest",
806 .function
= file_cmd_rename
,
809 .description
= "Renames a file"
811 #if defined(HAVE_READLINK)
814 .function
= file_cmd_readlink
,
817 .description
= "Value of the symbolic link"
822 .function
= file_cmd_size
,
825 .description
= "Size of file"
829 .function
= file_cmd_stat
,
832 .description
= "Stores results of stat in var array"
836 .function
= file_cmd_lstat
,
839 .description
= "Stores results of lstat in var array"
843 .function
= file_cmd_type
,
846 .description
= "Returns type of the file"
851 .function
= file_cmd_owned
,
854 .description
= "Returns 1 if owned by the current owner"
857 { .cmd
= "isdirectory",
859 .function
= file_cmd_isdirectory
,
862 .description
= "Returns 1 if name is a directory"
866 .function
= file_cmd_isfile
,
869 .description
= "Returns 1 if name is a file"
876 static int Jim_CdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
881 Jim_WrongNumArgs(interp
, 1, argv
, "dirname");
885 path
= Jim_String(argv
[1]);
887 if (chdir(path
) != 0) {
888 Jim_SetResultFormatted(interp
, "couldn't change working directory to \"%s\": %s", path
,
895 static int Jim_PwdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
897 const int cwd_len
= 2048;
898 char *cwd
= malloc(cwd_len
);
900 if (getcwd(cwd
, cwd_len
) == NULL
) {
901 Jim_SetResultString(interp
, "Failed to get pwd", -1);
904 #if defined(__MINGW32__)
906 /* Try to keep backlashes out of paths */
908 while ((p
= strchr(p
, '\\')) != NULL
) {
914 Jim_SetResultString(interp
, cwd
, -1);
920 int Jim_fileInit(Jim_Interp
*interp
)
922 if (Jim_PackageProvide(interp
, "file", "1.0", JIM_ERRMSG
))
925 Jim_CreateCommand(interp
, "file", Jim_SubCmdProc
, (void *)file_command_table
, NULL
);
926 Jim_CreateCommand(interp
, "pwd", Jim_PwdCmd
, NULL
, NULL
);
927 Jim_CreateCommand(interp
, "cd", Jim_CdCmd
, NULL
, NULL
);