From 32e3dccc892c7c960b8142390264f4c0ab489a0d Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Mon, 30 Jul 2012 01:48:28 -0500 Subject: Add dos2unix/unix2dos, remove old wrapper versions. --- toys/dos2unix.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ wrappers/dos2unix | 5 ---- wrappers/unix2dos | 5 ---- 3 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 toys/dos2unix.c delete mode 100755 wrappers/dos2unix delete mode 100755 wrappers/unix2dos diff --git a/toys/dos2unix.c b/toys/dos2unix.c new file mode 100644 index 00000000..01c90536 --- /dev/null +++ b/toys/dos2unix.c @@ -0,0 +1,70 @@ +/* vi: set sw=4 ts=4: + * + * dos2unix.c - convert newline format + * + * Copyright 2012 Rob Landley + * + * No standard + +USE_DOS2UNIX(NEWTOY(dos2unix, NULL, TOYFLAG_BIN)) +USE_DOS2UNIX(OLDTOY(unix2dos, dos2unix, NULL, TOYFLAG_BIN)) + +config DOS2UNIX + bool "dos2unix/unix2dos" + default y + help + usage: dos2unix/unix2dos [file...] + + Convert newline format between dos (\r\n) and unix (just \n) + If no files listed copy from stdin, "-" is a synonym for stdin. +*/ + +#include "toys.h" + +DEFINE_GLOBALS( + char *tempfile; +) + +#define TT this.dos2unix + +static void do_dos2unix(int fd, char *name) +{ + char c = toys.which->name[0]; + int outfd = 1, catch = 0; + + if (fd) outfd = copy_tempfile(fd, name, &TT.tempfile); + + for (;;) { + int len, in, out; + + len = read(fd, toybuf+(sizeof(toybuf)/2), sizeof(toybuf)/2); + if (len<0) { + perror_msg("%s",name); + toys.exitval = 1; + } + if (len<1) break; + + for (in = out = 0; in < len; in++) { + char x = toybuf[in+sizeof(toybuf)/2]; + + // Drop \r only if followed by \n in dos2unix mode + if (catch) { + if (c == 'u' || x != '\n') toybuf[out++] = '\r'; + catch = 0; + // Add \r only if \n not after \r in unix2dos mode + } else if (c == 'u' && x == '\n') toybuf[out++] = '\r'; + + if (x == '\r') catch++; + else toybuf[out++] = x; + } + xwrite(outfd, toybuf, out); + } + if (catch) xwrite(outfd, "\r", 1); + + if (fd) replace_tempfile(-1, outfd, &TT.tempfile); +} + +void dos2unix_main(void) +{ + loopfiles(toys.optargs, do_dos2unix); +} diff --git a/wrappers/dos2unix b/wrappers/dos2unix deleted file mode 100755 index 9eab6644..00000000 --- a/wrappers/dos2unix +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh -#HELP usage: dos2unix [FILE...]\n\nRemove DOS newlines - -[ $# -ne 0 ] && DASH_I=-i -sed $DASH_I -e 's/\r$//' "$@" diff --git a/wrappers/unix2dos b/wrappers/unix2dos deleted file mode 100755 index 68c18593..00000000 --- a/wrappers/unix2dos +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh -#HELP usage: unix2dos [FILE...]\n\nAdd DOS newlines - -[ $# -ne 0 ] && DASH_I=-i -sed $DASH_I -e 's/$/\r/' "$@" -- cgit v1.2.3