🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Thread View: news.software.nn
4 messages
4 total messages Started by Sami K|ykk{ Sun, 19 Sep 1993 22:09
Script to sort .newsrc similar as presentation sequence?
#4814
Author: Sami K|ykk{
Date: Sun, 19 Sep 1993 22:09
11 lines
1106 bytes
Is there some way to sort .newsrc so that groups are in same order as
in the presentation sequence defined in .nn/init file?

Every now and then I use other newsreaders and I would like to have
the groups in same order as in nn...

Thanks!

-- 
Sami K|ykk{			En tied{ miksi laulan, lintunen
samik@kaktus.uta.fi		  olenko iloinen vaiko suruinen
Re: Script to sort .newsrc similar as presentation sequence?
#4828
Author: Amos Shapir
Date: Wed, 22 Sep 1993 14:39
393 lines
11465 bytes
samik@uta.fi (Sami K|ykk{) writes:

>Is there some way to sort .newsrc so that groups are in same order as
>in the presentation sequence defined in .nn/init file?

I have been using the following program for a while -- so long in
fact, that I forget where I got it from...


		o /		o /		o /		o /
--Cut-here-------X---------------X---------------X---------------X----
		o \		o \		o \		o \

/* re-order the .newsrc according to my likes */

#include <stdio.h>
#include <strings.h>

/*
 * misc utility routines
 */

/* like malloc, except emalloc() will abort instead of returning NULL */
static char *emalloc(len)
int len;	/* number of bytes to allocate */
{
	char *malloc();
	char *new = malloc(len);

	if (!new) {
		fprintf(stderr, "Out of memory\n");
		exit(1);
	}

	return new;
}

/* return a copy of string str */
static char *stralloc(str)
char *str;	/* string to copy */
{
	return strcat(emalloc(strlen(str) + 1), str);
}

/* like strncmp, except the lengths of both strings are supplied */
static int mystrncmp(str1, str1len, str2, str2len)
char *str1;	/* first string */
int str1len;	/* str1 length */
char *str2;	/* second string */
int str2len;	/* str2 length */
{
	if (str1len < str2len) {
		int tmp = strncmp(str1, str2, str1len);

		if (tmp == 0)	/* longest prefix is equal */
			return -1;
		return tmp;

	} else if (str1len > str2len) {
		int tmp = strncmp(str1, str2, str2len);

		if (tmp == 0)	/* longest prefix is equal */
			return 1;
		return tmp;

	} /* else str1len == str2len */

	return strncmp(str1, str2, str1len);
}

/*
 * low level group list routines/data
 */

/* return the category index for category at grp and catlen characters long */
/* return -1 if category is not found */
static int catindex(grp, catlen)
char *grp;	/* group name string */
int catlen;	/* category name length */
{
	char **cat;				/* loop index */
	static char *categories[] = {		/* the category names */
		/* edit to taste and locale */

		/* most local to all but most global */
		"general",

		/* among the most global, */
		/* interesting/important to boring/worthless */
		"control",
		"local",
		"il",
		"comp",
		"gnu",
		"misc",
		"news",
		"alt",
		"sci",
		"soc",
		"talk",
		"rec",
		"clari",
		"usa-today",
		"trial",
		"bionet",
		"bit",
		"cs",
		"dcomp",
		"fa",
		"mail",
		"u3b",
		"unix-pc",
		"test",
		"junk",
	};
/* number of entries in categories[] */
#define NCATEGORIES	(sizeof categories / sizeof categories[0])

	for (cat = categories; cat < &categories[NCATEGORIES]; ++cat) {
		if (catlen == strlen(*cat) && strncmp(grp, *cat, catlen) == 0)
			return cat - categories;
	}
	return -1;
}

/* a group list element */
struct group {	/* a doubly-linked list for easy insertion */
	struct	group *next;	/* next struct group in list */
	struct	group *prev;	/* previous struct group in list */
	char	*group;		/* the original input line */
	int	catindex;	/* corresponding index into categories */
	int	categorylen;	/* length of category prefix */
	int	grouplen;	/* length of group prefix */
};

struct group *groups = NULL;	/* pointer to the head of the group list */
struct group *end_groups = NULL; /* pointer to the tail of the group list */

/* loop to iterate through the groups, indexed by cur */
#define FOREACH_GROUP(cur) for (cur = groups; cur; cur = cur->next)

#ifdef	DEBUG	/* for debugging */
/* print the data in a struct group */
static void groupprint(grp)
struct group *grp;		/* pointer to the group to print */
{
	printf("%x next %x prev %x cat %d catlen %d grplen %d %s", grp,
		grp->next, grp->prev, grp->catindex, grp->categorylen,
		grp->grouplen, grp->group);
}

/* print all groups */
static void groupallprint()
{
	struct group *grp;	/* loop index */

	FOREACH_GROUP(grp) groupprint(grp);
}
#endif	/* DEBUG */

/* return a struct group, initialized from line, abort if out of memory */
static struct group *groupalloc(line)
char *line;	/* the .newsrc line to "parse" */
{
	register struct group *new; /* pointer to the "parsed" .newsrc line */

	/* allocate/initialize a new group entry */

	new = (struct group *)emalloc(sizeof(struct group));
	new->group = stralloc(line);

	/* find group length (first [:!\n]) */
	new->grouplen = strcspn(line, ":!\n");

	/* find category length (first [.:!\n]) */
	new->categorylen = strcspn(line, ".:!\n");

	/* error checking */
	if ((new->catindex = catindex(line, new->categorylen)) < 0) {
		/* If this message comes out, edit the categories[] array */
		fprintf(stderr, "Unknown category: %.*s\n",
			new->categorylen, line);
	}

	new->next = NULL;
	new->prev = NULL;

	return new;
}

/* insert grp just before cur (at tail, if cur == NULL) */
static void groupinsert(grp, cur)
register struct group *grp; /* group to insert */
register struct group *cur; /* group to be just after grp, ow/ NULL */
{
	grp->next = cur;
	if (cur) {			/* insert just before cur */
		grp->prev = cur->prev;
		if (cur->prev)		/* grp is after cur->prev */
			cur->prev->next = grp;
		else			/* grp is now the first group */
			groups = grp;
		cur->prev = grp;

	} else {			/* insert at tail */
		grp->prev = end_groups;
		if (end_groups)
			end_groups->next = grp;
		else			/* group list was empty */
			groups = grp;	/* grp is now also the first group */
		end_groups = grp;
	}
}

/* return logical: "Is grp a *.tail group (or the group 'tail')?" */
static int grptailcmp(grp, tail)
struct group *grp;	/* the group to test */
char *tail;		/* the tail to test for (e.g. "general", "misc") */
{
	char *tmp = rindex(grp->group, '.');	/* pointer to tail of grp */
	int taillen = strlen(tail);		/* length of tail */

	if (tmp)	/* Is grp a *.tail group? */
		return grp->group + grp->grouplen == ++tmp + taillen
			&& strncmp(tmp, tail, taillen) == 0;
	else		/* Is grp the group "tail"? */
		return grp->grouplen == taillen
			&& strncmp(grp->group, tail, taillen) == 0;
}

/* like strcmp(), except for checking ordering of group heads (X.*) */
/* Does not know about categories, or *.general, *.misc, ... */
static int grpheadcmp(grp1, grp2)
struct group *grp1;	/* first group to compare */
struct group *grp2;	/* second group to compare */
{
	char *head1tail;	/* pointer to "tail" of grp1 */
	char *head2tail;	/* pointer to "tail" of grp2 */

#ifdef	KNOW_CATEGORIES
	if (grp1->catindex > grp2->catindex) {
		return 1;
	}
	if (grp1->catindex < grp2->catindex) {
		return -1;
	}
	/* hereafter: categories are equal */
#else	/* KNOW_CATEGORIES */
	/* assume categories are equal or don't matter */
#endif	/* KNOW_CATEGORIES */

	head1tail = rindex(grp1->group, '.');
	head2tail = rindex(grp2->group, '.');
	if (head1tail == head2tail)	/* grp1 is grp2 */
		return 0;
	if (!head1tail)			/* only grp1 has no head */
		return -1;
	if (!head2tail)			/* only grp2 has no head */
		return 1;

	/* finally, the implied comparison */
	return mystrncmp(grp1->group, head1tail - grp1->group,
		grp2->group, head2tail - grp2->group);
}

/*
 * high level group routines
 */

/* like strcmp(), except it compares "struct group"'s instead of strings */
static int grpcmp(grp1, grp2)
struct group *grp1;	/* first group to compare */
struct group *grp2;	/* second group to compare */
{
	/* optimization */
	/* . the categories are in a specified order */
	if (grp2->catindex > grp1->catindex)
		return -1;	/* grp1 is before grp2 */
	if (grp2->catindex < grp1->catindex)
		return 1;	/* grp1 is after grp2 */

	/* hereafter: grp2->catindex == grp1->catindex */

#ifdef	PREFIX_GOES_AFTER	/* e.g. comp.sources after comp.sources.bugs */
	/* . X is after all other X.* */
	if (grp1->grouplen < grp2->grouplen) {
		/* if grp1 is a prefix of grp2 ... */
		if (grp2->group[grp1->grouplen] == '.' &&
			strncmp(grp1->group, grp2->group, grp1->grouplen) == 0)
			return 1;

	/* . X is after all other X.* */
	} else if (grp1->grouplen > grp2->grouplen) {
		/* if grp2 is a prefix of grp1 ... */
		if (grp1->group[grp2->grouplen] == '.' &&
			strncmp(grp1->group, grp2->group, grp2->grouplen) == 0)
			return -1;
	}
#endif	/* PREFIX_GOES_AFTER */

	/* . X.general is before all other X* */
	if (grptailcmp(grp1, "general")) {
		if (grpheadcmp(grp1, grp2) == 0)
			return -1;	/* grp1 <= grp2 */

	/* . X.misc is after all other X* */
	} else if (grptailcmp(grp1, "misc")) {
		if (grpheadcmp(grp1, grp2) == 0)
			return 1;	/* grp1 >= grp2 */
	}

	/* . X.general is before all other X* */
	if (grptailcmp(grp2, "general")) {
		if (grpheadcmp(grp1, grp2) == 0)
			return 1;	/* grp1 >= grp2 */

	/* . X.misc is after all other X* */
	} else if (grptailcmp(grp2, "misc")) {
		if (grpheadcmp(grp1, grp2) == 0)
			return -1;	/* grp1 <= grp2 */
	}

	/* . other groups within one category are sorted as if by "sort" */
	return mystrncmp(grp1->group, grp1->grouplen,
		grp2->group, grp2->grouplen);
}

/* add line from .newsrc to group list at the proper place */
static void addgroup(line)
char *line;	/* .newsrc line to insert */
{
	struct group *new = groupalloc(line);	/* "parsed" version of line */
	struct group *cur;			/* search loop index */

	/* optimization, the list is usually "almost" already sorted */
	if (!end_groups || grpcmp(new, end_groups) > 0) {
		groupinsert(new, (struct group *)NULL);
		return;
	}

	/* find insertion point */
	FOREACH_GROUP(cur)
		if (grpcmp(new, cur) < 0) break;

	/* insert new just before cur (at tail, if cur == NULL) */
	groupinsert(new, cur);
}

/* Read a .newsrc from stdin.  Write a sorted .newsrc to stdout. */
main()
{
	struct group *cur;	/* loop index */
	static char line[512];	/* hopefully more than long enough */

	/* read in .newsrc, (bubble) sorting on the fly */
	while (fgets(line, sizeof line, stdin))
		addgroup(line);

	/* write .newsrc */
	FOREACH_GROUP(cur) printf("%s", cur->group);

	exit(0);
}

/*LINTLIBRARY*/
/*
 * Return the number of characters in the maximum leading segment
 * of string which consists solely of characters NOT from charset.
 */
int
strcspn(string, charset)
char	*string;
register char	*charset;
{
	register char *p, *q;

	for(q=string; *q != '\0'; ++q) {
		for(p=charset; *p != '\0' && *p != *q; ++p)
			;
		if(*p != '\0')
			break;
	}
	return(q-string);
}

		o /		o /		o /		o /
--Cut-here-------X---------------X---------------X---------------X----
		o \		o \		o \		o \
May the Source be with you, always...
--
	Amos Shapir		Net: amos@cs.huji.ac.il
Paper: The Hebrew Univ. of Jerusalem, Dept. of Comp. Science.
       Givat-Ram, Jerusalem 91904, Israel
Re: Script to sort .newsrc similar as presentation sequence?
#4837
Author: Alan Barrett
Date: Thu, 23 Sep 1993 14:53
288 lines
10507 bytes
In article <samik.748476449@uta.fi>,
samik@kaktus.uta.fi writes:
> Is there some way to sort .newsrc so that groups are in same order as
> in the presentation sequence defined in .nn/init file?

This is slow, and parses only a subset of the stuff that
can live in a .nn/init file, but it works for me.

--apb
Alan Barrett, Dept. of Electronic Eng., Univ. of Natal, Durban, South Africa
RFC822: barrett@ee.und.ac.za

#! /bin/sh
# This is a shell archive.  Remove anything before this line, then unpack
# it by saving it into a file and typing "sh file".  To overwrite existing
# files, type "sh file -c".  You can also feed this as standard input via
# unshar, or by typing "sh <file", e.g..  If this archive is complete, you
# will see the following message at the end:
#		"End of shell archive."
# Contents:  sort-newsrc
# Wrapped by barrett@lucy.ee.und.ac.za on Thu Sep 23 16:51:31 1993
PATH=/bin:/usr/bin:/usr/ucb ; export PATH
if test -f 'sort-newsrc' -a "${1}" != "-c" ; then 
  echo shar: Will not clobber existing file \"'sort-newsrc'\"
else
echo shar: Extracting \"'sort-newsrc'\" \(7895 characters\)
sed "s/^X//" >'sort-newsrc' <<'END_OF_FILE'
X#!/usr/bin/perl
X
X# Sort a .newsrc file, according to sequence information like that
X# used by nn.
X
X# A. P. Barrett <barrett@ee.und.ac.za>, December 1990.
X
X# Inputs:
X# 1.  The old .newsrc file.  Presented on stdin.
X# 2.  A .nn/init file, or reasonable facsimilie thereof.  Named
X#     as a command line argument, or defaulted to $HOME/.nn/init
X#     if that exists.
X#
X# Output:
X#     A new .newsrc file.  Sent to stdout.
X#
X# Action:
X# The .newsrc file is sorted according to the sequence information
X# in the .nn/init file.  This will not necessarily be identical to the
X# order used by nn, because we do not read the global nn/init file, and
X# we make no attempt to deal with non-vanilla features of nninit files
X# or newsrc files.
X#
X# Format of nninit file:
X# The format is actually more complicated; this script supports only the
X# following subset.
X# 1. '#' comments work as expected.
X# 2. Everything up to and including a line containing just the word
X#    'sequence' is ignored.
X# 3. Everything from the 'sequence' line to the end of the file defines
X#    the presentation sequence.
X# 4. A group or set of groups in included by listing its name.  'comp.unix'
X#    matches just one group; 'comp.unix.' matches all subgroups of comp.unix,
X#    but does not match the parent group; 'comp.unix*' matches both the
X#    parent and subgroups.  '.test' matcehs all groups whose name ends with
X#    .test.
X# 5. A group is excluded by placing a '!' before its name.
X# 6. A group is pushed to the start or end of the sequence by preceding it
X#    with a '<' or a '>'.
X# 7. A group that has been excluded may be reconsidered between a pair of
X#    '%' signs.  Thus, '! comp.misc comp. % comp.misc %' will force
X#    comp.misc to appear after all other comp groups.
X# 8. Nn allows several groups may be combined by separating them with commas
X#    instead of spaces.  This script treats commas in the same way as it
X#    treats spaces.
X# 9. Nn allows a group to have a save file and an entry sequence associated
X#    with it.  This script ignores such options.
X
X########################################################################
X
X@OLDNEWSRC = ();	# group names from old newscr file,
X			# in the order that they were read.
X			# (unused at present; when the RC flag in the nninit
X			# file is implemented, this array will probably be
X			# useful.)
X
X%INFO = ();		# information about each group.  This is the line
X			# from the newsrc file (apart from the group name
X			# itself).
X
X@SELECTED = ();		# group names for new newsrc file,
X			# in the order selected by the nninit file.
X
X@TAILEND = ();		# groups forced to end of sequence by '>' in nninit.
X
X%UNTOUCHED = ();	# groups not yet either selected or deselected
X			# by the nninit file.
X
X%DESELECTED = ();	# groups deselected by '!' in nninit.
X
X$debug = 0;		# debugging?
X
X$NNINIT = $ENV{"HOME"}."/.nn/init";	# default nninit file
X
X#
X# Process command line args.
X#
X# This is probably one of the stupidest command line parsers you
X# have seen for quite a while.
X#
X
Xwhile ($_ = shift (@ARGV)) {
X    if (/-v/) {
X	$debug++;
X    }
X    else {
X	$NNINIT = $_;
X    }
X}
X
X#
X# Read the .newsrc file from stdin.
X#
X
Xwhile (<>) {
X    # split into group name and other info
X    ($group,$info) = /(.*)([!:].*)/;
X    warn "read from newsrc: $group\n" if $debug >= 4;
X    # remember the info (subscribed or unsubscribed; what has been read)
X    $INFO{$group} = $info;
X    # remember the order that the groups appeared in the old newsrc
X    push (@OLDNEWSRC, $group);
X    # the group is still waiting to be selected
X    $UNTOUCHED{$group} = 1;
X}
X
X#
X# Open, slurp and close nninit file
X#
X
Xopen (NNINIT, $NNINIT) || die "cannot open nn init file: $NNINIT: $!\n";
Xundef $/;	# get ready to slurp
X$_ = <NNINIT>;	# slurp the file
Xclose (NNINIT);	# hope there is no error here
X
X#
X# Now process the nninit file.
X#
X
X    undef $lastword;		# previous word
X    $between_percents = 0;	# this is true inside a '% ... %' construct.
X
X    s/#[^\n]*//g;			# ignore comments
X    s/^(.*\n)*\s*sequence\s*\n//;	# ignore stuff before sequence line
X    s/\(([^\)]|\\.)*\)//g;		# ignore entry action inside parentheses
X					# (allow for \ escapes)
X    s/,/ /g;				# treat commas like spaces
X    s#\b[+/~]\S*##g;			# ignore save file names (words
X					# starting with +, / or ~)
X    s/!:\S+/!/;				# treat '!:stuff' like '!'
X    s/([!%<>])/ $1 /;			# put spaces around special chars
X					# to facilitate breaking into words
X    s/^\s+//; s/\s+$//;			# kill leading and trailing blanks
X
X    foreach $word (split (/\s+/,$_)) {	# process each word
X	warn "word from nninit: $word\n" if $debug > 3;
X
X	# '!', '<' and '>' must be followed by group name
X	if (($lastword =~ /[!<>]/) && ($word =~ /[%!<>]/)) {
X	    die "$NNINIT line $.: !, < or > must be followed by group name\n";
X	}
X
X	# '%' toggles state
X	elsif ($word eq '%') {
X	    $between_percents = ! $between_percents;
X	}
X
X	# '!', '<' and '>' just get remembered
X	elsif ($word =~ /[!<>]/) {
X	    # do nothing
X	}
X
X	# otherwise it must be a group name to be selected or deselected
X	else {
X	    @MATCHED = ();
X	    # check the untouched groups
X	    &find_matches (*UNTOUCHED, *MATCHED, $word);
X	    # if between percents, also check deselected groups
X	    &find_matches (*DESELECTED, *MATCHED, $word) if $between_percents;
X
X	    if ($#MATCHED < 0) {
X		warn "nothing matched: $word\n" if $debug;
X	    }
X	    # process the groups just matched
X	    elsif ($lastword eq '!') {
X		foreach $group (@MATCHED) {
X		    $DESELECTED{$group} = 1;
X		}
X		warn "deselect: ".join(" ",sort(@MATCHED))."\n" if $debug;
X	    }
X	    elsif ($lastword eq '<') {
X		unshift (@SELECTED, sort(@MATCHED));
X		warn "force to start: ".join(" ",sort(@MATCHED))."\n" if $debug;
X	    }
X	    elsif ($lastword eq '>') {
X		push (@TAILEND, sort(@MATCHED));
X		warn "force to end: ".join(" ",sort(@MATCHED))."\n" if $debug;
X	    }
X	    else {
X		push (@SELECTED, sort(@MATCHED));
X		warn "select: ".join(" ",sort(@MATCHED))."\n" if $debug;
X	    }
X	}
X
X	# remember the word just read
X	$lastword = $word;
X
X    } # process next word
X
X#
X# Now we can output the results.
X# As well as the selected groups (from the @SELECTED and
X# @TAILEND arrays), we also output deselected groups
X# and untouched groups
X#
Xwarn "SELECTED: ".join(" ",@SELECTED)."\n" if $debug >= 2;
Xwarn "TAILEND: ".join(" ",@TAILEND)."\n"
X			if ($debug >= 2 && $#TAILEND >= 0);
Xwarn "UNTOUCHED: ".join(" ",keys(%UNTOUCHED))."\n"
X			if ($debug >= 1 && $#UNTOUCHED >= 0);
Xwarn "DESELECTED: ".join(" ",keys(%DESELECTED))."\n"
X			if ($debug >= 1 && $#DESELECTED >= 0);
X
Xforeach $group (@SELECTED, @TAILEND, keys(%UNTOUCHED), keys(%DESELECTED)) {
X    print $group, $INFO{$group}, "\n";
X}
X
X#############
X
Xsub find_matches
X#
X# find all groups matching a pattern.  delete them from the input
X# associative array and push them onto the output array.
X# Returns number of matches.
X#
X{
X    local (*IN, *OUT, $pattern) = @_;
X    local ($count) = 0;
X
X    # if the pattern is not a wildcard, quickly do what is required.
X    if (($pattern !~ /^\./) && ($pattern !~ /[.*]$/)) {
X	if (delete $IN{$pattern}) {
X	    push (@OUT, $pattern);
X	    $count++;
X	    warn "matched: $pattern\n" if $debug >= 3;
X	}
X    }
X
X    # if the pattern is a wildcard, check each group for a match
X    else {
X	$pattern =~ s/(\W)/\\$1/g;	# quote all special chars in the pattern
X	$pattern = "^$pattern$";	# anchor the pattern
X	$pattern =~ s/\\\*/.*/g;	# '*' becomes '.*'
X	$pattern =~ s/\\\.\$$/\\./;	# '.' at end un-anchors pattern
X	$pattern =~ s/^\^\\\./\\./;	# '.' at start un-anchors pattern
X	$pattern =~ s/^\^\.\*//;	# '^.*' at start is useless
X	$pattern =~ s/\.\*\$$//;	# '.*$' at end is useless
X	warn "matching pattern: /$pattern/\n" if $debug >= 3;
X
X	foreach $group (keys (%IN)) {
X	    if ($group =~ /$pattern/) {
X		delete $IN{$group};
X		push (@OUT, $group);
X		$count++;
X		warn "matched: $group\n" if $debug >= 3;
X	    }
X	}
X    }
X
X    # return result
X    $count;
X}
END_OF_FILE
if test 7895 -ne `wc -c <'sort-newsrc'`; then
    echo shar: \"'sort-newsrc'\" unpacked with wrong size!
fi
chmod +x 'sort-newsrc'
# end of 'sort-newsrc'
fi
echo shar: End of shell archive.
exit 0
Re: Script to sort .newsrc similar as presentation sequence?
#4925
Author: Tom van Nes
Date: Tue, 05 Oct 1993 09:54
294 lines
9728 bytes
In article <27sd95$1qg@lucy.ee.und.ac.za>,
Alan Barrett <barrett@lucy.ee.und.ac.za> wrote:
>In article <samik.748476449@uta.fi>,
>samik@kaktus.uta.fi writes:
>> Is there some way to sort .newsrc so that groups are in same order as
>> in the presentation sequence defined in .nn/init file?
>
>This is slow, and parses only a subset of the stuff that
>can live in a .nn/init file, but it works for me.
>
>--apb
>Alan Barrett, Dept. of Electronic Eng., Univ. of Natal, Durban, South Africa
>RFC822: barrett@ee.und.ac.za
>

there is a solution in Perl which I quite like. It reads the file
'.news.favorites' and sorts the '.newsrc' accordingly. It has a few
features more:

---------cut fixnewsrc here----------
#!/usr/local/bin/perl

# FixNewsrc

# v1.5 by Chris Davis <ckd@eff.org>
#      and Dan Wallach <dwallach@soda.berkeley.edu>

# run "fixnewsrc -help" for documentation and usage notes,

# New features in 1.5
#
# generates ~/.nn/init 'sequence' list -- should probably read what's there
# and do something useful with it, but if you've gone to the trouble of
# making a complicated sequence list, you don't need this program :-)
#
# revamped output section to only leave a newsrc ".bak" file if the write
# succeeded on the new file
#
# Finally, Tom will be happy.  (Or, Tom may never be happy :-)
# --dwallach 1991 Aug 09

# New feature in 1.4
#
# cleaned up the eval in sub insert, it's now evaling the loop instead
# of being within it.  This optimizes (/pat/) perl patterns; it now runs in
# much less time on my sample .news.favorite (with a 2500+ group .newsrc!)
#
#old: 44.0u 15.9s 1:10.66 84.9% 0+1080k 5+15io 0pf+0w
#new: 12.4u  9.7s 0:27.94 79.7% 0+1012k 3+15io 0pf+0w
# --ckd 1991 Aug 09

# New features in 1.3
#
# Cleaned up some messages to print the true filename.
# added -s sortfile option (from Ed Vielmetti <emv@msen.com>)
# Fixed an array-slice masquerading as a scalar...
#
# --ckd 1991 Aug 08

# New features in 1.2:
#
# Uses getopts.pl to allow the following new feature (so the help parsing
#  also changed)
#
# has -f file to allow using something other than $HOME/.newsrc.
#  (good for those GNUS users using .newsrc-nntpserver style files)
# --ckd 1991 Jul 16

# New features in 1.1:
#
# handles arbitrary Perl patterns via eval (idea from Liam Quin's awk script)
# handles stranger and more obscure error cases (happy, Tom? :-)
# -- dwallach 1991 Jun 10

# Version 1.0, written sometime in June, 1991 -- dwallach

# counter return true if it actually printed anything
sub counter {
    return 0 unless ((++$counter % 100) == 0);
    $prev_blurt = 0;
    print STDERR "$counter...";
    1;
}

sub tally_counter {
    print STDERR "$counter",(defined $verbosity)?" total\n\n":"\n";
}

sub blurt {
    return unless $verbosity;
    print STDERR "\n" unless $prev_blurt;
    print STDERR @_;
    $prev_blurt = 1;
}

sub insert {
	local($group) = split(/[:!]/, $_[0], 2);
	if(!defined $newsrc{$group}) {
	    &blurt("Warning: $group not in $newsrc_file!\n")
		if !defined($inserted{$group});
	    next;
	}

	&blurt(">> $_\n");
	&counter;
	push (@output, $newsrc{$group});
	$inserted{$group} = 1;
	delete $newsrc{$group};
}

sub print_favorites {
    print STDERR "Parsing favorites: ";
    favorite: foreach(<FAVORITE>) {
	chop;
	s/\s*\#.*$//;
	next if /^$/;

	if(/\(/) {
	    &blurt("Matching: $_\n");
	    $pattern = $_;
	    eval <<END_OF_EVAL;
	    foreach (\@newsrc) {
		    if ($pattern) {
			&insert(\$_);
		    }
	    }
END_OF_EVAL
	    &blurt("Match complete\n");
	    next favorite;
	}
	&insert($_);
    }
    &tally_counter;
}

require 'getopts.pl';	# and unfortunately require 3.0.44 or later
&Getopts("h:s:f:vnc");	# help, sortlist (favorites), file, verbose, clean

if (@ARGV || $opt_h) {
    print STDERR <<NO_MORE_HELP;
fixnewsrc 1.5 by Chris Davis <ckd@eff.org>
              and Dan Wallach <dwallach@soda.berkeley.edu>
              and patches by Ed Vielmetti <emv@msen.com>
Usage: $0       [-n] [-v] [-f file] [-s favoritefile] [-c] [anything else]
    -v == more verbose
    -f == use file instead of .newsrc
    -s == sort by this file instead of .news.favorite
    -n == do surgery on nn's init file -- rewrites the sequence entry
    -c == clean your .newsrc (removes article numbers in unsub'ed groups
    anything else == this help message

This program sorts your .newsrc, putting groups you read on top.  In addition,
if you have a file in your home directory called .news.favorite, then the
list of newsgroups in this file appear at the top of your .newsrc, so you
can still read groups in your favorite order.

Put any Perl expression you want to describe your group in parenthesis, and
that's good, too.  If it's not in parenthesis, it's considered to be exact.
Remember: you're matching on :'s and !'s, too.

# Example:
rec.humor.funny                        # comments, and blank lines are cool
alt.fan.warlord
ucb.computing.announce
comp.lang.perl
(/comp\\.text\\..*/ && (!/comp\\.text\\.tex/))  # comp.text everything but tex
# Here's a more complicated one which matches "nas" and "nas.msgs"
# but not "nasa.nudge" or "arc.nasamail.arc"
(/^nas\\..*/ || /^nas[:!]/)
NO_MORE_HELP
    exit 0;
}

$verbosity = $opt_v;
$newsrc_file = $opt_f || "$ENV{HOME}/.newsrc";
$favorite_file = $opt_s || "$ENV{HOME}/.news.favorite";
$do_nn = $opt_n;

die "No .newsrc file!  Crapped out at" unless -e "$newsrc_file";
open(NEWSRC, "<$newsrc_file") ||
    die "Can't open $newsrc_file: $!, crapped out at";

# we want to keep this associative array around for printing favorites
# so if we've already printed something, we just delete it from the
# associative array, and go on.

print STDERR "Reading groups: ";
$counter = 0;
foreach(<NEWSRC>) {
    chop;
    next if /^$/;
    &counter;
    $fullentry = $_;
    s/[:!].*$//;
    &blurt("Warning: $_ appears more than once!\n") if defined($newsrc{$_});
    $fullentry =~ s/!.*$/!/ if $opt_c;
    $newsrc{$_} = $fullentry;
}
&tally_counter;

print STDERR "Sorting..." if $verbosity;
@newsrc = sort values %newsrc;
print STDERR "Done\n" if $verbosity;
# output time... clear the counter and let's deal with the favorites file
$counter = 0;

if (open(FAVORITE, $favorite_file)) {
    &print_favorites;
} else {
    print STDERR "Couldn't find $favorite_file.  Just sorting $newsrc_file.\n";
}

# yeah, we have to do it twice... It's good enough...
undef @newsrc;
print STDERR "Sorting again..." if $verbosity;
@newsrc = sort values %newsrc;
print STDERR "Done\n" if $verbosity;
print STDERR "Generating output: ";

#
# I could just grep through the array for :'s then !'s, but that requires
# making two passes.  This works in one pass.
#
foreach(@newsrc) {
    &counter;
    if(/:/) {
	push (@output, $_);
    } elsif (/!/) {
	push (@output2, $_);
    }
}
&tally_counter;

close(NEWSRC);   # we're done with using NEWSRC for input.  Output time...

open(NEWSRC_TMP, "> ${newsrc_file}$$") || die "Can't open temporary .newsrc for writing: $!, crapped out at";

$\ = $, = "\n";
print NEWSRC_TMP @output, @output2;
close(NEWSRC_TMP) || die "Can't write new $newsrc_file: $!, crapped out at";

rename("$newsrc_file", "${newsrc_file}.bak") ||
    die "Can't rename $newsrc_file: $!, crapped out at";

rename("${newsrc_file}$$", "$newsrc_file") ||
    die "Can't rename $newsrc_file: $!, crapped out at";

# now, let's go fix the nn init file!
exit 0 unless (-d "$ENV{HOME}/.nn" && defined($do_nn));

printf STDERR "Fixing ~/.nn/init...";
open(NN_INIT,"> $ENV{HOME}/.nn/init.$$") || 
    die "Can't open temporary nn init file: $!, crapped out at";

# first, we need to read in the old init file, up to where it references
# the sequence...

if(-r "$ENV{HOME}/.nn/init") {
    open(NN_INIT_ORIG, "$ENV{HOME}/.nn/init") ||
	die("Can't open original nn init file: $!, crapped out at");
    while(<NN_INIT_ORIG>) {
	last if /sequence/;
	last if /# DON'T DELETE THIS LINE!  fixnewsrc DEPENDS ON IT./;
	chop;
	print NN_INIT;
    }
    close(NN_INIT_ORIG);   # don't need that any more...
}

printf NN_INIT "%s", <<NN_HEADER_END;
# DON'T DELETE THIS LINE!  fixnewsrc DEPENDS ON IT.
# the following was automatically generated by FixNewsrc...
#
sequence

NN_HEADER_END

foreach (@output) {
    s/:.*$//;
    next if /!/;
    print NN_INIT;
}
printf STDERR "Done.\n";
close(NN_INIT) || die "Can't write new nn init: $!, crapped out at";

if(-e "$ENV{HOME}/.nn/init") {
    rename("$ENV{HOME}/.nn/init", "$ENV{HOME}/.nn/init.bak") ||
	die "Can't rename nn init: $!, crapped out at";
}

rename("$ENV{HOME}/.nn/init.$$", "$ENV{HOME}/.nn/init") ||
    die "Can't rename nn init: $!, crapped out at";

------------------cut here -------------
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads