main.cs

来自「全功能c#编译器」· CS 代码 · 共 630 行 · 第 1/2 页

CS
630
字号
using System;
using System.IO;

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Tar;

/// <summary>
/// The tar class implements a simplistic version of the
/// traditional UNIX tar command. It currently supports
/// creating, listing, and extracting from archives. 
/// It supports GZIP, unix compress and bzip2 compression
/// GNU long filename extensions are supported, POSIX extensions are not yet supported...
/// See the help (-? or --help) for option details.
/// </summary>
public class Tar
{
	/// <summary>
	/// Flag that determines if debugging information is displayed.
	/// </summary>
	bool debug;
	
	/// <summary>
	/// Flag that determines if verbose feedback is provided.
	/// </summary>
	bool verbose;
	
	/// <summary>
	/// enum that determines compression in use
	/// </summary>
	enum Compression
	{
		None,
		Compress,
		Gzip,
		Bzip2
	}

	Compression compression = Compression.None;

	/// <summary>
	/// Operation to perform on archive
	/// </summary>
	enum Operation
	{
		List,
		Create,
		Extract
	}

	Operation operation = Operation.List;

	/// <summary>
	/// True if we are not to overwrite existing files.  (Unix noKlobber option)
	/// </summary>
	bool keepOldFiles;
	
	/// <summary>
	/// True if we are to convert ASCII text files from local line endings
	/// to the UNIX standard '\n'.
	/// </summary>
	bool asciiTranslate;
	
	/// <summary>
	/// The archive name provided on the command line, '-' if stdio.
	/// </summary>
	string archiveName;
	
	/// <summary>
	/// The blocking factor to use for the tar archive IO. Set by the '-b' option.
	/// </summary>
	int blockingFactor;
	
	/// <summary>
	/// The userId to use for files written to archives. Set by '-U' option.
	/// </summary>
	int userId;
	
	/// <summary>
	/// The userName to use for files written to archives. Set by '-u' option.
	/// </summary>
	string userName;
	
	/// <summary>
	/// The groupId to use for files written to archives. Set by '-G' option.
	/// </summary>
	int groupId;
	
	/// <summary>
	/// The groupName to use for files written to archives. Set by '-g' option.
	/// </summary>
	string groupName;
	
	/// <summary>
	/// The main entry point of the tar class.
	/// </summary>
	public static void Main(string[] argv)
	{
		Tar app = new Tar();
		app.InstanceMain(argv);
	}
	
	/// <summary>
	/// Establishes the default userName with the 'user.name' property.
	/// </summary>
	public Tar()
	{
		this.debug          = false;
		this.verbose        = false;
		this.archiveName    = null;
		this.keepOldFiles   = false;
		this.asciiTranslate = false;
		
		this.blockingFactor = TarBuffer.DefaultBlockFactor;
		this.userId   = 0;
		
		string sysUserName = Environment.UserName;
		this.userName = ((sysUserName == null) ? "" : sysUserName);
		
		this.groupId   = 0;
		this.groupName = "";
	}

	string[] GetFilesForSpec(string spec)
	{
		string dir = Path.GetDirectoryName(spec);
		if (dir == null || dir.Length == 0)
			dir = Directory.GetCurrentDirectory();

		return System.IO.Directory.GetFiles(dir, Path.GetFileName(spec));
	}

