Esempio n. 1
0
func prettyPaste(id string, limit int) (code []string, err os.Error) {
	source, err := io.ReadFile("pastes" + path.Clean("/"+id))
	if err != nil {
		return
	}

	multi := strings.Split(string(source), "\n---", 0)

	allCode := make([]string, len(multi))
	results := make(chan int)
	for i := 0; i < len(multi); i++ {
		go func(i int) {
			allCode[i], _ = prettySource(id, multi[i], limit)
			results <- i
		}(i)
	}

	for i := 0; i < len(multi); i++ {
		<-results
	}

	code = allCode

	return
}
Esempio n. 2
0
func readinfofile(name string) ([]zonetime, bool) {
	buf, err := io.ReadFile(name)
	if err != nil {
		return nil, false
	}
	return parseinfo(buf)
}
Esempio n. 3
0
func ReadConfig() *Config {
	content, err := io.ReadFile(configFilename)
	if err != nil {
		log.Exitf("Can't open config file: %s\n", err)
	}
	return ParseConfig(string(content))
}
Esempio n. 4
0
func Parse(filename string) (*parser, os.Error) {
	var p parser
	input, err := io.ReadFile(filename)
	p.init(filename, input)
	p.Parse()
	return &p, err
}
Esempio n. 5
0
func TestWriter(t *testing.T) {
testLoop:
	for i, test := range writerTests {
		expected, err := io.ReadFile(test.file)
		if err != nil {
			t.Errorf("test %d: Unexpected error: %v", i, err)
			continue
		}

		buf := new(bytes.Buffer)
		tw := NewWriter(iotest.TruncateWriter(buf, 4<<10)) // only catch the first 4 KB
		for j, entry := range test.entries {
			if err := tw.WriteHeader(entry.header); err != nil {
				t.Errorf("test %d, entry %d: Failed writing header: %v", i, j, err)
				continue testLoop
			}
			if _, err := io.WriteString(tw, entry.contents); err != nil {
				t.Errorf("test %d, entry %d: Failed writing contents: %v", i, j, err)
				continue testLoop
			}
		}
		if err := tw.Close(); err != nil {
			t.Errorf("test %d: Failed closing archive: %v", err)
			continue testLoop
		}

		actual := buf.Bytes()
		if !bytes.Equal(expected, actual) {
			t.Errorf("test %d: Incorrect result: (-=expected, +=actual)\n%v",
				i, bytediff(expected, actual))
		}
	}
}
Esempio n. 6
0
func main() {
	flag.Parse()

	var filename string
	switch flag.NArg() {
	case 0:
		filename = "/dev/stdin"
	case 1:
		filename = flag.Arg(0)
	default:
		usage()
	}

	src, err := io.ReadFile(filename)
	if err != nil {
		scanner.PrintError(os.Stderr, err)
	}

	if path.Ext(filename) == ".html" {
		src = extractEBNF(src)
	}

	grammar, err := ebnf.Parse(filename, src)
	if err != nil {
		scanner.PrintError(os.Stderr, err)
	}

	if err = ebnf.Verify(grammar, *start); err != nil {
		scanner.PrintError(os.Stderr, err)
	}
}
Esempio n. 7
0
// ReadAll lee el archivo .ini especificado en la estructura.
// Crea un mapa de mapas representando la estructura del archivo,
// separando secciones y elementos dentro de la seccion y lo almacena
// en la variable Seccion de la estructura InitFile.
func (iF *InitFile) ReadAll() (error os.Error) {
	micontenido := make(contenido)
	miseccion := "default"
	if mifichero, error := io.ReadFile(iF.nombre); error != nil {
		return error
	} else {
		cadena := string(mifichero)
		lineas := strings.Split(cadena, "\n", 0)
		for _, linea := range lineas {
			expresion := strings.TrimSpace(linea)
			if len(expresion) == 0 {
				continue
			}
			if expresion[0] == comentario {
				continue
			}
			if expresion[0] == corchete && expresion[len(expresion)-1] == cierracorchete {
				iF.Seccion[miseccion] = micontenido
				miseccion = string(expresion[1 : len(expresion)-1])
				micontenido = make(contenido)
				continue
			}
			valores := strings.Split(expresion, "=", 2)
			if len(valores) != 2 {
				continue
			}
			micontenido[valores[0]] = valores[1]
		}
	}
	if _, ok := iF.Seccion[miseccion]; !ok {
		iF.Seccion[miseccion] = micontenido
	}
	return nil
}
Esempio n. 8
0
// If src != nil, readSource converts src to a []byte if possible;
// otherwise it returns an error. If src == nil, readSource returns
// the result of reading the file specified by filename.
//
func readSource(filename string, src interface{}) ([]byte, os.Error) {
	if src != nil {
		switch s := src.(type) {
		case string:
			return strings.Bytes(s), nil
		case []byte:
			return s, nil
		case *bytes.Buffer:
			// is io.Reader, but src is already available in []byte form
			if s != nil {
				return s.Bytes(), nil
			}
		case io.Reader:
			var buf bytes.Buffer
			_, err := io.Copy(&buf, s)
			if err != nil {
				return nil, err
			}
			return buf.Bytes(), nil
		default:
			return nil, os.ErrorString("invalid source")
		}
	}

	return io.ReadFile(filename)
}
Esempio n. 9
0
func banana(c *http.Conn, req *http.Request) {
	contents, err := io.ReadFile("index.html")
	if err != nil {
		panic("ListenAndServe: ", err.String())
	}
	io.WriteString(c, string(contents))
}
Esempio n. 10
0
func TestFiles(t *testing.T) {
	for _, filename := range files {
		src, err := io.ReadFile(filename)
		if err != nil {
			t.Fatal(err)
		}
		check(t, filename, src)
	}
}
Esempio n. 11
0
File: views.go Progetto: tung/goblog
func loadTemplate(path string) (t *template.Template, err os.Error) {
	if buf, readErr := io.ReadFile("templates/" + path); readErr == nil {
		t = template.MustParse(string(buf), template.FormatterMap{
			"html": template.HTMLFormatter
		});
	} else {
		err = readErr
	}
	return;
}
Esempio n. 12
0
func main() {
	maths, err := io.ReadFile("math.peg")
	if err != nil {
		log.Exit("Error: ", err)
	}

	fmt.Println(maths)
	rune, size := utf8.DecodeRuneInString(string(maths))
	fmt.Println(rune, size)
	return
}
Esempio n. 13
0
File: godoc.go Progetto: 8l/go-learn
func readTemplate(name string) *template.Template {
	path := pathutil.Join(*tmplroot, name)
	data, err := io.ReadFile(path)
	if err != nil {
		log.Exitf("ReadFile %s: %v", path, err)
	}
	t, err := template.Parse(string(data), fmap)
	if err != nil {
		log.Exitf("%s: %v", name, err)
	}
	return t
}
Esempio n. 14
0
func serveTextFile(c *http.Conn, r *http.Request, path string) {
	src, err := io.ReadFile(path)
	if err != nil {
		log.Stderrf("serveTextFile: %s", err)
	}

	var buf bytes.Buffer
	fmt.Fprintln(&buf, "<pre>")
	template.HTMLEscape(&buf, src)
	fmt.Fprintln(&buf, "</pre>")

	servePage(c, "Text file "+path, "", buf.Bytes())
}
Esempio n. 15
0
// TODO: malicious ids
func (ps *PersistService) Get(id string) (*Model, bool) {
	log.Stderrf("PS:GET:%s", id);
	mpath := path.Join(ps.Path, id);
	log.Stderrf("PS:GET:path:%s", mpath);
	bs, e := io.ReadFile(mpath);
	// TODO: check error more specifically (not found, etc.)
	if e != nil {
		log.Stderrf("PS:GET:e:%s", e);
		return nil, false;
	}
	else {
		return parse_model(id, bs), true;
	}
	panic("unreachable");
}
Esempio n. 16
0
func main() {
	// パラメータをチェック
	if len(os.Args) <= 1 {
		fmt.Println("ファイルを指定してください")
		return
	}

	// ファイルを読み込み
	data, err := io.ReadFile(os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}

	// 出力
	fmt.Println(data)
}
Esempio n. 17
0
func main() {
	bytes, err := io.ReadFile("/dev/stdin")
	if err != nil {
		fmt.Fprintf(os.Stderr, "can't read input: %s\n", err)
		os.Exit(2)
	}
	ilen := len(bytes)
	// Delete the comment lines and newlines
	bytes = regexp.MustCompile("(>[^\n]+)?\n").ReplaceAll(bytes, []byte{})
	clen := len(bytes)
	for _, s := range variants {
		fmt.Printf("%s %d\n", s, countMatches(s, bytes))
	}
	for _, sub := range substs {
		bytes = regexp.MustCompile(sub.pat).ReplaceAll(bytes, strings.Bytes(sub.repl))
	}
	fmt.Printf("\n%d\n%d\n%d\n", ilen, clen, len(bytes))
}
Esempio n. 18
0
func serveHTMLDoc(c *http.Conn, r *http.Request, path string) {
	// get HTML body contents
	src, err := io.ReadFile(path)
	if err != nil {
		log.Stderrf("%v", err)
		http.NotFound(c, r)
		return
	}

	// if it's the language spec, add tags to EBNF productions
	if strings.HasSuffix(path, "go_spec.html") {
		var buf bytes.Buffer
		linkify(&buf, src)
		src = buf.Bytes()
	}

	title := commentText(src)
	servePage(c, title, "", src)
}
Esempio n. 19
0
// ParsePkgFile parses the file specified by filename and returns the
// corresponding AST. If the file cannot be read, has syntax errors, or
// does not belong to the package (i.e., pkgname != "" and the package
// name in the file doesn't match pkkname), an error is returned. Mode
// flags that control the amount of source text parsed are ignored.
//
func ParsePkgFile(pkgname, filename string, mode uint) (*ast.File, os.Error) {
	src, err := io.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	if pkgname != "" {
		prog, err := ParseFile(filename, src, PackageClauseOnly)
		if err != nil {
			return nil, err
		}
		if prog.Name.Value != pkgname {
			return nil, os.NewError(fmt.Sprintf("multiple packages found: %s, %s", prog.Name.Value, pkgname))
		}
	}

	// ignore flags that control partial parsing
	return ParseFile(filename, src, mode&^(PackageClauseOnly|ImportsOnly))
}
Esempio n. 20
0
func main() {
	// Read file into []byte
	bytes, err := io.ReadFile("math.peg")
	if err != nil {
		log.Exit("Error :")
	}

	// Convert []byte into []rune
	bmax := len(bytes)
	rmax := utf8.RuneCount(bytes) // # runes
	runes := make([]rune, rmax)
	for bi, ri := 0, 0; ri < rmax; ri++ {
		r, size := utf8.DecodeRune(bytes[bi:bmax])
		bi += size          // Advance in bytestream
		runes[ri] = rune(r) // Add rune
	}

	fmt.Println(runes)
}
Esempio n. 21
0
func main( )
{
	listener, err := net.Listen("tcp", "192.168.148.128:80" );

	if ( listener == nil )
	{
		fmt.Printf( "%s\n", err.String( ) );
	}

	conn, err := listener.Accept( );

	if ( conn == nil )
	{
		fmt.Printf( "%s\n", err.String( ) );
	}

	var data [1024]byte;
	conn.Read( &data );
        stringData := bytes.NewBuffer( &data ).String( );
        fmt.Printf( "%s", stringData );

	urls := strings.Split( stringData, " ", 0 );
	fmt.Printf( "%s\n", urls[ 1 ] );

	requestedFile, err := io.ReadFile( "." + urls[ 1 ] );

	var sendData *bytes.Buffer = new( bytes.Buffer );	
	sendData.WriteString( "HTTP/1.1 200 OK\r\n" );
	sendData.WriteString( "Date: Mon, 23 May 2009 22:38:34 GMT\r\n" );
	sendData.WriteString( "Accept-Ranges: bytes\r\n" );
	sendData.WriteString( "Content-Type: text/html; charset=UTF-8\r\n" );
	sendData.WriteString( "Connection: close\n" );
	sendData.WriteString( "Content-Length: 1100\r\n\r\n" );
	sendData.WriteString( bytes.NewBuffer( requestedFile ).String( ) );

	//sendData.WriteString( "Hello World" );
	
	conn.Write( sendData.Bytes( ) );

	fmt.Printf( "%s\n", sendData.String( ) );
}
Esempio n. 22
0
func TestWriteAt(t *testing.T) {
	f, err := Open("_obj/writetest", O_CREAT|O_RDWR|O_TRUNC, 0666)
	if err != nil {
		t.Fatalf("open _obj/writetest: %s", err)
	}
	const data = "hello, world\n"
	io.WriteString(f, data)

	n, err := f.WriteAt(strings.Bytes("WORLD"), 7)
	if err != nil || n != 5 {
		t.Fatalf("WriteAt 7: %d, %v", n, err)
	}

	b, err := io.ReadFile("_obj/writetest")
	if err != nil {
		t.Fatalf("ReadFile _obj/writetest: %v", err)
	}
	if string(b) != "hello, WORLD\n" {
		t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
	}
}
Esempio n. 23
0
File: godoc.go Progetto: 8l/go-learn
// Parses a file (path) and returns the corresponding AST and
// a sorted list (by file position) of errors, if any.
//
func parse(path string, mode uint) (*ast.File, *parseErrors) {
	src, err := io.ReadFile(path)
	if err != nil {
		log.Stderrf("%v", err)
		errs := []parseError{parseError{nil, 0, err.String()}}
		return nil, &parseErrors{path, errs, nil}
	}

	prog, err := parser.ParseFile(path, src, mode)
	if err != nil {
		var errs []parseError
		if errors, ok := err.(scanner.ErrorList); ok {
			// convert error list (already sorted)
			// TODO(gri) If the file contains //line comments, the errors
			//           may not be sorted in increasing file offset value
			//           which will lead to incorrect output.
			errs = make([]parseError, len(errors)+1) // +1 for final fragment of source
			offs := 0
			for i, r := range errors {
				// Should always be true, but check for robustness.
				if 0 <= r.Pos.Offset && r.Pos.Offset <= len(src) {
					errs[i].src = src[offs:r.Pos.Offset]
					offs = r.Pos.Offset
				}
				errs[i].line = r.Pos.Line
				errs[i].msg = r.Msg
			}
			errs[len(errors)].src = src[offs:len(src)]
		} else {
			// single error of unspecified type
			errs = make([]parseError, 2)
			errs[0] = parseError{[]byte{}, 0, err.String()}
			errs[1].src = src
		}
		return nil, &parseErrors{path, errs, src}
	}

	return prog, nil
}
Esempio n. 24
0
func processFile(filename string) os.Error {
	src, err := io.ReadFile(filename)
	if err != nil {
		return err
	}

	file, err := parser.ParseFile(filename, src, parserMode())
	if err != nil {
		return err
	}

	var res bytes.Buffer
	_, err = (&printer.Config{printerMode(), *tabwidth, nil}).Fprint(&res, file)
	if err != nil {
		return err
	}

	if bytes.Compare(src, res.Bytes()) != 0 {
		// formatting has changed
		if *list {
			fmt.Fprintln(os.Stdout, filename)
		}
		if *write {
			err = io.WriteFile(filename, res.Bytes(), 0)
			if err != nil {
				return err
			}
		}
	}

	if !*list && !*write {
		_, err = os.Stdout.Write(res.Bytes())
	}

	return err
}
Esempio n. 25
0
File: main.go Progetto: 8l/go-learn
func main() {
	flag.Parse()
	w := eval.NewWorld()
	if *filename != "" {
		data, err := io.ReadFile(*filename)
		if err != nil {
			println(err.String())
			os.Exit(1)
		}
		file, err := parser.ParseFile(*filename, data, 0)
		if err != nil {
			println(err.String())
			os.Exit(1)
		}
		code, err := w.CompileDeclList(file.Decls)
		if err != nil {
			if list, ok := err.(scanner.ErrorList); ok {
				for _, e := range list {
					println(e.String())
				}
			} else {
				println(err.String())
			}
			os.Exit(1)
		}
		_, err := code.Run()
		if err != nil {
			println(err.String())
			os.Exit(1)
		}
		code, err = w.Compile("init()")
		if code != nil {
			_, err := code.Run()
			if err != nil {
				println(err.String())
				os.Exit(1)
			}
		}
		code, err = w.Compile("main()")
		if err != nil {
			println(err.String())
			os.Exit(1)
		}
		_, err = code.Run()
		if err != nil {
			println(err.String())
			os.Exit(1)
		}
		os.Exit(0)
	}

	r := bufio.NewReader(os.Stdin)
	for {
		print("; ")
		line, err := r.ReadString('\n')
		if err != nil {
			break
		}
		code, err := w.Compile(line)
		if err != nil {
			println(err.String())
			continue
		}
		v, err := code.Run()
		if err != nil {
			println(err.String())
			continue
		}
		if v != nil {
			println(v.String())
		}
	}
}
Esempio n. 26
0
func check(t *testing.T, source, golden string, mode checkMode) {
	// parse source
	prog, err := parser.ParseFile(source, nil, parser.ParseComments)
	if err != nil {
		t.Error(err)
		return
	}

	// filter exports if necessary
	if mode&export != 0 {
		ast.FileExports(prog) // ignore result
		prog.Comments = nil   // don't print comments that are not in AST
	}

	// determine printer configuration
	cfg := Config{Tabwidth: tabwidth}
	if mode&rawFormat != 0 {
		cfg.Mode |= RawFormat
	}

	// format source
	var buf bytes.Buffer
	if _, err := cfg.Fprint(&buf, prog); err != nil {
		t.Error(err)
	}
	res := buf.Bytes()

	// update golden files if necessary
	if *update {
		if err := io.WriteFile(golden, res, 0644); err != nil {
			t.Error(err)
		}
		return
	}

	// get golden
	gld, err := io.ReadFile(golden)
	if err != nil {
		t.Error(err)
		return
	}

	// compare lengths
	if len(res) != len(gld) {
		t.Errorf("len = %d, expected %d (= len(%s))", len(res), len(gld), golden)
	}

	// compare contents
	for i, line, offs := 0, 1, 0; i < len(res) && i < len(gld); i++ {
		ch := res[i]
		if ch != gld[i] {
			t.Errorf("%s:%d:%d: %s", source, line, i-offs+1, lineString(res, offs))
			t.Errorf("%s:%d:%d: %s", golden, line, i-offs+1, lineString(gld, offs))
			t.Error()
			return
		}
		if ch == '\n' {
			line++
			offs = i + 1
		}
	}
}
Esempio n. 27
0
func main() {
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()
	var data []byte
	var err os.Error
	switch len(args) {
	case 0:
		data, err = io.ReadAll(os.Stdin)
	case 1:
		data, err = io.ReadFile(args[0])
	default:
		usage()
	}
	chk(err)

	pset, err := patch.Parse(data)
	chk(err)

	// Change to hg root directory, because
	// patch paths are relative to root.
	root, err := hgRoot()
	chk(err)
	chk(os.Chdir(root))

	// Make sure there are no pending changes on the server.
	if *checkSync && hgIncoming() {
		fmt.Fprintf(os.Stderr, "incoming changes waiting; run hg sync first\n")
		os.Exit(2)
	}

	// Make sure we won't be editing files with local pending changes.
	dirtylist, err := hgModified()
	chk(err)
	dirty := make(map[string]int)
	for _, f := range dirtylist {
		dirty[f] = 1
	}
	conflict := make(map[string]int)
	for _, f := range pset.File {
		if f.Verb == patch.Delete || f.Verb == patch.Rename {
			if _, ok := dirty[f.Src]; ok {
				conflict[f.Src] = 1
			}
		}
		if f.Verb != patch.Delete {
			if _, ok := dirty[f.Dst]; ok {
				conflict[f.Dst] = 1
			}
		}
	}
	if len(conflict) > 0 {
		fmt.Fprintf(os.Stderr, "cannot apply patch to locally modified files:\n")
		for name := range conflict {
			fmt.Fprintf(os.Stderr, "\t%s\n", name)
		}
		os.Exit(2)
	}

	// Apply changes in memory.
	op, err := pset.Apply(io.ReadFile)
	chk(err)

	// Write changes to disk copy: order of commands matters.
	// Accumulate undo log as we go, in case there is an error.
	// Also accumulate list of modified files to print at end.
	changed := make(map[string]int)

	// Copy, Rename create the destination file, so they
	// must happen before we write the data out.
	// A single patch may have a Copy and a Rename
	// with the same source, so we have to run all the
	// Copy in one pass, then all the Rename.
	for i := range op {
		o := &op[i]
		if o.Verb == patch.Copy {
			makeParent(o.Dst)
			chk(hgCopy(o.Dst, o.Src))
			undoRevert(o.Dst)
			changed[o.Dst] = 1
		}
	}
	for i := range op {
		o := &op[i]
		if o.Verb == patch.Rename {
			makeParent(o.Dst)
			chk(hgRename(o.Dst, o.Src))
			undoRevert(o.Dst)
			undoRevert(o.Src)
			changed[o.Src] = 1
			changed[o.Dst] = 1
		}
	}

	// Run Delete before writing to files in case one of the
	// deleted paths is becoming a directory.
	for i := range op {
		o := &op[i]
		if o.Verb == patch.Delete {
			chk(hgRemove(o.Src))
			undoRevert(o.Src)
			changed[o.Src] = 1
		}
	}

	// Write files.
	for i := range op {
		o := &op[i]
		if o.Verb == patch.Delete {
			continue
		}
		if o.Verb == patch.Add {
			makeParent(o.Dst)
			changed[o.Dst] = 1
		}
		if o.Data != nil {
			chk(io.WriteFile(o.Dst, o.Data, 0644))
			if o.Verb == patch.Add {
				undoRm(o.Dst)
			} else {
				undoRevert(o.Dst)
			}
			changed[o.Dst] = 1
		}
		if o.Mode != 0 {
			chk(os.Chmod(o.Dst, o.Mode&0755))
			undoRevert(o.Dst)
			changed[o.Dst] = 1
		}
	}

	// hg add looks at the destination file, so it must happen
	// after we write the data out.
	for i := range op {
		o := &op[i]
		if o.Verb == patch.Add {
			chk(hgAdd(o.Dst))
			undoRevert(o.Dst)
			changed[o.Dst] = 1
		}
	}

	// Finished editing files.  Write the list of changed files to stdout.
	list := make([]string, len(changed))
	i := 0
	for f := range changed {
		list[i] = f
		i++
	}
	sort.SortStrings(list)
	for _, f := range list {
		fmt.Printf("%s\n", f)
	}
}
Esempio n. 28
0
// TODO: cache strategy
// TODO: learn best practice for reading template file into string and parsing
// TODO: check error from ReadFile
// TODO: synchronized cache for multithreading
func get_template(s string) *template.Template {
	var templateBytes, _ = io.ReadFile(s);
	var templateBuffer = bytes.NewBuffer(templateBytes);
	var templateStr = templateBuffer.String();
	return template.MustParse(templateStr, fmap);
}
Esempio n. 29
0
File: main.go Progetto: ox/GoStones
func main() {
	flag.Parse()
	errors := vector.New(0)

	//fill repositories StringVector
	repositories := vector.New(0) //make a new vec
	file, err := os.Open("./list.txt", os.O_RDONLY, 0755)
	if file == nil {
		errors.Push(err)
	}

	in = bufio.NewReader(file)
	ik := 0

	for {
		dat2, err := in.ReadSlice('\n')
		if err == os.EOF || (string(dat2[0:len(dat2)-1]) == "" && err == os.EOF) {
			errors.Push(err)
			break
		}

		if string(dat2[0]) != "#" && string(dat2[0]) != "" && string(dat2[0]) != "\n" { //# is a comment
			str := strings.Split(string(dat2), " ", -1)
			gem := NewGemSource(str[1:len(str)], str[0])
			repositories.Push(gem)

			ik++
		}
	}

	//get the version number
	if *get_go_gems_version {
		go_gems_version, err := io.ReadFile("./go_stones_version")

		if go_gems_version == nil {
			errors.Push(err)
		}
		fmt.Println("GoStones version ", string(go_gems_version))

		br()
	}

	//list repositories
	if *list {
		fmt.Println("listing", ik, "repos:")
		for i := 0; i < ik; i++ {
			fmt.Printf("%v\n", repositories.At(i).(*GemSource).url)
		}
		br()
	}

	if *list_full {
		for i := 0; i < ik; i++ {
			fmt.Printf("%v\n----------------------\n    ", repositories.At(i).(*GemSource))
			for _, v := range repositories.At(i).(*GemSource).short_names {
				fmt.Printf("%v\n    ", v)
			}
			br()
		}
	}

	if *remove_repository != "" {

		fmt.Println("looking for", *remove_repository)

		l := 0

		for ; l < ik; l++ {
			gem := repositories.At(l).(*GemSource)

			if gem.url == *remove_repository {
				fmt.Print("found! removing ", gem.url, " at ", l, "\n")
				repositories.Delete(l)
				break
			}

			for _, v := range gem.short_names {
				if v == *remove_repository || v == *remove_repository+"\n" {
					fmt.Print("found! removing ", v, " at ", l, "\n")
					repositories.Delete(l)
					l = ik
					break
				}
			}
		}

		if repositories.Len() == ik { //nothing was removed
			//our fall through
			fmt.Println("No such alias or url found in the list, check spelling or url,", repositories.Len())
			os.Exit(1)
		}

		file, err := os.Open("./list.txt", os.O_RDWR, 0755)
		if file == nil {
			errors.Push(err)
		}

		out = bufio.NewWriter(file)

		errlol := io.WriteFile(file.Name(), []byte{}, 0755)
		if errlol != nil {
			fmt.Print(errlol)
			errors.Push(errlol)
			os.Exit(1)
		}

		for i := 0; i < repositories.Len(); i++ {
			gem := repositories.At(i).(*GemSource)
			io.WriteString(out, gem.url)
			fmt.Print(gem)

			for k := 0; k < len(gem.short_names); k++ {
				io.WriteString(out, " "+gem.short_names[k])
				fmt.Print(" " + gem.short_names[k])
			}
			//io.WriteString(out, "\n" );
		}

		out.Flush()
		file.Close()
	}

	if *add_repo != "" {
		str := strings.Split(*add_repo, " ", -1)

		var gem *GemSource

		if len(str) == 1 {
			_, short_name := path.Split(str[0])
			short_name = strings.Split(short_name, ".", -1)[0]
			gem = NewGemSource([]string{short_name + "\n"}, str[0])
			fmt.Println("no alias provided, making it", short_name)
		} else {
			gem = NewGemSource(str[1:len(str)], str[0])
		}

		fmt.Println("adding:", gem)

		repositories.Push(gem)

		file, err := os.Open("./list.txt", os.O_RDWR, 0755)
		if file == nil {
			errors.Push(err)
		}

		out = bufio.NewWriter(file)

		for i := 0; i < repositories.Len(); i++ {
			gem := repositories.At(i).(*GemSource)
			io.WriteString(out, gem.url)
			for k := 0; k < len(gem.short_names); k++ {
				io.WriteString(out, " "+gem.short_names[k])
			}
		}
		io.WriteString(out, "\n")

		out.Flush()
		file.Close()
	}

	if *install != "" {
		file_name := *install

		//search the repos for the right file
		for i := 0; i < ik; i++ {
			gem := repositories.At(i).(*GemSource)
			_, pre_tested_name := path.Split(gem.short_names[0])
			tested_name := strings.Split(pre_tested_name, ".", -1)[0]

			for _, val := range gem.short_names {

				if tested_name == file_name || val == file_name || val == file_name+"\n" {
					str := strings.Split(gem.url, ":", -1)

					fmt.Println(str[0])

					switch str[0] {
					case "http":
						fmt.Println("Pulling from the net...")

						response, _, err := http.Get(gem.url)
						if err != nil {
							fmt.Println(err)
							os.Exit(1)
						}

						var nr int
						const buf_size = 0x10
						buf := make([]byte, buf_size)
						nr, _ = response.Body.Read(buf)

						if nr >= buf_size {
							panic("Buffer overrun")
						}

						errorr := io.WriteFile("./"+pre_tested_name, buf, 0755)
						if errorr != nil {
							fmt.Println(errorr)
							os.Exit(1)
						}

						buf = nil
						response.Body.Close()
						break

					case "git":
						fmt.Println("git'n it from the net...")

						dir := git_from_net(string(gem.url))
						log.Stdout(dir)
						build_pkg(string(dir))

						break
					}

					fmt.Println("passed retrieving file...")

					break
				}
			}
		}
	}

	if *show_errors {
		fmt.Println(errors)
	}

	file.Close()

}
Esempio n. 30
0
func main() {
	sqlite3.Initialize()
	defer func() {
		log.Stdout("closing sqlite3")
		sqlite3.Shutdown()
	}()

	dbh := new(sqlite3.Handle)
	dbh.Open("bbs.db")
	defer dbh.Close()

	InitTables(dbh)

	flag.Parse()
	templ := func() *template.Template {
		templateStr, err := io.ReadFile("tmpl/top.tmpl")
		if err != nil {
			log.Exit(err)
		}
		return template.MustParse(string(templateStr), nil)
	}()

	http.Handle("/", http.HandlerFunc(func(c *http.Conn, req *http.Request) {
		params := new(struct{ msgs []string })
		storage := new(vector.StringVector)
		func() {
			st, err := dbh.Prepare("SELECT * from entry ORDER BY id DESC limit 30;")
			func() {
				if err != "" {
					log.Exit(err)
				}
				for {
					rv := st.Step()
					switch {
					case rv == sqlite3.SQLITE_DONE:
						return
					case rv == sqlite3.SQLITE_ROW:
						body := st.ColumnText(1)
						storage.Push(body)
					default:
						println(rv)
						log.Exit(dbh.ErrMsg())
					}
				}
			}()
			if st.Finalize() != sqlite3.SQLITE_OK {
				log.Exit(dbh.ErrMsg())
			}
		}()
		params.msgs = storage.Data()
		err := templ.Execute(params, c)
		if err != nil {
			log.Exit("templ.Execute:", err)
		}
	}))
	http.Handle("/post", http.HandlerFunc(func(c *http.Conn, req *http.Request) {
		req.ParseForm()

		body := req.Form["body"][0]
		st, err := dbh.Prepare("INSERT INTO entry (body) VALUES (?)")
		if err != "" {
			log.Exit(err)
		}
		if st.BindText(1, body) != sqlite3.SQLITE_OK {
			log.Exit("cannot bind: ", dbh.ErrMsg())
		}
		if st.Step() != sqlite3.SQLITE_DONE {
			log.Exit(dbh.ErrMsg())
		}
		if st.Finalize() != sqlite3.SQLITE_OK {
			log.Exit(dbh.ErrMsg())
		}

		http.Redirect(c, "/", 302)
	}))
	http.Handle("/css/", http.HandlerFunc(func(c *http.Conn, req *http.Request) {
		http.ServeFile(c, req, "."+req.URL.Path)
	}))

	// run httpd
	func() {
		fmt.Printf("http://%s/\n", *addr)
		err := http.ListenAndServe(*addr, nil)
		if err != nil {
			log.Exit("ListenAndServe:", err)
		}
	}()
}