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 <jimautoconf.h>
54 #include <jim-subcmd.h>
61 #elif defined(_MSC_VER)
66 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
67 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
71 # define MAXPATHLEN JIM_PATH_LEN
75 *----------------------------------------------------------------------
79 * Given a mode word, returns a string identifying the type of a
83 * A static text string giving the file type from mode.
88 *----------------------------------------------------------------------
91 static const char *JimGetFileType(int mode
)
96 else if (S_ISDIR(mode
)) {
100 else if (S_ISCHR(mode
)) {
101 return "characterSpecial";
105 else if (S_ISBLK(mode
)) {
106 return "blockSpecial";
110 else if (S_ISFIFO(mode
)) {
115 else if (S_ISLNK(mode
)) {
120 else if (S_ISSOCK(mode
)) {
128 *----------------------------------------------------------------------
132 * This is a utility procedure that breaks out the fields of a
133 * "stat" structure and stores them in textual form into the
134 * elements of an associative array.
137 * Returns a standard Tcl return value. If an error occurs then
138 * a message is left in interp->result.
141 * Elements of the associative array given by "varName" are modified.
143 *----------------------------------------------------------------------
145 static void AppendStatElement(Jim_Interp
*interp
, Jim_Obj
*listObj
, const char *key
, jim_wide value
)
147 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, key
, -1));
148 Jim_ListAppendElement(interp
, listObj
, Jim_NewIntObj(interp
, value
));
151 static int StoreStatData(Jim_Interp
*interp
, Jim_Obj
*varName
, const struct stat
*sb
)
153 /* Just use a list to store the data */
154 Jim_Obj
*listObj
= Jim_NewListObj(interp
, NULL
, 0);
156 AppendStatElement(interp
, listObj
, "dev", sb
->st_dev
);
157 AppendStatElement(interp
, listObj
, "ino", sb
->st_ino
);
158 AppendStatElement(interp
, listObj
, "mode", sb
->st_mode
);
159 AppendStatElement(interp
, listObj
, "nlink", sb
->st_nlink
);
160 AppendStatElement(interp
, listObj
, "uid", sb
->st_uid
);
161 AppendStatElement(interp
, listObj
, "gid", sb
->st_gid
);
162 AppendStatElement(interp
, listObj
, "size", sb
->st_size
);
163 AppendStatElement(interp
, listObj
, "atime", sb
->st_atime
);
164 AppendStatElement(interp
, listObj
, "mtime", sb
->st_mtime
);
165 AppendStatElement(interp
, listObj
, "ctime", sb
->st_ctime
);
166 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, "type", -1));
167 Jim_ListAppendElement(interp
, listObj
, Jim_NewStringObj(interp
, JimGetFileType((int)sb
->st_mode
), -1));
169 /* Was a variable specified? */
171 Jim_Obj
*objPtr
= Jim_GetVariable(interp
, varName
, JIM_NONE
);
173 if (Jim_DictSize(interp
, objPtr
) < 0) {
174 /* This message matches the one from Tcl */
175 Jim_SetResultFormatted(interp
, "can't set \"%#s(dev)\": variable isn't array", varName
);
176 Jim_FreeNewObj(interp
, listObj
);
180 if (Jim_IsShared(objPtr
))
181 objPtr
= Jim_DuplicateObj(interp
, objPtr
);
183 /* Just cheat here and append as a list and convert to a dict */
184 Jim_ListAppendList(interp
, objPtr
, listObj
);
185 Jim_DictSize(interp
, objPtr
);
186 Jim_InvalidateStringRep(objPtr
);
188 Jim_FreeNewObj(interp
, listObj
);
191 Jim_SetVariable(interp
, varName
, listObj
);
194 /* And also return the value */
195 Jim_SetResult(interp
, listObj
);
200 static int file_cmd_dirname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
202 const char *path
= Jim_String(argv
[0]);
203 const char *p
= strrchr(path
, '/');
205 if (!p
&& path
[0] == '.' && path
[1] == '.' && path
[2] == '\0') {
206 Jim_SetResultString(interp
, "..", -1);
208 Jim_SetResultString(interp
, ".", -1);
210 else if (p
== path
) {
211 Jim_SetResultString(interp
, "/", -1);
213 #if defined(__MINGW32__) || defined(_MSC_VER)
214 else if (p
[-1] == ':') {
216 Jim_SetResultString(interp
, path
, p
- path
+ 1);
220 Jim_SetResultString(interp
, path
, p
- path
);
225 static int file_cmd_rootname(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
227 const char *path
= Jim_String(argv
[0]);
228 const char *lastSlash
= strrchr(path
, '/');
229 const char *p
= strrchr(path
, '.');
231 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
> p
)) {
232 Jim_SetResult(interp
, argv
[0]);
235 Jim_SetResultString(interp
, path
, p
- path
);
240 static int file_cmd_extension(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
242 const char *path
= Jim_String(argv
[0]);
243 const char *lastSlash
= strrchr(path
, '/');
244 const char *p
= strrchr(path
, '.');
246 if (p
== NULL
|| (lastSlash
!= NULL
&& lastSlash
>= p
)) {
249 Jim_SetResultString(interp
, p
, -1);
253 static int file_cmd_tail(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
255 const char *path
= Jim_String(argv
[0]);
256 const char *lastSlash
= strrchr(path
, '/');
259 Jim_SetResultString(interp
, lastSlash
+ 1, -1);
262 Jim_SetResult(interp
, argv
[0]);
267 static int file_cmd_normalize(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
270 const char *path
= Jim_String(argv
[0]);
271 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
273 if (realpath(path
, newname
)) {
274 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, -1));
279 Jim_SetResultFormatted(interp
, "can't normalize \"%#s\": %s", argv
[0], strerror(errno
));
283 Jim_SetResultString(interp
, "Not implemented", -1);
288 static int file_cmd_join(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
291 char *newname
= Jim_Alloc(MAXPATHLEN
+ 1);
292 char *last
= newname
;
296 /* Simple implementation for now */
297 for (i
= 0; i
< argc
; i
++) {
299 const char *part
= Jim_GetString(argv
[i
], &len
);
302 /* Absolute component, so go back to the start */
305 #if defined(__MINGW32__) || defined(_MSC_VER)
306 else if (strchr(part
, ':')) {
307 /* Absolute compontent on mingw, so go back to the start */
311 else if (part
[0] == '.') {
312 if (part
[1] == '/') {
316 else if (part
[1] == 0 && last
!= newname
) {
317 /* Adding '.' to an existing path does nothing */
322 /* Add a slash if needed */
323 if (last
!= newname
&& last
[-1] != '/') {
328 if (last
+ len
- newname
>= MAXPATHLEN
) {
330 Jim_SetResultString(interp
, "Path too long", -1);
333 memcpy(last
, part
, len
);
337 /* Remove a slash if needed */
338 if (last
> newname
+ 1 && last
[-1] == '/') {
345 /* Probably need to handle some special cases ... */
347 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, newname
, last
- newname
));
352 static int file_access(Jim_Interp
*interp
, Jim_Obj
*filename
, int mode
)
354 Jim_SetResultBool(interp
, access(Jim_String(filename
), mode
) != -1);
359 static int file_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
361 return file_access(interp
, argv
[0], R_OK
);
364 static int file_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
366 return file_access(interp
, argv
[0], W_OK
);
369 static int file_cmd_executable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
372 return file_access(interp
, argv
[0], X_OK
);
374 /* If no X_OK, just assume true. */
375 Jim_SetResultBool(interp
, 1);
380 static int file_cmd_exists(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
382 return file_access(interp
, argv
[0], F_OK
);
385 static int file_cmd_delete(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
387 int force
= Jim_CompareStringImmediate(interp
, argv
[0], "-force");
389 if (force
|| Jim_CompareStringImmediate(interp
, argv
[0], "--")) {
395 const char *path
= Jim_String(argv
[0]);
397 if (unlink(path
) == -1 && errno
!= ENOENT
) {
398 if (rmdir(path
) == -1) {
399 /* Maybe try using the script helper */
400 if (!force
|| Jim_EvalPrefix(interp
, "file delete force", 1, argv
) != JIM_OK
) {
401 Jim_SetResultFormatted(interp
, "couldn't delete file \"%s\": %s", path
,
412 #ifdef HAVE_MKDIR_ONE_ARG
413 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
415 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
419 * Create directory, creating all intermediate paths if necessary.
421 * Returns 0 if OK or -1 on failure (and sets errno)
423 * Note: The path may be modified.
425 static int mkdir_all(char *path
)
429 /* First time just try to make the dir */
433 /* Must have failed the first time, so recursively make the parent and try again */
435 char *slash
= strrchr(path
, '/');
437 if (slash
&& slash
!= path
) {
439 if (mkdir_all(path
) != 0) {
446 if (MKDIR_DEFAULT(path
) == 0) {
449 if (errno
== ENOENT
) {
450 /* Create the parent and try again */
453 /* Maybe it already exists as a directory */
454 if (errno
== EEXIST
) {
457 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
469 static int file_cmd_mkdir(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
472 char *path
= Jim_StrDup(Jim_String(argv
[0]));
473 int rc
= mkdir_all(path
);
477 Jim_SetResultFormatted(interp
, "can't create directory \"%#s\": %s", argv
[0],
487 static int file_cmd_tempfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
491 const char *template = "/tmp/tcl.tmp.XXXXXX";
494 template = Jim_String(argv
[0]);
496 filename
= Jim_StrDup(template);
498 fd
= mkstemp(filename
);
500 Jim_SetResultString(interp
, "Failed to create tempfile", -1);
506 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, filename
, -1));
511 static int file_cmd_rename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
518 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-force")) {
526 source
= Jim_String(argv
[0]);
527 dest
= Jim_String(argv
[1]);
529 if (!force
&& access(dest
, F_OK
) == 0) {
530 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": target exists", argv
[0],
535 if (rename(source
, dest
) != 0) {
536 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
544 static int file_stat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
546 const char *path
= Jim_String(filename
);
548 if (stat(path
, sb
) == -1) {
549 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
556 static int file_lstat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
558 const char *path
= Jim_String(filename
);
560 if (lstat(path
, sb
) == -1) {
561 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
567 #define file_lstat file_stat
570 static int file_cmd_atime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
574 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
577 Jim_SetResultInt(interp
, sb
.st_atime
);
581 static int file_cmd_mtime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
588 struct timeval times
[2];
590 if (Jim_GetWide(interp
, argv
[1], &newtime
) != JIM_OK
) {
594 times
[1].tv_sec
= times
[0].tv_sec
= newtime
;
595 times
[1].tv_usec
= times
[0].tv_usec
= 0;
597 if (utimes(Jim_String(argv
[0]), times
) != 0) {
598 Jim_SetResultFormatted(interp
, "can't set time on \"%#s\": %s", argv
[0], strerror(errno
));
602 Jim_SetResultString(interp
, "Not implemented", -1);
606 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
609 Jim_SetResultInt(interp
, sb
.st_mtime
);
613 static int file_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
615 return Jim_EvalPrefix(interp
, "file copy", argc
, argv
);
618 static int file_cmd_size(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
622 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
625 Jim_SetResultInt(interp
, sb
.st_size
);
629 static int file_cmd_isdirectory(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
634 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
635 ret
= S_ISDIR(sb
.st_mode
);
637 Jim_SetResultInt(interp
, ret
);
641 static int file_cmd_isfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
646 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
647 ret
= S_ISREG(sb
.st_mode
);
649 Jim_SetResultInt(interp
, ret
);
654 static int file_cmd_owned(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
659 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
660 ret
= (geteuid() == sb
.st_uid
);
662 Jim_SetResultInt(interp
, ret
);
667 #if defined(HAVE_READLINK)
668 static int file_cmd_readlink(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
670 const char *path
= Jim_String(argv
[0]);
671 char *linkValue
= Jim_Alloc(MAXPATHLEN
+ 1);
673 int linkLength
= readlink(path
, linkValue
, MAXPATHLEN
);
675 if (linkLength
== -1) {
677 Jim_SetResultFormatted(interp
, "couldn't readlink \"%#s\": %s", argv
[0], strerror(errno
));
680 linkValue
[linkLength
] = 0;
681 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, linkValue
, linkLength
));
686 static int file_cmd_type(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
690 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
693 Jim_SetResultString(interp
, JimGetFileType((int)sb
.st_mode
), -1);
698 static int file_cmd_lstat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
702 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
705 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
708 #define file_cmd_lstat file_cmd_stat
711 static int file_cmd_stat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
715 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
718 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
721 static const jim_subcmd_type file_command_table
[] = {
727 /* Description: Last access time */
734 /* Description: Get or set last modification time */
737 "?-force? source dest",
741 /* Description: Copy source file to destination file */
748 /* Description: Directory part of the name */
755 /* Description: Name without any extension */
762 /* Description: Last extension including the dot */
769 /* Description: Last component of the name */
776 /* Description: Normalized path of name */
783 /* Description: Join multiple path components */
790 /* Description: Is file readable */
797 /* Description: Is file writable */
804 /* Description: Is file executable */
811 /* Description: Does file exist */
814 "?-force|--? name ...",
818 /* Description: Deletes the files or directories (must be empty unless -force) */
825 /* Description: Creates the directories */
833 /* Description: Creates a temporary filename */
837 "?-force? source dest",
841 /* Description: Renames a file */
843 #if defined(HAVE_READLINK)
849 /* Description: Value of the symbolic link */
857 /* Description: Size of file */
864 /* Description: Returns results of stat, and may store in var array */
871 /* Description: Returns results of lstat, and may store in var array */
878 /* Description: Returns type of the file */
886 /* Description: Returns 1 if owned by the current owner */
891 file_cmd_isdirectory
,
894 /* Description: Returns 1 if name is a directory */
901 /* Description: Returns 1 if name is a file */
908 static int Jim_CdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
913 Jim_WrongNumArgs(interp
, 1, argv
, "dirname");
917 path
= Jim_String(argv
[1]);
919 if (chdir(path
) != 0) {
920 Jim_SetResultFormatted(interp
, "couldn't change working directory to \"%s\": %s", path
,
927 static int Jim_PwdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
929 char *cwd
= Jim_Alloc(MAXPATHLEN
);
931 if (getcwd(cwd
, MAXPATHLEN
) == NULL
) {
932 Jim_SetResultString(interp
, "Failed to get pwd", -1);
936 #if defined(__MINGW32__) || defined(_MSC_VER)
938 /* Try to keep backlashes out of paths */
940 while ((p
= strchr(p
, '\\')) != NULL
) {
946 Jim_SetResultString(interp
, cwd
, -1);
952 int Jim_fileInit(Jim_Interp
*interp
)
954 if (Jim_PackageProvide(interp
, "file", "1.0", JIM_ERRMSG
))
957 Jim_CreateCommand(interp
, "file", Jim_SubCmdProc
, (void *)file_command_table
, NULL
);
958 Jim_CreateCommand(interp
, "pwd", Jim_PwdCmd
, NULL
, NULL
);
959 Jim_CreateCommand(interp
, "cd", Jim_CdCmd
, NULL
, NULL
);