	/// <summary>
	/// This is the "real" main. The class main() instantiates a tar object
	/// for the application and then calls this method. Process the arguments
	/// and perform the requested operation.
	/// </summary>
	public void InstanceMain(string[] argv)
	{
		TarArchive archive = null;
		
		int argIdx = this.ProcessArguments(argv);

		if (this.archiveName != null && ! this.archiveName.Equals("-") && operation != Operation.Create) {
			if (File.Exists(this.archiveName) == false) {
				Console.Error.WriteLine("File does not exist " + this.archiveName);
				return;
			}
		}

		if (operation == Operation.Create) { 		               // WRITING
			Stream outStream = Console.OpenStandardOutput();
			
			if (this.archiveName != null && ! this.archiveName.Equals("-")) {
				outStream = File.Create(archiveName);
			}
			
			if (outStream != null) {
				switch (this.compression) {
					case Compression.Compress:
						outStream = new DeflaterOutputStream(outStream);
						break;

					case Compression.Gzip:
						outStream = new GZipOutputStream(outStream);
						break;

					case Compression.Bzip2:
						outStream = new BZip2OutputStream(outStream, 9);
					break;
				}
				archive = TarArchive.CreateOutputTarArchive(outStream, this.blockingFactor);
			}
		} else {								// EXTRACTING OR LISTING
			Stream inStream = Console.OpenStandardInput();
			
			if (this.archiveName != null && ! this.archiveName.Equals( "-" )) {
				inStream = File.OpenRead(archiveName);
			}
			
			if (inStream != null) {
				switch (this.compression) {
					case Compression.Compress:
						inStream = new InflaterInputStream(inStream);
						break;

					case Compression.Gzip:
						inStream = new GZipInputStream(inStream);
						break;
					
					case Compression.Bzip2:
						inStream = new BZip2InputStream(inStream);
						break;
				}
				archive = TarArchive.CreateInputTarArchive(inStream, this.blockingFactor);
			}
		}
		
		if (archive != null) {						// SET ARCHIVE OPTIONS
			archive.SetDebug(this.debug);
			archive.IsVerbose = this.verbose;
			
			archive.SetKeepOldFiles(this.keepOldFiles);
			archive.SetAsciiTranslation(this.asciiTranslate);
			
			archive.SetUserInfo(this.userId, this.userName, this.groupId, this.groupName);
		}
		
		if (archive == null) {
			Console.Error.WriteLine( "no processing due to errors" );
		} else if (operation == Operation.Create) {                        // WRITING
			if (verbose) {
				archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
			}

			for ( ; argIdx < argv.Length ; ++argIdx ) {
				string[] fileNames = GetFilesForSpec(argv[argIdx]);
				if (fileNames.Length > 0) {
					foreach (string name in fileNames) {
						TarEntry entry = TarEntry.CreateEntryFromFile(name);
						archive.WriteEntry(entry, true);
					}
				} else {
					Console.Error.Write("No files for " + argv[argIdx]);
				}
			}
		} else if (operation == Operation.List) {                   // LISTING
			archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
			archive.ListContents();
		} else {                                                    // EXTRACTING
			string userDir = Environment.CurrentDirectory;
			if (verbose) {
				archive.ProgressMessageEvent += new ProgressMessageHandler(ShowTarProgressMessage);
			}
			
			if (userDir != null) {
				archive.ExtractContents(userDir);
			}
		}

		if (archive != null) {                                   // CLOSE ARCHIVE
			archive.CloseArchive();
		}
	}
	
	///
	/// <summary>
	/// Process arguments, handling options, and return the index of the
	/// first non-option argument.
	/// </summary>
	/// <returns>
	/// The index of the first non-option argument.
	/// </returns>
	int ProcessArguments(string[] args)
	{
		int idx = 0;
		bool bailOut = false;
		bool gotOP = false;
		
		for ( ; idx < args.Length ; ++idx ) {
			string arg = args[ idx ];
			
			if (!arg.StartsWith("-")) {
				break;
			}
			
			if (arg.StartsWith("--" )) {
				int valuePos = arg.IndexOf('=');
				string argValue = null;
				
				if (valuePos >= 0) {
					argValue = arg.Substring(valuePos + 1);
					arg = arg.Substring(0, valuePos);
				}

				if (arg.Equals( "--help")) {
					this.ShowHelp();
					Environment.Exit(1);
				} else if (arg.Equals( "--version")) {
					this.Version();
					Environment.Exit(1);
				} else if (arg.Equals("--extract")) {
					gotOP = true;
					operation = Operation.Extract;
				} else if (arg.Equals("--list")) {
					gotOP = true;
					operation = Operation.List;
				} else if (arg.Equals("--create")) {
					gotOP = true;
					operation = Operation.Create;
				} else if (arg.Equals("--gzip")) {
					compression = Compression.Gzip;
				} else if (arg.Equals("--bzip2")) {
					compression = Compression.Bzip2;
				} else if (arg.Equals("--compress")) {
					compression = Compression.Compress;
				} else if (arg.Equals("--blocking-factor")) {
					if (argValue == null || argValue.Length == 0)
						Console.Error.WriteLine("expected numeric blocking factor");
					else {
						try {
							this.blockingFactor = Int32.Parse(argValue);
						} catch {
							Console.Error.WriteLine("invalid blocking factor");
						}
					}
				} else if (arg.Equals("--verbose")) {
					this.verbose = true;
				} else if (arg.Equals("--keep-old-files")) {
					this.keepOldFiles = true;
				} else if (arg.Equals("--record-size")) {
					if (argValue == null || argValue.Length == 0) {
						Console.Error.WriteLine("expected numeric record size");

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?