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
, int 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 const char *path
= Jim_String(filename
);
355 int rc
= access(path
, mode
);
357 Jim_SetResultBool(interp
, rc
!= -1);
362 static int file_cmd_readable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
364 return file_access(interp
, argv
[0], R_OK
);
367 static int file_cmd_writable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
369 return file_access(interp
, argv
[0], W_OK
);
372 static int file_cmd_executable(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
375 return file_access(interp
, argv
[0], X_OK
);
377 /* XXX: X_OK doesn't work under Windows.
378 * In any case, may need to add .exe, etc. so just lie!
380 Jim_SetResultBool(interp
, 1);
385 static int file_cmd_exists(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
387 return file_access(interp
, argv
[0], F_OK
);
390 static int file_cmd_delete(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
392 int force
= Jim_CompareStringImmediate(interp
, argv
[0], "-force");
394 if (force
|| Jim_CompareStringImmediate(interp
, argv
[0], "--")) {
400 const char *path
= Jim_String(argv
[0]);
402 if (unlink(path
) == -1 && errno
!= ENOENT
) {
403 if (rmdir(path
) == -1) {
404 /* Maybe try using the script helper */
405 if (!force
|| Jim_EvalPrefix(interp
, "file delete force", 1, argv
) != JIM_OK
) {
406 Jim_SetResultFormatted(interp
, "couldn't delete file \"%s\": %s", path
,
417 #ifdef HAVE_MKDIR_ONE_ARG
418 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME)
420 #define MKDIR_DEFAULT(PATHNAME) mkdir(PATHNAME, 0755)
424 * Create directory, creating all intermediate paths if necessary.
426 * Returns 0 if OK or -1 on failure (and sets errno)
428 * Note: The path may be modified.
430 static int mkdir_all(char *path
)
434 /* First time just try to make the dir */
438 /* Must have failed the first time, so recursively make the parent and try again */
440 char *slash
= strrchr(path
, '/');
442 if (slash
&& slash
!= path
) {
444 if (mkdir_all(path
) != 0) {
451 if (MKDIR_DEFAULT(path
) == 0) {
454 if (errno
== ENOENT
) {
455 /* Create the parent and try again */
458 /* Maybe it already exists as a directory */
459 if (errno
== EEXIST
) {
462 if (stat(path
, &sb
) == 0 && S_ISDIR(sb
.st_mode
)) {
474 static int file_cmd_mkdir(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
477 char *path
= Jim_StrDup(Jim_String(argv
[0]));
478 int rc
= mkdir_all(path
);
482 Jim_SetResultFormatted(interp
, "can't create directory \"%#s\": %s", argv
[0],
492 static int file_cmd_tempfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
496 const char *template = "/tmp/tcl.tmp.XXXXXX";
499 template = Jim_String(argv
[0]);
501 filename
= Jim_StrDup(template);
503 fd
= mkstemp(filename
);
505 Jim_SetResultString(interp
, "Failed to create tempfile", -1);
510 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, filename
, -1));
515 static int file_cmd_rename(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
522 if (!Jim_CompareStringImmediate(interp
, argv
[0], "-force")) {
530 source
= Jim_String(argv
[0]);
531 dest
= Jim_String(argv
[1]);
533 if (!force
&& access(dest
, F_OK
) == 0) {
534 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": target exists", argv
[0],
539 if (rename(source
, dest
) != 0) {
540 Jim_SetResultFormatted(interp
, "error renaming \"%#s\" to \"%#s\": %s", argv
[0], argv
[1],
548 static int file_stat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
550 const char *path
= Jim_String(filename
);
552 if (stat(path
, sb
) == -1) {
553 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
560 static int file_lstat(Jim_Interp
*interp
, Jim_Obj
*filename
, struct stat
*sb
)
562 const char *path
= Jim_String(filename
);
564 if (lstat(path
, sb
) == -1) {
565 Jim_SetResultFormatted(interp
, "could not read \"%#s\": %s", filename
, strerror(errno
));
571 #define file_lstat file_stat
574 static int file_cmd_atime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
578 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
581 Jim_SetResultInt(interp
, sb
.st_atime
);
585 static int file_cmd_mtime(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
592 struct timeval times
[2];
594 if (Jim_GetWide(interp
, argv
[1], &newtime
) != JIM_OK
) {
598 times
[1].tv_sec
= times
[0].tv_sec
= newtime
;
599 times
[1].tv_usec
= times
[0].tv_usec
= 0;
601 if (utimes(Jim_String(argv
[0]), times
) != 0) {
602 Jim_SetResultFormatted(interp
, "can't set time on \"%#s\": %s", argv
[0], strerror(errno
));
606 Jim_SetResultString(interp
, "Not implemented", -1);
610 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
613 Jim_SetResultInt(interp
, sb
.st_mtime
);
617 static int file_cmd_copy(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
619 return Jim_EvalPrefix(interp
, "file copy", argc
, argv
);
622 static int file_cmd_size(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
626 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
629 Jim_SetResultInt(interp
, sb
.st_size
);
633 static int file_cmd_isdirectory(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
638 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
639 ret
= S_ISDIR(sb
.st_mode
);
641 Jim_SetResultInt(interp
, ret
);
645 static int file_cmd_isfile(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
650 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
651 ret
= S_ISREG(sb
.st_mode
);
653 Jim_SetResultInt(interp
, ret
);
658 static int file_cmd_owned(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
663 if (file_stat(interp
, argv
[0], &sb
) == JIM_OK
) {
664 ret
= (geteuid() == sb
.st_uid
);
666 Jim_SetResultInt(interp
, ret
);
671 #if defined(HAVE_READLINK)
672 static int file_cmd_readlink(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
674 const char *path
= Jim_String(argv
[0]);
675 char *linkValue
= Jim_Alloc(MAXPATHLEN
+ 1);
677 int linkLength
= readlink(path
, linkValue
, MAXPATHLEN
);
679 if (linkLength
== -1) {
681 Jim_SetResultFormatted(interp
, "couldn't readlink \"%#s\": %s", argv
[0], strerror(errno
));
684 linkValue
[linkLength
] = 0;
685 Jim_SetResult(interp
, Jim_NewStringObjNoAlloc(interp
, linkValue
, linkLength
));
690 static int file_cmd_type(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
694 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
697 Jim_SetResultString(interp
, JimGetFileType((int)sb
.st_mode
), -1);
702 static int file_cmd_lstat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
706 if (file_lstat(interp
, argv
[0], &sb
) != JIM_OK
) {
709 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
712 #define file_cmd_lstat file_cmd_stat
715 static int file_cmd_stat(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
719 if (file_stat(interp
, argv
[0], &sb
) != JIM_OK
) {
722 return StoreStatData(interp
, argc
== 2 ? argv
[1] : NULL
, &sb
);
725 static const jim_subcmd_type file_command_table
[] = {
731 /* Description: Last access time */
738 /* Description: Get or set last modification time */
741 "?-force? source dest",
745 /* Description: Copy source file to destination file */
752 /* Description: Directory part of the name */
759 /* Description: Name without any extension */
766 /* Description: Last extension including the dot */
773 /* Description: Last component of the name */
780 /* Description: Normalized path of name */
787 /* Description: Join multiple path components */
794 /* Description: Is file readable */
801 /* Description: Is file writable */
808 /* Description: Is file executable */
815 /* Description: Does file exist */
818 "?-force|--? name ...",
822 /* Description: Deletes the files or directories (must be empty unless -force) */
829 /* Description: Creates the directories */
837 /* Description: Creates a temporary filename */
841 "?-force? source dest",
845 /* Description: Renames a file */
847 #if defined(HAVE_READLINK)
853 /* Description: Value of the symbolic link */
861 /* Description: Size of file */
868 /* Description: Returns results of stat, and may store in var array */
875 /* Description: Returns results of lstat, and may store in var array */
882 /* Description: Returns type of the file */
890 /* Description: Returns 1 if owned by the current owner */
895 file_cmd_isdirectory
,
898 /* Description: Returns 1 if name is a directory */
905 /* Description: Returns 1 if name is a file */
912 static int Jim_CdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
917 Jim_WrongNumArgs(interp
, 1, argv
, "dirname");
921 path
= Jim_String(argv
[1]);
923 if (chdir(path
) != 0) {
924 Jim_SetResultFormatted(interp
, "couldn't change working directory to \"%s\": %s", path
,
931 static int Jim_PwdCmd(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
933 const int cwd_len
= 2048;
934 char *cwd
= malloc(cwd_len
);
936 if (getcwd(cwd
, cwd_len
) == NULL
) {
937 Jim_SetResultString(interp
, "Failed to get pwd", -1);
940 #if defined(__MINGW32__) || defined(_MSC_VER)
942 /* Try to keep backlashes out of paths */
944 while ((p
= strchr(p
, '\\')) != NULL
) {
950 Jim_SetResultString(interp
, cwd
, -1);
956 int Jim_fileInit(Jim_Interp
*interp
)
958 if (Jim_PackageProvide(interp
, "file", "1.0", JIM_ERRMSG
))
961 Jim_CreateCommand(interp
, "file", Jim_SubCmdProc
, (void *)file_command_table
, NULL
);
962 Jim_CreateCommand(interp
, "pwd", Jim_PwdCmd
, NULL
, NULL
);
963 Jim_CreateCommand(interp
, "cd", Jim_CdCmd
, NULL
, NULL
);