<commit_before>package client

import (
	"cnblogs/conf"
	"cnblogs/db"
	"cnblogs/ing"
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"strconv"

	"time"

	"github.com/robfig/cron"
)

//"github.com/PuerkitoBio/goquery"

var ingClient *ing.Client

//Main main function
func Main(conf conf.Conf) {
	ingClient = &ing.Client{}
	ingClient.Init(conf.AuthCookie)
	err := db.InitialDB()
	if err != nil {
		fmt.Println("Execute Sql Script Error: ", err)
		return
	}
	//http://home.cnblogs.com/ing/1115171/

	if conf.StartIngID <= 0 || conf.EndIngID <= 0 || conf.EndIngID < conf.StartIngID {
		fmt.Println("config startIngID or endIngID config error")
		return
	}

	ingID := conf.StartIngID
	c := cron.New()
	spec := "*/1 * * * * *"
	c.AddFunc(spec, func() {
		//ingID++
		if ingID > conf.EndIngID {
			fmt.Println("task finished")
			c.Stop()
			return
		}

		currentIngID := ingID
		ingID++
		fmt.Println("currentIngID", currentIngID)
		err = GetIngAndSaveToDB(currentIngID)
		if err != nil {
			//maybe can log err to database
			fmt.Println("IngID: ", currentIngID, "err: ", err)
		}
	})
	c.Start()
	if !conf.EnableSite {
		select {}
	}
}

//GetIngAndSaveToDB Get Ing Cotnent by IngID and save it to sqlite database
func GetIngAndSaveToDB(ingID int) error {
	if ingClient == nil {
		return errors.New("ingClient is not initial")
	}
	//search if current Ing in table && ingStatus is 404, do nothing.
	ingContent, originContent, err := ingClient.GetIngByID(ingID)
	if err != nil {
		return errors.New("Get IngInfo Error: " + err.Error())
	}

	if ingContent.Status == 403 {
		return errors.New("auth cookie invalid, please check")
	}
	//OriginContent
	//go call(*ingContent, *originContent)
	err = InsertToOriginDB(ingContent.IngID, *originContent)
	if err != nil {
		return errors.New("InsertToOriginDB: " + err.Error())
	}
	err = InsertIngToDB(*ingContent)
	if err != nil {
		return errors.New("InsertIngToDB: " + err.Error())
	}
	return nil
}

//InsertIngToDB Insert or update Ing To sqlite3 db
func InsertIngToDB(ingContent ing.Content) error {
	sqlite, err := db.GetDB()
	if err != nil {
		return errors.New("open db error: " + err.Error())
	}
	defer sqlite.Close()

	//if error is database is locked repeat 10 times
	for i := 1; i <= 10; i++ {
		err = sqlite.Ping()
		if err != nil {
			if err.Error() == "database is locked" {
				fmt.Println("Ping occur occured database is locked, try times:" + strconv.Itoa(i) +
					" IngID: " + strconv.Itoa(ingContent.IngID))
				time.Sleep(time.Millisecond * 100)
				continue
			}
			return errors.New("Ping error: " + err.Error())
		}
		break
	}
	trans, err := sqlite.Begin()
	if err != nil {
		return errors.New("begin trans error: " + err.Error())
	}
	//http://go-database-sql.org/prepared.html
	defer trans.Rollback()
	//Content
	stmt, err := trans.Prepare("select `Status` from `Ing` where IngID = ?")
	if err != nil {
		return errors.New("prepare select IngStatus error: " + err.Error())
	}
	defer stmt.Close()
	row := stmt.QueryRow(ingContent.IngID)
	var ingStatus int
	err = row.Scan(&ingStatus)

	if ingStatus == 0 || err == sql.ErrNoRows {
		sqlIngContent := "insert into `Ing` (`IngID`, `AuthorID`, `AuthorUserName`, `AuthorNickName`, `Time`, `Status`, `Lucky`, `IsPrivate`, `IsNewbie`, `AcquiredAt`, `Body`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
		stmt, err = trans.Prepare(sqlIngContent)
		if err != nil {
			return errors.New("prepare ing sql error: " + err.Error())
		}
		defer stmt.Close()
		_, err = stmt.Exec(ingContent.IngID, ingContent.AuthorID, ingContent.AuthorUserName, ingContent.AuthorNickName,
			ingContent.Time, ingContent.Status, ingContent.Lucky, ingContent.IsPrivate, ingContent.IsNewbie,
			ingContent.AcquiredAt, ingContent.Body)
		if err != nil {
			return errors.New("insert ing table error: " + err.Error())
		}
	} else if err != nil {
		return errors.New("scan ingStatus error: " + err.Error())
	}
	if ingStatus == 404 {
		trans.Commit()
		return nil
	}
	if ingContent.Status == 404 {
		//update status = 404 and return
		sqlIngUpdate := "update `Ing` set `Status` = 404 where `IngID` = ?"
		stmt, err = trans.Prepare(sqlIngUpdate)
		if err != nil {
			return errors.New("prepare update status sql error: " + err.Error())
		}
		defer stmt.Close()
		_, err := stmt.Exec(ingContent.IngID)
		if err != nil {
			return errors.New("update ing Status error: " + err.Error())
		}
		trans.Commit()
		return nil
	}
	//Comments
	stmt, err = trans.Prepare("select ID, CommentID from Comment where IngID = ? and IsDelete = 0")
	if err != nil {
		return errors.New("prepare select CommentID error: " + err.Error())
	}
	defer stmt.Close()
	rows, err := stmt.Query(ingContent.IngID)
	if err != nil {
		return errors.New("get CommentID error: " + err.Error())
	}
	defer rows.Close()
	// update IsDelete = 1, insert
	unDeletedCommentIDs := make([]string, 0)
	for rows.Next() {
		var ID int
		var commentID string
		err = rows.Scan(&ID, &commentID)
		if err != nil {
			return errors.New("get commentID error: " + err.Error())
		}
		unDeletedCommentIDs = append(unDeletedCommentIDs, commentID)
	}
	commentUpdated := false
	sqlIngComment := "insert into `Comment` (`IngID`, `CommentID`, `AuthorID`, `AuthorUserName`, `AuthorNickName`, `Body`, `Time`, `IsDelete`) values (?, ?, ?, ?, ?, ?, ?, ?);"
	stmt, err = trans.Prepare(sqlIngComment)
	if err != nil {
		return errors.New("prepare insert ingComment sql error: " + err.Error())
	}
	defer stmt.Close()
	for _, ingComment := range ingContent.Comments {
		//if CommentID in savedCommentIDs, remove it.
		currIndex := -1
		for i := 0; i < len(unDeletedCommentIDs); i++ {
			if unDeletedCommentIDs[i] == ingComment.CommentID {
				currIndex = i
				break
			}
		}
		if currIndex != -1 {
			unDeletedCommentIDs[currIndex] = ""
			continue
		}
		_, err = stmt.Exec(ingComment.IngID, ingComment.CommentID, ingComment.AuthorID, ingComment.AuthorUserName, ingComment.AuthorNickName,
			ingComment.Body, ingComment.Time, ingComment.IsDelete)
		if err != nil {
			return errors.New("insert comment error: " + err.Error())
		}
		if !commentUpdated {
			commentUpdated = true
		}
	}

	// set to Deleted
	sqlIngCommentUpdate := "update `Comment` set IsDelete = 1 where IngID = ? and CommentID = ?"
	stmt, err = trans.Prepare(sqlIngCommentUpdate)
	if err != nil {
		return errors.New("prepare update set IsDelete sql error: " + err.Error())
	}
	defer stmt.Close()
	if err != nil {
		return errors.New("prepare delete sql error: " + err.Error())
	}
	for _, willDeletedCommentID := range unDeletedCommentIDs {
		if willDeletedCommentID == "" {
			continue
		}
		if !commentUpdated {
			commentUpdated = true
		}
		_, err = stmt.Exec(ingContent.IngID, willDeletedCommentID)
		if err != nil {
			return errors.New("update Comment IsDelete flag error: " + err.Error())
		}
	}
	if commentUpdated && ingStatus == 200 {
		sqlStmt := "update `Ing` set `AcquiredAt` = ? where `IngID` = ?"
		stmt, err = trans.Prepare(sqlStmt)
		if err != nil {
			return errors.New("prepare ing AcquiredAt error: " + err.Error())
		}
		defer stmt.Close()
		_, err := stmt.Exec(ingContent.AcquiredAt, ingContent.IngID)
		if err != nil {
			return errors.New("update ing AcquiredAt error: " + err.Error())
		}
	}
	trans.Commit()
	return nil
}

//InsertToOriginDB store Origin Ing Info to seperator database
func InsertToOriginDB(ingID int, originContent ing.OriginContent) error {
	originDB, err := db.GetDBOrigin()
	if err != nil {
		return errors.New("open origin db error:" + err.Error())
	}
	defer originDB.Close()
	/*
		err = originDB.Ping()
		if err != nil {
			// do something here
		}
	*/
	originDB.SetMaxOpenConns(1)
	md5Hash := md5String(originContent.HTML)
	var htmlHash string
	//if error is database is locked repeat 10 times
	for i := 1; i <= 10; i++ {
		err = originDB.QueryRow("select `HTMLHash` from `OriginIng` where `IngID` = ? and `HTMLHash` = ?",
			ingID, md5Hash).Scan(&htmlHash)
		if err != nil {
			if err == sql.ErrNoRows {
				//sql: no rows in result set
				break
			}
			if err.Error() == "database is locked" {
				fmt.Println("scan htmlHash occured database is locked, try times:" + strconv.Itoa(i) + " IngID: " + strconv.Itoa(originContent.IngID))
				time.Sleep(time.Millisecond * 100)
				continue
			}
			return errors.New("scan htmlHash error: " + err.Error())
		}
		break
	}

	if htmlHash == "" || err == sql.ErrNoRows {
		sqlIngOriginContent := "insert into OriginIng (IngID, Status, AcquiredAt, Exception, HTMLHash, HTML) values (?, ?, ?, ?, ?, ?);"
		//if error is database is locked repeat 10 times
		for i := 1; i <= 10; i++ {
			_, err := originDB.Exec(sqlIngOriginContent, originContent.IngID, originContent.Status, originContent.AcquiredAt,
				originContent.Exception, md5Hash, originContent.HTML)
			if err != nil {
				if err.Error() == "database is locked" {
					fmt.Println("scan htmlHash occured database is locked, try times:" + strconv.Itoa(i) + " IngID: " + strconv.Itoa(originContent.IngID))
					time.Sleep(time.Millisecond * 100)
					continue
				}
				return errors.New("insert OriginContent error: " + err.Error())
			}
			break
		}
		/*
			id, err := result.LastInsertId()
			if err != nil {
				return errors.New("get LastInsertId error: " + err.Error())
			}
			fmt.Println("id", id)
		*/
	}
	return nil
}

func md5String(originString string) string {
	md5 := md5.New()
	md5.Write([]byte(originString))
	hashString := hex.EncodeToString(md5.Sum(nil))
	return hashString
}
<commit_msg>resolve insert ing occur database is locked error<commit_after>package client

import (
	"cnblogs/conf"
	"cnblogs/db"
	"cnblogs/ing"
	"crypto/md5"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"strconv"

	"time"

	"github.com/robfig/cron"
)

//"github.com/PuerkitoBio/goquery"

var ingClient *ing.Client

//Main main function
func Main(conf conf.Conf) {
	ingClient = &ing.Client{}
	ingClient.Init(conf.AuthCookie)
	err := db.InitialDB()
	if err != nil {
		fmt.Println("Execute Sql Script Error: ", err)
		return
	}
	//http://home.cnblogs.com/ing/1115171/

	if conf.StartIngID <= 0 || conf.EndIngID <= 0 || conf.EndIngID < conf.StartIngID {
		fmt.Println("config startIngID or endIngID config error")
		return
	}

	ingID := conf.StartIngID
	c := cron.New()
	spec := "*/1 * * * * *"
	c.AddFunc(spec, func() {
		//ingID++
		if ingID > conf.EndIngID {
			fmt.Println("task finished")
			c.Stop()
			return
		}

		currentIngID := ingID
		ingID++
		fmt.Println("currentIngID", currentIngID)
		err = GetIngAndSaveToDB(currentIngID)
		if err != nil {
			//maybe can log err to database
			fmt.Println("IngID: ", currentIngID, "err: ", err)
		}
	})
	c.Start()
	if !conf.EnableSite {
		select {}
	}
}

//GetIngAndSaveToDB Get Ing Cotnent by IngID and save it to sqlite database
func GetIngAndSaveToDB(ingID int) error {
	if ingClient == nil {
		return errors.New("ingClient is not initial")
	}
	//search if current Ing in table && ingStatus is 404, do nothing.
	ingContent, originContent, err := ingClient.GetIngByID(ingID)
	if err != nil {
		return errors.New("Get IngInfo Error: " + err.Error())
	}

	if ingContent.Status == 403 {
		return errors.New("auth cookie invalid, please check")
	}
	//OriginContent
	//go call(*ingContent, *originContent)
	err = InsertToOriginDB(ingContent.IngID, *originContent)
	if err != nil {
		return errors.New("InsertToOriginDB: " + err.Error())
	}
	err = InsertIngToDB(*ingContent)
	if err != nil {
		return errors.New("InsertIngToDB: " + err.Error())
	}
	return nil
}

//InsertIngToDB Insert or update Ing To sqlite3 db
func InsertIngToDB(ingContent ing.Content) error {
	sqlite, err := db.GetDB()
	if err != nil {
		return errors.New("open db error: " + err.Error())
	}
	defer sqlite.Close()

	//if error is database is locked repeat 10 times
	for i := 1; i <= 10; i++ {
		err = sqlite.Ping()
		if err != nil {
			if err.Error() == "database is locked" {
				fmt.Println("Ping occured database is locked, try times:" + strconv.Itoa(i) +
					" IngID: " + strconv.Itoa(ingContent.IngID))
				time.Sleep(time.Millisecond * 100)
				continue
			}
			return errors.New("Ping error: " + err.Error())
		}
		break
	}
	trans, err := sqlite.Begin()
	if err != nil {
		return errors.New("begin trans error: " + err.Error())
	}
	//http://go-database-sql.org/prepared.html
	defer trans.Rollback()
	//Content
	stmt, err := trans.Prepare("select `Status` from `Ing` where IngID = ?")
	if err != nil {
		return errors.New("prepare select IngStatus error: " + err.Error())
	}
	defer stmt.Close()
	row := stmt.QueryRow(ingContent.IngID)
	var ingStatus int
	err = row.Scan(&ingStatus)

	if ingStatus == 0 || err == sql.ErrNoRows {
		sqlIngContent := "insert into `Ing` (`IngID`, `AuthorID`, `AuthorUserName`, `AuthorNickName`, `Time`, `Status`, `Lucky`, `IsPrivate`, `IsNewbie`, `AcquiredAt`, `Body`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
		stmt, err = trans.Prepare(sqlIngContent)
		if err != nil {
			return errors.New("prepare ing sql error: " + err.Error())
		}
		defer stmt.Close()
		//if error is database is locked repeat 10 times
		for i := 1; i <= 10; i++ {
			_, err = stmt.Exec(ingContent.IngID, ingContent.AuthorID, ingContent.AuthorUserName, ingContent.AuthorNickName,
				ingContent.Time, ingContent.Status, ingContent.Lucky, ingContent.IsPrivate, ingContent.IsNewbie,
				ingContent.AcquiredAt, ingContent.Body)
			if err != nil {
				if err.Error() == "database is locked" {
					fmt.Println("insert ing table occured database is locked, try times:" + strconv.Itoa(i) +
						" IngID: " + strconv.Itoa(ingContent.IngID))
					time.Sleep(time.Millisecond * 100)
					continue
				}
				return errors.New("insert ing table error: " + err.Error())
			}
			break
		}
	} else if err != nil {
		return errors.New("scan ingStatus error: " + err.Error())
	}
	if ingStatus == 404 {
		trans.Commit()
		return nil
	}
	if ingContent.Status == 404 {
		//update status = 404 and return
		sqlIngUpdate := "update `Ing` set `Status` = 404 where `IngID` = ?"
		stmt, err = trans.Prepare(sqlIngUpdate)
		if err != nil {
			return errors.New("prepare update status sql error: " + err.Error())
		}
		defer stmt.Close()
		_, err := stmt.Exec(ingContent.IngID)
		if err != nil {
			return errors.New("update ing Status error: " + err.Error())
		}
		trans.Commit()
		return nil
	}
	//Comments
	stmt, err = trans.Prepare("select ID, CommentID from Comment where IngID = ? and IsDelete = 0")
	if err != nil {
		return errors.New("prepare select CommentID error: " + err.Error())
	}
	defer stmt.Close()
	rows, err := stmt.Query(ingContent.IngID)
	if err != nil {
		return errors.New("get CommentID error: " + err.Error())
	}
	defer rows.Close()
	// update IsDelete = 1, insert
	unDeletedCommentIDs := make([]string, 0)
	for rows.Next() {
		var ID int
		var commentID string
		err = rows.Scan(&ID, &commentID)
		if err != nil {
			return errors.New("get commentID error: " + err.Error())
		}
		unDeletedCommentIDs = append(unDeletedCommentIDs, commentID)
	}
	commentUpdated := false
	sqlIngComment := "insert into `Comment` (`IngID`, `CommentID`, `AuthorID`, `AuthorUserName`, `AuthorNickName`, `Body`, `Time`, `IsDelete`) values (?, ?, ?, ?, ?, ?, ?, ?);"
	stmt, err = trans.Prepare(sqlIngComment)
	if err != nil {
		return errors.New("prepare insert ingComment sql error: " + err.Error())
	}
	defer stmt.Close()
	for _, ingComment := range ingContent.Comments {
		//if CommentID in savedCommentIDs, remove it.
		currIndex := -1
		for i := 0; i < len(unDeletedCommentIDs); i++ {
			if unDeletedCommentIDs[i] == ingComment.CommentID {
				currIndex = i
				break
			}
		}
		if currIndex != -1 {
			unDeletedCommentIDs[currIndex] = ""
			continue
		}
		_, err = stmt.Exec(ingComment.IngID, ingComment.CommentID, ingComment.AuthorID, ingComment.AuthorUserName, ingComment.AuthorNickName,
			ingComment.Body, ingComment.Time, ingComment.IsDelete)
		if err != nil {
			return errors.New("insert comment error: " + err.Error())
		}
		if !commentUpdated {
			commentUpdated = true
		}
	}

	// set to Deleted
	sqlIngCommentUpdate := "update `Comment` set IsDelete = 1 where IngID = ? and CommentID = ?"
	stmt, err = trans.Prepare(sqlIngCommentUpdate)
	if err != nil {
		return errors.New("prepare update set IsDelete sql error: " + err.Error())
	}
	defer stmt.Close()
	if err != nil {
		return errors.New("prepare delete sql error: " + err.Error())
	}
	for _, willDeletedCommentID := range unDeletedCommentIDs {
		if willDeletedCommentID == "" {
			continue
		}
		if !commentUpdated {
			commentUpdated = true
		}
		_, err = stmt.Exec(ingContent.IngID, willDeletedCommentID)
		if err != nil {
			return errors.New("update Comment IsDelete flag error: " + err.Error())
		}
	}
	if commentUpdated && ingStatus == 200 {
		sqlStmt := "update `Ing` set `AcquiredAt` = ? where `IngID` = ?"
		stmt, err = trans.Prepare(sqlStmt)
		if err != nil {
			return errors.New("prepare ing AcquiredAt error: " + err.Error())
		}
		defer stmt.Close()
		_, err := stmt.Exec(ingContent.AcquiredAt, ingContent.IngID)
		if err != nil {
			return errors.New("update ing AcquiredAt error: " + err.Error())
		}
	}
	trans.Commit()
	return nil
}

//InsertToOriginDB store Origin Ing Info to seperator database
func InsertToOriginDB(ingID int, originContent ing.OriginContent) error {
	originDB, err := db.GetDBOrigin()
	if err != nil {
		return errors.New("open origin db error:" + err.Error())
	}
	defer originDB.Close()
	/*
		err = originDB.Ping()
		if err != nil {
			// do something here
		}
	*/
	originDB.SetMaxOpenConns(1)
	md5Hash := md5String(originContent.HTML)
	var htmlHash string
	//if error is database is locked repeat 10 times
	for i := 1; i <= 10; i++ {
		err = originDB.QueryRow("select `HTMLHash` from `OriginIng` where `IngID` = ? and `HTMLHash` = ?",
			ingID, md5Hash).Scan(&htmlHash)
		if err != nil {
			if err == sql.ErrNoRows {
				//sql: no rows in result set
				break
			}
			if err.Error() == "database is locked" {
				fmt.Println("scan htmlHash occured database is locked, try times:" + strconv.Itoa(i) + " IngID: " + strconv.Itoa(originContent.IngID))
				time.Sleep(time.Millisecond * 100)
				continue
			}
			return errors.New("scan htmlHash error: " + err.Error())
		}
		break
	}

	if htmlHash == "" || err == sql.ErrNoRows {
		sqlIngOriginContent := "insert into OriginIng (IngID, Status, AcquiredAt, Exception, HTMLHash, HTML) values (?, ?, ?, ?, ?, ?);"
		//if error is database is locked repeat 10 times
		for i := 1; i <= 10; i++ {
			_, err := originDB.Exec(sqlIngOriginContent, originContent.IngID, originContent.Status, originContent.AcquiredAt,
				originContent.Exception, md5Hash, originContent.HTML)
			if err != nil {
				if err.Error() == "database is locked" {
					fmt.Println("scan htmlHash occured database is locked, try times:" + strconv.Itoa(i) + " IngID: " + strconv.Itoa(originContent.IngID))
					time.Sleep(time.Millisecond * 100)
					continue
				}
				return errors.New("insert OriginContent error: " + err.Error())
			}
			break
		}
		/*
			id, err := result.LastInsertId()
			if err != nil {
				return errors.New("get LastInsertId error: " + err.Error())
			}
			fmt.Println("id", id)
		*/
	}
	return nil
}

func md5String(originString string) string {
	md5 := md5.New()
	md5.Write([]byte(originString))
	hashString := hex.EncodeToString(md5.Sum(nil))
	return hashString
}
<|endoftext|>


<commit_before>package aat

import (
	"testing"
	"time"

	"github.com/gammazero/nexus/wamp"
)

func TestWhitelistAttribute(t *testing.T) {
	// Setup subscriber1
	subscriber1, err := connectClientDetails(wamp.Dict{"org_id": "spirent"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync1 := make(chan struct{})
	evtHandler1 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber1.Subscribe(testTopic, evtHandler1, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Setup subscriber2
	subscriber2, err := connectClientDetails(wamp.Dict{"org_id": "other"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync2 := make(chan struct{})
	evtHandler2 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber2.Subscribe(testTopic, evtHandler2, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Connect publisher
	publisher, err := connectClient()
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}

	opts := wamp.Dict{"eligible_org_id": wamp.List{"spirent", "goodguys"}}

	// Publish an event to something that matches by wildcard.
	publisher.Publish(testTopic, opts, wamp.List{"hello world"}, nil)

	// Make sure the event was received by subscriber1
	select {
	case <-sync1:
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Subscriber1 did not get published event")
	}

	// Make sure the event was not received by subscriber2
	select {
	case <-sync2:
		t.Fatal("Subscriber2 received published event")
	case <-time.After(200 * time.Millisecond):
	}

	err = subscriber1.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
	err = subscriber2.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
}

func TestBlacklistAttribute(t *testing.T) {
	// Setup subscriber1
	subscriber1, err := connectClientDetails(wamp.Dict{"org_id": "spirent"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync1 := make(chan struct{})
	evtHandler1 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber1.Subscribe(testTopic, evtHandler1, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Setup subscriber2
	subscriber2, err := connectClientDetails(wamp.Dict{"org_id": "other"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync2 := make(chan struct{})
	evtHandler2 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber2.Subscribe(testTopic, evtHandler2, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Connect publisher
	publisher, err := connectClient()
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}

	opts := wamp.Dict{"exclude_org_id": wamp.List{"other", "bagduy"}}

	// Publish an event to something that matches by wildcard.
	publisher.Publish(testTopic, opts, wamp.List{"hello world"}, nil)

	// Make sure the event was received by subscriber1
	select {
	case <-sync1:
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Subscriber1 did not get published event")
	}

	// Make sure the event was not received by subscriber2
	select {
	case <-sync2:
		t.Fatal("Subscriber2 received published event")
	case <-time.After(200 * time.Millisecond):
	}

	err = subscriber1.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
	err = subscriber2.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
}
<commit_msg>fix signaling in test<commit_after>package aat

import (
	"testing"
	"time"

	"github.com/gammazero/nexus/wamp"
)

func TestWhitelistAttribute(t *testing.T) {
	// Setup subscriber1
	subscriber1, err := connectClientDetails(wamp.Dict{"org_id": "spirent"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync1 := make(chan struct{})
	evtHandler1 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber1.Subscribe(testTopic, evtHandler1, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Setup subscriber2
	subscriber2, err := connectClientDetails(wamp.Dict{"org_id": "other"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync2 := make(chan struct{})
	evtHandler2 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync2 <- struct{}{}
	}
	err = subscriber2.Subscribe(testTopic, evtHandler2, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Connect publisher
	publisher, err := connectClient()
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}

	opts := wamp.Dict{"eligible_org_id": wamp.List{"spirent", "goodguys"}}

	// Publish an event to something that matches by wildcard.
	publisher.Publish(testTopic, opts, wamp.List{"hello world"}, nil)

	// Make sure the event was received by subscriber1
	select {
	case <-sync1:
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Subscriber1 did not get published event")
	}

	// Make sure the event was not received by subscriber2
	select {
	case <-sync2:
		t.Fatal("Subscriber2 received published event")
	case <-time.After(200 * time.Millisecond):
	}

	err = subscriber1.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
	err = subscriber2.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
}

func TestBlacklistAttribute(t *testing.T) {
	// Setup subscriber1
	subscriber1, err := connectClientDetails(wamp.Dict{"org_id": "spirent"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync1 := make(chan struct{})
	evtHandler1 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync1 <- struct{}{}
	}
	err = subscriber1.Subscribe(testTopic, evtHandler1, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Setup subscriber2
	subscriber2, err := connectClientDetails(wamp.Dict{"org_id": "other"})
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}
	sync2 := make(chan struct{})
	evtHandler2 := func(args wamp.List, kwargs wamp.Dict, details wamp.Dict) {
		sync2 <- struct{}{}
	}
	err = subscriber2.Subscribe(testTopic, evtHandler2, nil)
	if err != nil {
		t.Fatal("subscribe error:", err)
	}

	// Connect publisher
	publisher, err := connectClient()
	if err != nil {
		t.Fatal("Failed to connect client:", err)
	}

	opts := wamp.Dict{"exclude_org_id": wamp.List{"other", "bagduy"}}

	// Publish an event to something that matches by wildcard.
	publisher.Publish(testTopic, opts, wamp.List{"hello world"}, nil)

	// Make sure the event was received by subscriber1
	select {
	case <-sync1:
	case <-time.After(200 * time.Millisecond):
		t.Fatal("Subscriber1 did not get published event")
	}

	// Make sure the event was not received by subscriber2
	select {
	case <-sync2:
		t.Fatal("Subscriber2 received published event")
	case <-time.After(200 * time.Millisecond):
	}

	err = subscriber1.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
	err = subscriber2.Close()
	if err != nil {
		t.Fatal("Failed to disconnect client:", err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"

	"github.com/ninjasphere/go-openzwave"
)

const (
	driverName = "com.ninjablocks.zwave"
)

var (
	log  = logger.GetLogger(driverName)
	info = ninja.LoadModuleInfo("./package.json")
)

/*model.Module{
	ID:          "com.ninjablocks.zwave",
	Name:        "ZWave Driver",
	Version:     "0.2.0",
	Description: "Ninja Blocks ZWave driver",
	Author:      "Jon Seymour <jon@ninjablocks.com>",
	License:     "MIT",
}*/

type zwaveDriver struct {
	config    *ZWaveDriverConfig
	conn      *ninja.Connection
	debug     bool
	zwaveAPI  openzwave.API
	exit      chan int
	sendEvent func(event string, payload interface{}) error
}

type ZWaveDriverConfig struct {
}

func defaultConfig() *ZWaveDriverConfig {
	return &ZWaveDriverConfig{}
}

func (driver *zwaveDriver) GetOpenZWaveAPI() openzwave.API {
	return driver.zwaveAPI
}

func (driver *zwaveDriver) GetNinjaDriver() ninja.Driver {
	return driver
}

func (driver *zwaveDriver) GetNinjaConnection() *ninja.Connection {
	return driver.conn
}

func newZWaveDriver(debug bool) (*zwaveDriver, error) {

	conn, err := ninja.Connect(driverName)

	if err != nil {
		log.Fatalf("Failed to create %s driver: %s", driverName, err)
	}

	driver := &zwaveDriver{
		config:    defaultConfig(),
		conn:      conn,
		sendEvent: nil,
		debug:     debug,
		zwaveAPI:  nil,
		exit:      make(chan int, 0),
	}

	err = conn.ExportDriver(driver)

	if err != nil {
		log.Fatalf("Failed to export %s driver: %s", driverName, err)
	}

	return driver, nil
}

func (d *zwaveDriver) Start(config *ZWaveDriverConfig) error {
	log.Infof("Driver %s starting with config %v", driverName, config)

	d.config = config

	zwaveDeviceFactory := func(api openzwave.API, node openzwave.Node) openzwave.Device {
		d.zwaveAPI = api
		return GetLibrary().GetDeviceFactory(*node.GetProductId())(d, node)
	}

	configurator := openzwave.
		BuildAPI("/usr/local/etc/openzwave", ".", "").
		SetLogger(log).
		SetDeviceFactory(zwaveDeviceFactory)

	if d.debug {
		callback := func(api openzwave.API, notification openzwave.Notification) {
			api.Logger().Infof("%v\n", notification)
		}

		configurator.SetNotificationCallback(callback)
	}

	go func() {
		// slightly racy - we would like a guarantee we have replied to Start
		// before we start generating advice about new nodes.
		d.exit <- configurator.Run()
	}()

	d.sendEvent("config", config)

	return nil
}

func (d *zwaveDriver) Stop() error {
	// TODO: propagate shutdown request to ZWave driver and let it take it down
	log.Infof("Stop received - shutting down")
	d.exit <- 0
	return nil
}

// wait until the drivers are ready for us to shutdown.
func (d *zwaveDriver) Wait() int {
	return <-d.exit
}

func (d *zwaveDriver) GetModuleInfo() *model.Module {
	return info
}

func (d *zwaveDriver) SetEventHandler(sendEvent func(event string, payload interface{}) error) {
	d.sendEvent = sendEvent
}
<commit_msg>Shutdown the driver in response to ZWave NODE_REMOVED events.<commit_after>package main

import (
	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"

	"github.com/ninjasphere/go-openzwave"
	"github.com/ninjasphere/go-openzwave/NT"
)

const (
	driverName = "com.ninjablocks.zwave"
)

var (
	log  = logger.GetLogger(driverName)
	info = ninja.LoadModuleInfo("./package.json")
)

/*model.Module{
	ID:          "com.ninjablocks.zwave",
	Name:        "ZWave Driver",
	Version:     "0.2.0",
	Description: "Ninja Blocks ZWave driver",
	Author:      "Jon Seymour <jon@ninjablocks.com>",
	License:     "MIT",
}*/

type zwaveDriver struct {
	config    *ZWaveDriverConfig
	conn      *ninja.Connection
	debug     bool
	zwaveAPI  openzwave.API
	exit      chan int
	sendEvent func(event string, payload interface{}) error
}

type ZWaveDriverConfig struct {
}

func defaultConfig() *ZWaveDriverConfig {
	return &ZWaveDriverConfig{}
}

func (driver *zwaveDriver) GetOpenZWaveAPI() openzwave.API {
	return driver.zwaveAPI
}

func (driver *zwaveDriver) GetNinjaDriver() ninja.Driver {
	return driver
}

func (driver *zwaveDriver) GetNinjaConnection() *ninja.Connection {
	return driver.conn
}

func newZWaveDriver(debug bool) (*zwaveDriver, error) {

	conn, err := ninja.Connect(driverName)

	if err != nil {
		log.Fatalf("Failed to create %s driver: %s", driverName, err)
	}

	driver := &zwaveDriver{
		config:    defaultConfig(),
		conn:      conn,
		sendEvent: nil,
		debug:     debug,
		zwaveAPI:  nil,
		exit:      make(chan int, 0),
	}

	err = conn.ExportDriver(driver)

	if err != nil {
		log.Fatalf("Failed to export %s driver: %s", driverName, err)
	}

	return driver, nil
}

func (d *zwaveDriver) Start(config *ZWaveDriverConfig) error {
	log.Infof("Driver %s starting with config %v", driverName, config)

	d.config = config

	zwaveDeviceFactory := func(api openzwave.API, node openzwave.Node) openzwave.Device {
		d.zwaveAPI = api
		return GetLibrary().GetDeviceFactory(*node.GetProductId())(d, node)
	}

	shuttingDown := false

	notificationCallback := func(api openzwave.API, nt openzwave.Notification) {
		switch nt.GetNotificationType().Code {
		case NT.NODE_REMOVED:
			//
			// Currently the RPC layer prevents us releasing the resources associated
			// with removed nodes. If the nodes come back (when, say, the zwave controller
			// is re-inserted), we can't build new device  wrappers for them because the
			// devices are already registered with the RPC layer.
			//
			// We could fix the RPC layer or we could attempt to work around the
			// problems with the RPC layer by using "patch" proxies for each ninja device
			// that allows us to change the actual zwave device.
			//
			// For now, it is simpler if we simply restart the driver process in the event of node
			// removal. This also avoids potential race conditions between
			// event dispatch and freeing of the resources associated with the
			// removed node.
			//
			if !shuttingDown {
				shuttingDown = true
				api.Logger().Infof("ZWave driver shutdown in response to node removed event.")
				api.Shutdown(openzwave.EXIT_NODE_REMOVED)
			}
		default:

		}
	}

	configurator := openzwave.
		BuildAPI("/usr/local/etc/openzwave", ".", "").
		SetLogger(log).
		SetNotificationCallback(notificationCallback).
		SetDeviceFactory(zwaveDeviceFactory)

	if d.debug {
		callback := func(api openzwave.API, notification openzwave.Notification) {
			api.Logger().Infof("%v\n", notification)
			notificationCallback(api, notification)
		}

		configurator.SetNotificationCallback(callback)
	}

	go func() {
		// slightly racy - we would like a guarantee we have replied to Start
		// before we start generating advice about new nodes.
		d.exit <- configurator.Run()
	}()

	d.sendEvent("config", config)

	return nil
}

func (d *zwaveDriver) Stop() error {
	// TODO: propagate shutdown request to ZWave driver and let it take it down
	log.Infof("Stop received - shutting down")
	d.exit <- 0
	return nil
}

// wait until the drivers are ready for us to shutdown.
func (d *zwaveDriver) Wait() int {
	return <-d.exit
}

func (d *zwaveDriver) GetModuleInfo() *model.Module {
	return info
}

func (d *zwaveDriver) SetEventHandler(sendEvent func(event string, payload interface{}) error) {
	d.sendEvent = sendEvent
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path"
	"regexp"
	"syscall"
	"text/template"
	"time"

	"github.com/codegangsta/cli"
	godaemon "github.com/yookoala/go-daemon"
)

func handleShutdown(l net.Listener, pidfile string) {
	c := make(chan os.Signal, 1)
	signal.Notify(c,
		os.Interrupt,
		syscall.SIGTERM,
		syscall.SIGQUIT,
		syscall.SIGKILL)

	for {
		select {
		case <-c:
			l.Close()
			if pidfile != "" {
				os.Remove(pidfile)
			}
			os.Exit(0)
		}
	}
}

func handleConnection(conn net.Conn, src *gitSource, stdout, stderr io.Writer) {
	log.Printf("server: handleConnection")
	defer conn.Close()

	for {
		bufbytes := make([]byte, 1024)
		nr, err := conn.Read(bufbytes)

		// handle error
		if err == io.EOF {
			log.Printf("server: client connect closed")
			return
		} else if err != nil {
			log.Printf("server read error: %#v", err.Error())
			return
		}

		data := bufbytes[0:nr]
		log.Printf("server got: %s", data)

		rw := io.MultiWriter(conn, stdout)
		ew := io.MultiWriter(conn, stderr)
		ctx := src.Context(rw, ew)
		ctx.Logf("command received: %s", data)

		if err := ctx.HardPull(); err == io.EOF {
			ctx.Logf("command completed")
			log.Printf("server: connection terminated")
			return
		} else if err != nil {
			log.Printf("callback error: %s", err.Error())
			return
		}
	}
}

// address returns networkk and address that fits
// the use of either net.Dial or net.Listen
func address(listen string) (network, address string) {
	reIP := regexp.MustCompile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(\\d{2,5}$)")
	rePort := regexp.MustCompile("^(\\d+)$")
	switch {
	case reIP.MatchString(listen):
		network = "tcp"
		address = listen
	case rePort.MatchString(listen):
		network = "tcp"
		address = ":" + listen
	default:
		network = "unix"
		address = listen
	}
	return
}

func actionServer(c *cli.Context) {

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr

	if output := c.String("output"); output != "" {
		var f *os.File
		var err error
		if f, err = os.Create(output); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	} else if c.Bool("daemon") {
		var f *os.File
		var err error
		if f, err = os.Create(os.DevNull); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	}

	// daemonized server
	if c.Bool("daemon") {
		context := new(godaemon.Context)
		if child, _ := context.Reborn(); child != nil {

			// set timeout time
			timeout := time.After(time.Second * 30)

			// test if the socket is ready
			ready := make(chan int)
			go func() {
				for {
					conn, err := net.Dial(address(c.String("listen")))
					if err == nil {
						conn.Close() // close the test connection
						break
					}
					// sleep 2 millisecond before next check
					time.Sleep(time.Millisecond * 2)
				}
				ready <- 0
			}()

			// wait until timeout or socket ready by child
			select {
			case <-timeout:
				log.Fatalf("timeout: socket not ready in %d seconds", 30)
			case <-ready:
				return
			}
		}
		defer context.Release()
		actionServerMain(c, stdout, stderr)
		return
	}

	// normal server output
	actionServerMain(c, stdout, stderr)
}

func actionServerMain(c *cli.Context, stdout, stderr io.Writer) {

	l, err := net.Listen(address(c.String("listen")))
	if err != nil {
		log.Fatalf("error: %s", err)
	}

	pidfile := c.String("pidfile")
	if pidfile != "" {
		// get current pid and write to file
		pid := fmt.Sprintf("%d", os.Getpid())
		ioutil.WriteFile(pidfile, []byte(pid), 0600)
	}

	// cleanly disconnect the socket
	go handleShutdown(l, pidfile)

	// define git source to update from
	src := newSource(mustGitRootPath(c.String("gitrepo")),
		c.String("remote"), c.String("branch"))

	for {
		conn, err := l.Accept()
		if err != nil {
			panic(err)
		}

		go handleConnection(conn, src, stdout, stderr)
	}
}

func actionOnce(c *cli.Context) {

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr
	if output := c.String("output"); output != "" {
		var f *os.File
		var err error
		if f, err = os.Create(output); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	}

	// define git source to update from
	src := newSource(mustGitRootPath(c.String("gitrepo")),
		c.String("remote"), c.String("branch"))

	if err := src.Context(stdout, stderr).HardPull(); err != io.EOF {
		log.Fatalf("error: %s", err.Error())
	}
}

func actionClient(c *cli.Context) {
	conn, err := net.Dial(address(c.String("conn")))
	if err != nil {
		log.Fatalf("connection error: %s", err.Error())
		return
	}

	conn.Write([]byte("hello\n"))

	bufbytes := make([]byte, 1024)
	for {
		nr, err := conn.Read(bufbytes)

		// handle error
		if err == io.EOF {
			log.Printf("client: server connect closed")
			return
		} else if err != nil {
			log.Printf("client read error: %#v", err.Error())
			return
		}

		data := bufbytes[0:nr]
		fmt.Printf("%s", data)
	}
}

func createHookScript(filename, command string) (err error) {

	// template for git hook script
	tpl := template.Must(template.New("gitsocket").Parse(`#!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-checkout".
{{ .Command }}
`))

	f, err := os.Create(filename)
	if err != nil {
		log.Fatalf("error: %s", err)
		return
	}
	err = tpl.Execute(f, map[string]interface{}{
		"Command": command,
	})
	f.Close()
	if err != nil {
		return
	}

	err = os.Chmod(filename, 0777)
	return
}

func actionSetup(c *cli.Context) {

	// define git source to update from
	rootPath := mustGitRootPath(c.String("gitrepo"))
	filename := path.Join(rootPath, ".git/hooks/post-checkout")

	if command := c.String("command"); command != "" {
		// if file not exists, create the file
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			createHookScript(filename, command)
			return
		} else if c.Bool("force") {
			createHookScript(filename, command)
			return
		}
		fmt.Println("post-checkout script already exists. If you want to " +
			"overwrite, please use the -f flag")
		os.Exit(1)
		return
	}

	// if file not exists, create the file
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		createHookScript(filename, "exec echo \"checkout completed.\"\n")
	}

	cmd := exec.Command("vi", filename)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout
	if err := cmd.Run(); err != nil {
		log.Fatalf("error: %s", err)
	}
}
<commit_msg>client: improve output message<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path"
	"regexp"
	"syscall"
	"text/template"
	"time"

	"github.com/codegangsta/cli"
	godaemon "github.com/yookoala/go-daemon"
)

func handleShutdown(l net.Listener, pidfile string) {
	c := make(chan os.Signal, 1)
	signal.Notify(c,
		os.Interrupt,
		syscall.SIGTERM,
		syscall.SIGQUIT,
		syscall.SIGKILL)

	for {
		select {
		case <-c:
			l.Close()
			if pidfile != "" {
				os.Remove(pidfile)
			}
			os.Exit(0)
		}
	}
}

func handleConnection(conn net.Conn, src *gitSource, stdout, stderr io.Writer) {
	log.Printf("server: handleConnection")
	defer conn.Close()

	for {
		bufbytes := make([]byte, 1024)
		nr, err := conn.Read(bufbytes)

		// handle error
		if err == io.EOF {
			log.Printf("server: client connect closed")
			return
		} else if err != nil {
			log.Printf("server read error: %#v", err.Error())
			return
		}

		data := bufbytes[0:nr]
		log.Printf("server got: %s", data)

		rw := io.MultiWriter(conn, stdout)
		ew := io.MultiWriter(conn, stderr)
		ctx := src.Context(rw, ew)
		ctx.Logf("command received: %s", data)

		if err := ctx.HardPull(); err == io.EOF {
			ctx.Logf("command completed")
			log.Printf("server: connection terminated")
			return
		} else if err != nil {
			log.Printf("callback error: %s", err.Error())
			return
		}
	}
}

// address returns networkk and address that fits
// the use of either net.Dial or net.Listen
func address(listen string) (network, address string) {
	reIP := regexp.MustCompile("^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\:(\\d{2,5}$)")
	rePort := regexp.MustCompile("^(\\d+)$")
	switch {
	case reIP.MatchString(listen):
		network = "tcp"
		address = listen
	case rePort.MatchString(listen):
		network = "tcp"
		address = ":" + listen
	default:
		network = "unix"
		address = listen
	}
	return
}

func actionServer(c *cli.Context) {

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr

	if output := c.String("output"); output != "" {
		var f *os.File
		var err error
		if f, err = os.Create(output); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	} else if c.Bool("daemon") {
		var f *os.File
		var err error
		if f, err = os.Create(os.DevNull); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	}

	// daemonized server
	if c.Bool("daemon") {
		context := new(godaemon.Context)
		if child, _ := context.Reborn(); child != nil {

			// set timeout time
			timeout := time.After(time.Second * 30)

			// test if the socket is ready
			ready := make(chan int)
			go func() {
				for {
					conn, err := net.Dial(address(c.String("listen")))
					if err == nil {
						conn.Close() // close the test connection
						break
					}
					// sleep 2 millisecond before next check
					time.Sleep(time.Millisecond * 2)
				}
				ready <- 0
			}()

			// wait until timeout or socket ready by child
			select {
			case <-timeout:
				log.Fatalf("timeout: socket not ready in %d seconds", 30)
			case <-ready:
				return
			}
		}
		defer context.Release()
		actionServerMain(c, stdout, stderr)
		return
	}

	// normal server output
	actionServerMain(c, stdout, stderr)
}

func actionServerMain(c *cli.Context, stdout, stderr io.Writer) {

	l, err := net.Listen(address(c.String("listen")))
	if err != nil {
		log.Fatalf("error: %s", err)
	}

	pidfile := c.String("pidfile")
	if pidfile != "" {
		// get current pid and write to file
		pid := fmt.Sprintf("%d", os.Getpid())
		ioutil.WriteFile(pidfile, []byte(pid), 0600)
	}

	// cleanly disconnect the socket
	go handleShutdown(l, pidfile)

	// define git source to update from
	src := newSource(mustGitRootPath(c.String("gitrepo")),
		c.String("remote"), c.String("branch"))

	for {
		conn, err := l.Accept()
		if err != nil {
			panic(err)
		}

		go handleConnection(conn, src, stdout, stderr)
	}
}

func actionOnce(c *cli.Context) {

	var stdout io.Writer = os.Stdout
	var stderr io.Writer = os.Stderr
	if output := c.String("output"); output != "" {
		var f *os.File
		var err error
		if f, err = os.Create(output); err != nil {
			log.Fatalf("error opening output logfile %#v: %s",
				output, err.Error())
			return
		}
		stdout = f
		stderr = f
		log.SetOutput(f)
	}

	// define git source to update from
	src := newSource(mustGitRootPath(c.String("gitrepo")),
		c.String("remote"), c.String("branch"))

	if err := src.Context(stdout, stderr).HardPull(); err != io.EOF {
		log.Fatalf("error: %s", err.Error())
	}
}

func actionClient(c *cli.Context) {

	log.SetFlags(0)
	log.SetPrefix("gitsocket client: ")

	conn, err := net.Dial(address(c.String("conn")))
	if err != nil {
		log.Fatalf("connection error (%s)", err.Error())
		return
	}

	conn.Write([]byte("hello\n"))

	bufbytes := make([]byte, 1024)
	for {
		nr, err := conn.Read(bufbytes)

		// handle error
		if err == io.EOF {
			log.Printf("server connect closed")
			return
		} else if err != nil {
			log.Printf("error (%s)", err.Error())
			return
		}

		data := bufbytes[0:nr]
		fmt.Printf("%s", data)
	}
}

func createHookScript(filename, command string) (err error) {

	// template for git hook script
	tpl := template.Must(template.New("gitsocket").Parse(`#!/bin/sh
#
# An example hook script to prepare a packed repository for use over
# dumb transports.
#
# To enable this hook, rename this file to "post-checkout".
{{ .Command }}
`))

	f, err := os.Create(filename)
	if err != nil {
		log.Fatalf("error: %s", err)
		return
	}
	err = tpl.Execute(f, map[string]interface{}{
		"Command": command,
	})
	f.Close()
	if err != nil {
		return
	}

	err = os.Chmod(filename, 0777)
	return
}

func actionSetup(c *cli.Context) {

	// define git source to update from
	rootPath := mustGitRootPath(c.String("gitrepo"))
	filename := path.Join(rootPath, ".git/hooks/post-checkout")

	if command := c.String("command"); command != "" {
		// if file not exists, create the file
		if _, err := os.Stat(filename); os.IsNotExist(err) {
			createHookScript(filename, command)
			return
		} else if c.Bool("force") {
			createHookScript(filename, command)
			return
		}
		fmt.Println("post-checkout script already exists. If you want to " +
			"overwrite, please use the -f flag")
		os.Exit(1)
		return
	}

	// if file not exists, create the file
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		createHookScript(filename, "exec echo \"checkout completed.\"\n")
	}

	cmd := exec.Command("vi", filename)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stdout
	if err := cmd.Run(); err != nil {
		log.Fatalf("error: %s", err)
	}
}
<|endoftext|>


<commit_before>// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"io/ioutil"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/trillian/storage/storagepb"
	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/testing/protocmp"
)

// TestDBFormatNoChange ensures that the prefix, suffix, and protos stored in the database do not change.
// This test compares the output from dump_tree against a previously saved output.
func TestDBFormatNoChange(t *testing.T) {
	for _, tc := range []struct {
		desc string
		file string
		opts Options
	}{
		{
			desc: "tree_size: 96",
			file: "testdata/dump_tree_output_96",
			opts: Options{
				96, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 871",
			file: "testdata/dump_tree_output_871",
			opts: Options{
				871, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 1000",
			file: "testdata/dump_tree_output_1000",
			opts: Options{
				1000, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 1024",
			file: "testdata/dump_tree_output_1024",
			opts: Options{
				1024, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
	} {
		out := Main(tc.opts)
		saved, err := ioutil.ReadFile(tc.file)
		if err != nil {
			t.Fatalf("ReadFile(%v): %v", tc.file, err)
		}
		got := parseTiles(t, out)
		want := parseTiles(t, string(saved))
		if d := cmp.Diff(want, got, protocmp.Transform()); d != "" {
			t.Errorf("Diff(-want,+got):\n%s", d)
		}
	}
}

func parseTiles(t *testing.T, text string) []storagepb.SubtreeProto {
	t.Helper()
	parts := strings.Split(text, "\n\n")
	tiles := make([]storagepb.SubtreeProto, len(parts))
	for i, part := range parts {
		if err := prototext.Unmarshal([]byte(part), &tiles[i]); err != nil {
			t.Fatalf("Failed to unmarshal part %d: %v", i, err)
		}
	}
	return tiles
}
<commit_msg>Pass protos only by pointer (#2588)<commit_after>// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"io/ioutil"
	"strings"
	"testing"

	"github.com/google/go-cmp/cmp"
	"github.com/google/trillian/storage/storagepb"
	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/testing/protocmp"
)

// TestDBFormatNoChange ensures that the prefix, suffix, and protos stored in the database do not change.
// This test compares the output from dump_tree against a previously saved output.
func TestDBFormatNoChange(t *testing.T) {
	for _, tc := range []struct {
		desc string
		file string
		opts Options
	}{
		{
			desc: "tree_size: 96",
			file: "testdata/dump_tree_output_96",
			opts: Options{
				96, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 871",
			file: "testdata/dump_tree_output_871",
			opts: Options{
				871, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 1000",
			file: "testdata/dump_tree_output_1000",
			opts: Options{
				1000, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
		{
			desc: "tree_size: 1024",
			file: "testdata/dump_tree_output_1024",
			opts: Options{
				1024, 50,
				"Leaf %d",
				true, false, false, false, false, true, false, false,
			},
		},
	} {
		out := Main(tc.opts)
		saved, err := ioutil.ReadFile(tc.file)
		if err != nil {
			t.Fatalf("ReadFile(%v): %v", tc.file, err)
		}
		got := parseTiles(t, out)
		want := parseTiles(t, string(saved))
		if d := cmp.Diff(want, got, protocmp.Transform()); d != "" {
			t.Errorf("Diff(-want,+got):\n%s", d)
		}
	}
}

func parseTiles(t *testing.T, text string) []*storagepb.SubtreeProto {
	t.Helper()
	parts := strings.Split(text, "\n\n")
	tiles := make([]*storagepb.SubtreeProto, len(parts))
	for i, part := range parts {
		var tile storagepb.SubtreeProto
		if err := prototext.Unmarshal([]byte(part), &tile); err != nil {
			t.Fatalf("Failed to unmarshal part %d: %v", i, err)
		}
		tiles[i] = &tile
	}
	return tiles
}
<|endoftext|>


<commit_before>package widgets

import (
	"fmt"

	ui "github.com/gizak/termui"
)

type TextView struct {
	ui.Block
	inputStream <-chan string
	render      chan bool
	Text        []string // all the text
	TextOut     []string // text to be displayed
	TextFgColor ui.Attribute
	TextBgColor ui.Attribute
	padding     Padding
}

func NewTextView(lines <-chan string) *TextView {
	i := &TextView{
		Block:       *ui.NewBlock(),
		inputStream: lines,
		render:      make(chan bool),
		Text:        []string{},
		TextOut:     []string{},
		TextFgColor: ui.ThemeAttr("menu.text.fg"),
		TextBgColor: ui.ThemeAttr("menu.text.bg"),
		padding:     Padding{4, 2},
	}

	i.BorderFg = ui.ThemeAttr("menu.border.fg")
	i.BorderLabelFg = ui.ThemeAttr("menu.label.fg")

	i.Resize()

	i.readInputLoop()
	i.renderLoop()
	return i
}

func (i *TextView) Resize() {
	ui.Clear()
	i.Height = ui.TermHeight()
	i.Width = ui.TermWidth()
}

func (i *TextView) Buffer() ui.Buffer {

	var cell ui.Cell
	buf := i.Block.Buffer()

	x := i.Block.X + i.padding[0]
	y := i.Block.Y + i.padding[1]

	maxWidth := i.Width - (i.padding[0] * 2)

	for _, line := range i.TextOut {
		// truncate lines longer than maxWidth
		if len(line) > maxWidth {
			line = fmt.Sprintf("%s...", line[:maxWidth-3])
		}
		for _, ch := range line {
			cell = ui.Cell{Ch: ch, Fg: i.TextFgColor, Bg: i.TextBgColor}
			buf.Set(x, y, cell)
			x++
		}
		x = i.Block.X + i.padding[0]
		y++
	}
	return buf
}

func (i *TextView) renderLoop() {
	go func() {
		for range i.render {
			size := i.Height - (i.padding[1] * 2)
			if size > len(i.Text) {
				size = len(i.Text)
			}
			i.TextOut = i.Text[len(i.Text)-size:]

			ui.Render(i)
		}
	}()
}

func (i *TextView) readInputLoop() {
	go func() {
		for line := range i.inputStream {
			i.Text = append(i.Text, line)
			i.render <- true
		}
		close(i.render)
	}()
}
<commit_msg>line wrapping in log view, closes #106<commit_after>package widgets

import (
	ui "github.com/gizak/termui"
)

type TextView struct {
	ui.Block
	inputStream <-chan string
	render      chan bool
	Text        []string // all the text
	TextOut     []string // text to be displayed
	TextFgColor ui.Attribute
	TextBgColor ui.Attribute
	padding     Padding
}

func NewTextView(lines <-chan string) *TextView {
	t := &TextView{
		Block:       *ui.NewBlock(),
		inputStream: lines,
		render:      make(chan bool),
		Text:        []string{},
		TextOut:     []string{},
		TextFgColor: ui.ThemeAttr("menu.text.fg"),
		TextBgColor: ui.ThemeAttr("menu.text.bg"),
		padding:     Padding{4, 2},
	}

	t.BorderFg = ui.ThemeAttr("menu.border.fg")
	t.BorderLabelFg = ui.ThemeAttr("menu.label.fg")
	t.Height = ui.TermHeight()
	t.Width = ui.TermWidth()

	t.readInputLoop()
	t.renderLoop()
	return t
}

func (t *TextView) Resize() {
	ui.Clear()
	t.Height = ui.TermHeight()
	t.Width = ui.TermWidth()
	t.render <- true
}

func (t *TextView) Buffer() ui.Buffer {
	var cell ui.Cell
	buf := t.Block.Buffer()

	x := t.Block.X + t.padding[0]
	y := t.Block.Y + t.padding[1]

	for _, line := range t.TextOut {
		for _, ch := range line {
			cell = ui.Cell{Ch: ch, Fg: t.TextFgColor, Bg: t.TextBgColor}
			buf.Set(x, y, cell)
			x++
		}
		x = t.Block.X + t.padding[0]
		y++
	}
	return buf
}

func (t *TextView) renderLoop() {
	go func() {
		for range t.render {
			maxWidth := t.Width - (t.padding[0] * 2)
			height := t.Height - (t.padding[1] * 2)
			t.TextOut = []string{}
			for i := len(t.Text) - 1; i >= 0; i-- {
				lines := splitLine(t.Text[i], maxWidth)
				t.TextOut = append(lines, t.TextOut...)
				if len(t.TextOut) > height {
					t.TextOut = t.TextOut[:height]
					break
				}
			}
			ui.Render(t)
		}
	}()
}

func (t *TextView) readInputLoop() {
	go func() {
		for line := range t.inputStream {
			t.Text = append(t.Text, line)
			t.render <- true
		}
		close(t.render)
	}()
}

func splitLine(line string, lineSize int) []string {
	var lines []string
	for {
		if len(line) < lineSize {
			lines = append(lines, line)
			return lines
		}
		lines = append(lines, line[:lineSize])
		line = line[lineSize:]
	}
	return lines
}
<|endoftext|>


<commit_before>package p

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// Prolog lexer.
var Prolog = internal.Register(MustNewLexer(
	&Config{
		Name:      "Prolog",
		Aliases:   []string{"prolog"},
		Filenames: []string{"*.ecl", "*.prolog", "*.pro", "*.pl"},
		MimeTypes: []string{"text/x-prolog"},
	},
	Rules{
		"root": {
			{`^#.*`, CommentSingle, nil},
			{`/\*`, CommentMultiline, Push("nested-comment")},
			{`%.*`, CommentSingle, nil},
			{`0\'.`, LiteralStringChar, nil},
			{`0b[01]+`, LiteralNumberBin, nil},
			{`0o[0-7]+`, LiteralNumberOct, nil},
			{`0x[0-9a-fA-F]+`, LiteralNumberHex, nil},
			{`\d\d?\'[a-zA-Z0-9]+`, LiteralNumberInteger, nil},
			{`(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?`, LiteralNumberFloat, nil},
			{`\d+`, LiteralNumberInteger, nil},
			{`[\[\](){}|.,;!]`, Punctuation, nil},
			{`:-|-->`, Punctuation, nil},
			{`"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\[0-7]+\\|\\["\nabcefnrstv]|[^\\"])*"`, LiteralStringDouble, nil},
			{`'(?:''|[^'])*'`, LiteralStringAtom, nil},
			{`is\b`, Operator, nil},
			{`(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])`, Operator, nil},
			{`(mod|div|not)\b`, Operator, nil},
			{`_`, Keyword, nil},
			{`([a-z]+)(:)`, ByGroups(NameNamespace, Punctuation), nil},
			{`([a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*)(\s*)(:-|-->)`, ByGroups(NameFunction, Text, Operator), nil},
			{`([a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*)(\s*)(\()`, ByGroups(NameFunction, Text, Punctuation), nil},
			{`[a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*`, LiteralStringAtom, nil},
			{`[#&*+\-./:<=>?@\\^~¡-¿‐-〿]+`, LiteralStringAtom, nil},
			{`[A-Z_]\w*`, NameVariable, nil},
			{`\s+|[ --￯]`, Text, nil},
		},
		"nested-comment": {
			{`\*/`, CommentMultiline, Pop(1)},
			{`/\*`, CommentMultiline, Push()},
			{`[^*/]+`, CommentMultiline, nil},
			{`[*/]`, CommentMultiline, nil},
		},
	},
))
<commit_msg>Removed # as a comment character<commit_after>package p

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// Prolog lexer.
var Prolog = internal.Register(MustNewLexer(
	&Config{
		Name:      "Prolog",
		Aliases:   []string{"prolog"},
		Filenames: []string{"*.ecl", "*.prolog", "*.pro", "*.pl"},
		MimeTypes: []string{"text/x-prolog"},
	},
	Rules{
		"root": {
			{`/\*`, CommentMultiline, Push("nested-comment")},
			{`%.*`, CommentSingle, nil},
			{`0\'.`, LiteralStringChar, nil},
			{`0b[01]+`, LiteralNumberBin, nil},
			{`0o[0-7]+`, LiteralNumberOct, nil},
			{`0x[0-9a-fA-F]+`, LiteralNumberHex, nil},
			{`\d\d?\'[a-zA-Z0-9]+`, LiteralNumberInteger, nil},
			{`(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?`, LiteralNumberFloat, nil},
			{`\d+`, LiteralNumberInteger, nil},
			{`[\[\](){}|.,;!]`, Punctuation, nil},
			{`:-|-->`, Punctuation, nil},
			{`"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\[0-7]+\\|\\["\nabcefnrstv]|[^\\"])*"`, LiteralStringDouble, nil},
			{`'(?:''|[^'])*'`, LiteralStringAtom, nil},
			{`is\b`, Operator, nil},
			{`(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])`, Operator, nil},
			{`(mod|div|not)\b`, Operator, nil},
			{`_`, Keyword, nil},
			{`([a-z]+)(:)`, ByGroups(NameNamespace, Punctuation), nil},
			{`([a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*)(\s*)(:-|-->)`, ByGroups(NameFunction, Text, Operator), nil},
			{`([a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*)(\s*)(\()`, ByGroups(NameFunction, Text, Punctuation), nil},
			{`[a-zÀ-῿぀-퟿-￯][\w$À-῿぀-퟿-￯]*`, LiteralStringAtom, nil},
			{`[#&*+\-./:<=>?@\\^~¡-¿‐-〿]+`, LiteralStringAtom, nil},
			{`[A-Z_]\w*`, NameVariable, nil},
			{`\s+|[ --￯]`, Text, nil},
		},
		"nested-comment": {
			{`\*/`, CommentMultiline, Pop(1)},
			{`/\*`, CommentMultiline, Push()},
			{`[^*/]+`, CommentMultiline, nil},
			{`[*/]`, CommentMultiline, nil},
		},
	},
))
<|endoftext|>


<commit_before>package peco

import (
	"io"
	"io/ioutil"
	"os"
	"reflect"
	"testing"
)

func TestIssue212_SanityCheck(t *testing.T) {
	ctx := NewCtx(nil)

	// Check if the default layout type is honored */
	// This the main issue on 212, but while we're at it, we're just
	// going to check that all the default values are as expected
	if ctx.config.Layout != "top-down" {
		t.Errorf("Default layout type should be 'top-down', got '%s'", ctx.config.Layout)
	}

	if len(ctx.config.Keymap) != 0 {
		t.Errorf("Default keymap should be empty, but got '%#v'", ctx.config.Keymap)
	}

	if ctx.config.InitialMatcher != IgnoreCaseMatch {
		t.Errorf("Default matcher should IgnoreCaseMatch, but got '%s'", ctx.config.InitialMatcher)
	}

	if !reflect.DeepEqual(ctx.config.Style, NewStyleSet()) {
		t.Errorf("Default style should was not the same as NewStyleSet()")
	}

	if ctx.config.Prompt != "QUERY>" {
		t.Errorf("Default prompt should be 'QUERY>', but got '%s'", ctx.config.Prompt)
	}

	// Okay, this time create a dummy config file, and read that in
	f, err := ioutil.TempFile("", "peco-test-config")
	if err != nil {
		t.Errorf("Failed to create temporary config file: %s", err)
		return
	}
	fn := f.Name()
	defer os.Remove(fn)

	io.WriteString(f, `{
    "Layout": "bottom-up"
}`)
	f.Close()

	ctx = NewCtx(nil)
	if err := ctx.ReadConfig(fn); err != nil {
		t.Errorf("Failed to read config: %s", err)
		return
	}
	if ctx.config.Layout != "bottom-up" {
		t.Errorf("Default layout type should be 'bottom-up', got '%s'", ctx.config.Layout)
	}
}

// Satisfy CtxOptions interface
type issue212DummyConfig struct {
	layout string
}

func (i issue212DummyConfig) BufferSize() int     { return 0 }
func (i issue212DummyConfig) InitialIndex() int   { return 0 }
func (i issue212DummyConfig) EnableNullSep() bool { return false }
func (i issue212DummyConfig) LayoutType() string  { return i.layout }
func TestIssue212_ActualProblem(t *testing.T) {
	ctx := NewCtx(issue212DummyConfig{layout: ""})
	if ctx.layoutType != "top-down" {
		t.Errorf("event if CtxOption returns an empty string, we should still get the default top-down layout")
	}
}
<commit_msg>fix test<commit_after>package peco

import (
	"io"
	"io/ioutil"
	"os"
	"reflect"
	"testing"
)

func TestIssue212_SanityCheck(t *testing.T) {
	ctx := NewCtx(nil)

	// Check if the default layout type is honored */
	// This the main issue on 212, but while we're at it, we're just
	// going to check that all the default values are as expected
	if ctx.config.Layout != "top-down" {
		t.Errorf("Default layout type should be 'top-down', got '%s'", ctx.config.Layout)
	}

	if len(ctx.config.Keymap) != 0 {
		t.Errorf("Default keymap should be empty, but got '%#v'", ctx.config.Keymap)
	}

	if ctx.config.InitialMatcher != IgnoreCaseMatch {
		t.Errorf("Default matcher should IgnoreCaseMatch, but got '%s'", ctx.config.InitialMatcher)
	}

	if !reflect.DeepEqual(ctx.config.Style, NewStyleSet()) {
		t.Errorf("Default style should was not the same as NewStyleSet()")
	}

	if ctx.config.Prompt != "QUERY>" {
		t.Errorf("Default prompt should be 'QUERY>', but got '%s'", ctx.config.Prompt)
	}

	// Okay, this time create a dummy config file, and read that in
	f, err := ioutil.TempFile("", "peco-test-config")
	if err != nil {
		t.Errorf("Failed to create temporary config file: %s", err)
		return
	}
	fn := f.Name()
	defer os.Remove(fn)

	io.WriteString(f, `{
    "Layout": "bottom-up"
}`)
	f.Close()

	ctx = NewCtx(nil)
	if err := ctx.ReadConfig(fn); err != nil {
		t.Errorf("Failed to read config: %s", err)
		return
	}
	if ctx.config.Layout != "bottom-up" {
		t.Errorf("Default layout type should be 'bottom-up', got '%s'", ctx.config.Layout)
	}
}

// Satisfy CtxOptions interface
type issue212DummyConfig struct {
	layout string
}

func (i issue212DummyConfig) BufferSize() int     { return 0 }
func (i issue212DummyConfig) InitialIndex() int   { return 0 }
func (i issue212DummyConfig) EnableNullSep() bool { return false }
func (i issue212DummyConfig) LayoutType() string  { return i.layout }
func TestIssue212_ActualProblem(t *testing.T) {
	ctx := NewCtx(issue212DummyConfig{layout: ""})
	if ctx.layoutType != "" {
		t.Errorf("CtxOption should be return an empty string but '%s'", ctx.layoutType)
	}
}
<|endoftext|>


<commit_before>// Package transpiler handles the conversion between the Clang AST and the Go
// AST.
package transpiler

import (
	"errors"
	"fmt"
	goast "go/ast"
	"go/parser"
	"go/token"

	"github.com/elliotchance/c2go/ast"
	"github.com/elliotchance/c2go/program"
	"github.com/elliotchance/c2go/util"
)

// TranspileAST iterates through the Clang AST and builds a Go AST
func TranspileAST(fileName, packageName string, p *program.Program, root ast.Node) error {
	// Start by parsing an empty file.
	p.FileSet = token.NewFileSet()
	packageSignature := fmt.Sprintf("package %v", packageName)
	f, err := parser.ParseFile(p.FileSet, fileName, packageSignature, 0)
	p.File = f

	if err != nil {
		return err
	}

	// Now begin building the Go AST.
	err = transpileToNode(root, p)

	// Now we need to build the __init() function. This sets up certain state
	// and variables that the runtime expects to be ready.
	p.File.Decls = append(p.File.Decls, &goast.FuncDecl{
		Name: util.NewIdent("__init"),
		Type: util.NewFuncType(&goast.FieldList{}, ""),
		Body: &goast.BlockStmt{
			List: p.StartupStatements(),
		},
	})

	// Add the imports after everything else so we can ensure that they are all
	// placed at the top.
	// A valid Lparen position (Lparen.IsValid()) indicated a parenthesized
	// declaration. According to the function definition, line should be
	// greater than 0.
	importDecl := &goast.GenDecl{
		Tok:    token.IMPORT,
		Lparen: 1,
	}

	for _, quotedImportPath := range p.Imports() {
		importSpec := &goast.ImportSpec{
			Path: &goast.BasicLit{
				Kind:  token.IMPORT,
				Value: quotedImportPath,
			},
		}

		importDecl.Specs = append(importDecl.Specs, importSpec)
	}

	p.File.Decls = append([]goast.Decl{importDecl}, p.File.Decls...)

	return err
}

func transpileToExpr(node ast.Node, p *program.Program) (
	expr goast.Expr,
	exprType string,
	preStmts []goast.Stmt,
	postStmts []goast.Stmt,
	err error) {
	if node == nil {
		panic(node)
	}

	switch n := node.(type) {
	case *ast.StringLiteral:
		expr = transpileStringLiteral(n)
		exprType = "const char *"

	case *ast.FloatingLiteral:
		expr = transpileFloatingLiteral(n)
		exprType = "double"

	case *ast.PredefinedExpr:
		expr, exprType, err = transpilePredefinedExpr(n, p)

	case *ast.ConditionalOperator:
		expr, exprType, preStmts, postStmts, err = transpileConditionalOperator(n, p)

	case *ast.ArraySubscriptExpr:
		expr, exprType, preStmts, postStmts, err = transpileArraySubscriptExpr(n, p)

	case *ast.BinaryOperator:
		expr, exprType, preStmts, postStmts, err = transpileBinaryOperator(n, p)

	case *ast.UnaryOperator:
		expr, exprType, preStmts, postStmts, err = transpileUnaryOperator(n, p)

	case *ast.MemberExpr:
		expr, exprType, preStmts, postStmts, err = transpileMemberExpr(n, p)

	case *ast.ImplicitCastExpr:
		expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children[0], p)

	case *ast.DeclRefExpr:
		expr, exprType, err = transpileDeclRefExpr(n, p)

	case *ast.IntegerLiteral:
		expr, exprType, err = transpileIntegerLiteral(n), "int", nil

	case *ast.ParenExpr:
		expr, exprType, preStmts, postStmts, err = transpileParenExpr(n, p)

	case *ast.CStyleCastExpr:
		expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children[0], p)

	case *ast.CharacterLiteral:
		expr, exprType, err = transpileCharacterLiteral(n), "char", nil

	case *ast.CallExpr:
		expr, exprType, preStmts, postStmts, err = transpileCallExpr(n, p)

	case *ast.CompoundAssignOperator:
		return transpileCompoundAssignOperator(n, p)

	case *ast.UnaryExprOrTypeTraitExpr:
		return transpileUnaryExprOrTypeTraitExpr(n, p)

	default:
		p.AddMessage(ast.GenerateWarningMessage(errors.New("cannot transpile to expr"), node))
		expr = util.NewNil()
	}

	// Real return is through named arguments.
	return
}

func transpileToStmts(node ast.Node, p *program.Program) ([]goast.Stmt, error) {
	if node == nil {
		return nil, nil
	}

	switch n := node.(type) {
	case *ast.DeclStmt:
		stmts, preStmts, postStmts, err := transpileDeclStmt(n, p)
		stmts = append(preStmts, stmts...)
		stmts = append(stmts, postStmts...)
		return stmts, err
	}

	stmt, preStmts, postStmts, err := transpileToStmt(node, p)
	stmts := append(preStmts, stmt)
	stmts = append(stmts, postStmts...)
	return stmts, err
}

func transpileToStmt(node ast.Node, p *program.Program) (
	stmt goast.Stmt, preStmts []goast.Stmt, postStmts []goast.Stmt, err error) {
	if node == nil {
		return
	}

	var expr goast.Expr

	switch n := node.(type) {
	case *ast.DefaultStmt:
		stmt, err = transpileDefaultStmt(n, p)
		return

	case *ast.CaseStmt:
		stmt, preStmts, postStmts, err = transpileCaseStmt(n, p)
		return

	case *ast.SwitchStmt:
		stmt, preStmts, postStmts, err = transpileSwitchStmt(n, p)
		return

	case *ast.BreakStmt:
		stmt = &goast.BranchStmt{
			Tok: token.BREAK,
		}
		return

	case *ast.WhileStmt:
		return transpileWhileStmt(n, p)

	case *ast.DoStmt:
		return transpileDoStmt(n, p)

	case *ast.ContinueStmt:
		stmt, err = transpileContinueStmt(n, p)
		return

	case *ast.IfStmt:
		return transpileIfStmt(n, p)

	case *ast.ForStmt:
		return transpileForStmt(n, p)

	case *ast.ReturnStmt:
		return transpileReturnStmt(n, p)

	case *ast.CompoundStmt:
		stmt, preStmts, postStmts, err = transpileCompoundStmt(n, p)
		return

	case *ast.BinaryOperator:
		if n.Operator == "," {
			stmt, preStmts, err = transpileBinaryOperatorComma(n, p)
			return
		}
	}

	// We do not care about the return type.
	expr, _, preStmts, postStmts, err = transpileToExpr(node, p)
	if err != nil {
		return
	}

	stmt = util.NewExprStmt(expr)

	return
}

func transpileToNode(node ast.Node, p *program.Program) error {
	switch n := node.(type) {
	case *ast.TranslationUnitDecl:
		for _, c := range n.Children {
			transpileToNode(c, p)
		}

	case *ast.FunctionDecl:
		err := transpileFunctionDecl(n, p)
		if err != nil {
			return err
		}

	case *ast.TypedefDecl:
		return transpileTypedefDecl(p, n)

	case *ast.RecordDecl:
		return transpileRecordDecl(p, n)

	case *ast.VarDecl:
		transpileVarDecl(p, n)
		return nil

	case *ast.EnumDecl:
		transpileEnumDecl(p, n)
		return nil

	default:
		panic(fmt.Sprintf("cannot transpile to node: %#v", node))
	}

	return nil
}

func transpileStmts(nodes []ast.Node, p *program.Program) ([]goast.Stmt, error) {
	preStmts := []goast.Stmt{}
	postStmts := []goast.Stmt{}
	stmts := []goast.Stmt{}

	for _, s := range nodes {
		if s != nil {
			a, newPre, newPost, err := transpileToStmt(s, p)
			if err != nil {
				return nil, err
			}

			preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)

			stmts = append(stmts, a)
		}
	}

	return stmts, nil
}
<commit_msg>Revert "Implement parenthesized import declaration"<commit_after>// Package transpiler handles the conversion between the Clang AST and the Go
// AST.
package transpiler

import (
	"errors"
	"fmt"
	goast "go/ast"
	"go/parser"
	"go/token"

	"github.com/elliotchance/c2go/ast"
	"github.com/elliotchance/c2go/program"
	"github.com/elliotchance/c2go/util"
)

// TranspileAST iterates through the Clang AST and builds a Go AST
func TranspileAST(fileName, packageName string, p *program.Program, root ast.Node) error {
	// Start by parsing an empty file.
	p.FileSet = token.NewFileSet()
	packageSignature := fmt.Sprintf("package %v", packageName)
	f, err := parser.ParseFile(p.FileSet, fileName, packageSignature, 0)
	p.File = f

	if err != nil {
		return err
	}

	// Now begin building the Go AST.
	err = transpileToNode(root, p)

	// Now we need to build the __init() function. This sets up certain state
	// and variables that the runtime expects to be ready.
	p.File.Decls = append(p.File.Decls, &goast.FuncDecl{
		Name: util.NewIdent("__init"),
		Type: util.NewFuncType(&goast.FieldList{}, ""),
		Body: &goast.BlockStmt{
			List: p.StartupStatements(),
		},
	})

	// Add the imports after everything else so we can ensure that they are all
	// placed at the top.
	for _, quotedImportPath := range p.Imports() {
		importSpec := &goast.ImportSpec{
			Path: &goast.BasicLit{
				Kind:  token.IMPORT,
				Value: quotedImportPath,
			},
		}
		importDecl := &goast.GenDecl{
			Tok: token.IMPORT,
		}

		importDecl.Specs = append(importDecl.Specs, importSpec)
		p.File.Decls = append([]goast.Decl{importDecl}, p.File.Decls...)
	}

	return err
}

func transpileToExpr(node ast.Node, p *program.Program) (
	expr goast.Expr,
	exprType string,
	preStmts []goast.Stmt,
	postStmts []goast.Stmt,
	err error) {
	if node == nil {
		panic(node)
	}

	switch n := node.(type) {
	case *ast.StringLiteral:
		expr = transpileStringLiteral(n)
		exprType = "const char *"

	case *ast.FloatingLiteral:
		expr = transpileFloatingLiteral(n)
		exprType = "double"

	case *ast.PredefinedExpr:
		expr, exprType, err = transpilePredefinedExpr(n, p)

	case *ast.ConditionalOperator:
		expr, exprType, preStmts, postStmts, err = transpileConditionalOperator(n, p)

	case *ast.ArraySubscriptExpr:
		expr, exprType, preStmts, postStmts, err = transpileArraySubscriptExpr(n, p)

	case *ast.BinaryOperator:
		expr, exprType, preStmts, postStmts, err = transpileBinaryOperator(n, p)

	case *ast.UnaryOperator:
		expr, exprType, preStmts, postStmts, err = transpileUnaryOperator(n, p)

	case *ast.MemberExpr:
		expr, exprType, preStmts, postStmts, err = transpileMemberExpr(n, p)

	case *ast.ImplicitCastExpr:
		expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children[0], p)

	case *ast.DeclRefExpr:
		expr, exprType, err = transpileDeclRefExpr(n, p)

	case *ast.IntegerLiteral:
		expr, exprType, err = transpileIntegerLiteral(n), "int", nil

	case *ast.ParenExpr:
		expr, exprType, preStmts, postStmts, err = transpileParenExpr(n, p)

	case *ast.CStyleCastExpr:
		expr, exprType, preStmts, postStmts, err = transpileToExpr(n.Children[0], p)

	case *ast.CharacterLiteral:
		expr, exprType, err = transpileCharacterLiteral(n), "char", nil

	case *ast.CallExpr:
		expr, exprType, preStmts, postStmts, err = transpileCallExpr(n, p)

	case *ast.CompoundAssignOperator:
		return transpileCompoundAssignOperator(n, p)

	case *ast.UnaryExprOrTypeTraitExpr:
		return transpileUnaryExprOrTypeTraitExpr(n, p)

	default:
		p.AddMessage(ast.GenerateWarningMessage(errors.New("cannot transpile to expr"), node))
		expr = util.NewNil()
	}

	// Real return is through named arguments.
	return
}

func transpileToStmts(node ast.Node, p *program.Program) ([]goast.Stmt, error) {
	if node == nil {
		return nil, nil
	}

	switch n := node.(type) {
	case *ast.DeclStmt:
		stmts, preStmts, postStmts, err := transpileDeclStmt(n, p)
		stmts = append(preStmts, stmts...)
		stmts = append(stmts, postStmts...)
		return stmts, err
	}

	stmt, preStmts, postStmts, err := transpileToStmt(node, p)
	stmts := append(preStmts, stmt)
	stmts = append(stmts, postStmts...)
	return stmts, err
}

func transpileToStmt(node ast.Node, p *program.Program) (
	stmt goast.Stmt, preStmts []goast.Stmt, postStmts []goast.Stmt, err error) {
	if node == nil {
		return
	}

	var expr goast.Expr

	switch n := node.(type) {
	case *ast.DefaultStmt:
		stmt, err = transpileDefaultStmt(n, p)
		return

	case *ast.CaseStmt:
		stmt, preStmts, postStmts, err = transpileCaseStmt(n, p)
		return

	case *ast.SwitchStmt:
		stmt, preStmts, postStmts, err = transpileSwitchStmt(n, p)
		return

	case *ast.BreakStmt:
		stmt = &goast.BranchStmt{
			Tok: token.BREAK,
		}
		return

	case *ast.WhileStmt:
		return transpileWhileStmt(n, p)

	case *ast.DoStmt:
		return transpileDoStmt(n, p)

	case *ast.ContinueStmt:
		stmt, err = transpileContinueStmt(n, p)
		return

	case *ast.IfStmt:
		return transpileIfStmt(n, p)

	case *ast.ForStmt:
		return transpileForStmt(n, p)

	case *ast.ReturnStmt:
		return transpileReturnStmt(n, p)

	case *ast.CompoundStmt:
		stmt, preStmts, postStmts, err = transpileCompoundStmt(n, p)
		return

	case *ast.BinaryOperator:
		if n.Operator == "," {
			stmt, preStmts, err = transpileBinaryOperatorComma(n, p)
			return
		}
	}

	// We do not care about the return type.
	expr, _, preStmts, postStmts, err = transpileToExpr(node, p)
	if err != nil {
		return
	}

	stmt = util.NewExprStmt(expr)

	return
}

func transpileToNode(node ast.Node, p *program.Program) error {
	switch n := node.(type) {
	case *ast.TranslationUnitDecl:
		for _, c := range n.Children {
			transpileToNode(c, p)
		}

	case *ast.FunctionDecl:
		err := transpileFunctionDecl(n, p)
		if err != nil {
			return err
		}

	case *ast.TypedefDecl:
		return transpileTypedefDecl(p, n)

	case *ast.RecordDecl:
		return transpileRecordDecl(p, n)

	case *ast.VarDecl:
		transpileVarDecl(p, n)
		return nil

	case *ast.EnumDecl:
		transpileEnumDecl(p, n)
		return nil

	default:
		panic(fmt.Sprintf("cannot transpile to node: %#v", node))
	}

	return nil
}

func transpileStmts(nodes []ast.Node, p *program.Program) ([]goast.Stmt, error) {
	preStmts := []goast.Stmt{}
	postStmts := []goast.Stmt{}
	stmts := []goast.Stmt{}

	for _, s := range nodes {
		if s != nil {
			a, newPre, newPost, err := transpileToStmt(s, p)
			if err != nil {
				return nil, err
			}

			preStmts, postStmts = combinePreAndPostStmts(preStmts, postStmts, newPre, newPost)

			stmts = append(stmts, a)
		}
	}

	return stmts, nil
}
<|endoftext|>


<commit_before>package sorter

// InsertionSort sorts the given array according to insertion sort algoritm
func InsertionSort(arr []int) []int {
	var key int
	var j int

	for i := 1; i < len(arr); i++ {
		key = arr[i]
		j = i - 1
		for j >= 0 && arr[j] > key {
			arr[j+1] = arr[j]
			j--
		}
		arr[j+1] = key
	}

	return arr
}

/////// Insertion Sort Recursively ////////

// RecursiveInsertionSort
func RecursiveInsertionSort(arr []int) []int {
	lenArr := len(arr)
	if lenArr < 2 {
		return arr
	}
	newArr := arr[:lenArr-1]
	r := RecursiveInsertionSort(newArr)
	lastItem := arr[lenArr-1]

	ins := Insert(r, lastItem)

	return ins
}

// Insert
func Insert(arr []int, key int) []int {
	newArr := make([]int, len(arr)+1)
	i := len(arr) - 1
	for i >= 0 && arr[i] > key {
		newArr[i+1] = arr[i]
		i--
	}
	newArr[i+1] = key

	for i >= 0 {
		newArr[i] = arr[i]
		i--
	}

	return newArr
}
<commit_msg>insertion: add comment for insertion sorts<commit_after>package sorter

// InsertionSort sorts the given array according to insertion sort algorithm
func InsertionSort(arr []int) []int {
	var key int
	var j int

	for i := 1; i < len(arr); i++ {
		key = arr[i]
		j = i - 1
		for j >= 0 && arr[j] > key {
			arr[j+1] = arr[j]
			j--
		}
		arr[j+1] = key
	}

	return arr
}

/////// Insertion Sort Recursively ////////

// RecursiveInsertionSort sorts the array recursively
func RecursiveInsertionSort(arr []int) []int {
	lenArr := len(arr)
	if lenArr < 2 {
		return arr
	}
	newArr := arr[:lenArr-1]
	r := RecursiveInsertionSort(newArr)
	lastItem := arr[lenArr-1]

	ins := Insert(r, lastItem)

	return ins
}

// Insert inserts the array
func Insert(arr []int, key int) []int {
	newArr := make([]int, len(arr)+1)
	i := len(arr) - 1
	for i >= 0 && arr[i] > key {
		newArr[i+1] = arr[i]
		i--
	}
	newArr[i+1] = key

	for i >= 0 {
		newArr[i] = arr[i]
		i--
	}

	return newArr
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"os"
	"strconv"
)

func main() {
	var (
		ClientOV    *ov.OVClient
		scp_name    = "ScopeTest"
		new_scope   = "new-scope"
		upd_scope   = "update-scope"
		eth_network = "Auto-ethernet_network"
	)
	apiversion, _ := strconv.Atoi(os.Getenv("ONEVIEW_APIVERSION"))

	ovc := ClientOV.NewOVClient(
		os.Getenv("ONEVIEW_OV_USER"),
		os.Getenv("ONEVIEW_OV_PASSWORD"),
		os.Getenv("ONEVIEW_OV_DOMAIN"),
		os.Getenv("ONEVIEW_OV_ENDPOINT"),
		false,
		apiversion,
		"*")
	scope_test := ov.Scope{Name: scp_name, Description: "Test from script", Type: "ScopeV3"}

	er_test := ovc.CreateScope(scope_test)

	if er_test != nil{
		fmt.Println("Error Creating Scope: ", er_test)
	}

	fmt.Println("#................... Scope by Name ...............#")
	scp, scperr := ovc.GetScopeByName(scp_name)
	if scperr != nil {
		fmt.Println(scperr)
	}
	fmt.Println(scp)

	sort := "name:desc"
	scp_list, err := ovc.GetScopes("", "", "", "", sort)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("# ................... Scopes List .................#")
	for i := 0; i < len(scp_list.Members); i++ {
		fmt.Println(scp_list.Members[i].Name)
	}
	eth_uri, err := ovc.GetEthernetNetworkByName(eth_network)
	if err != nil {
		fmt.Println(err)
	}

	initialScopeUris := &[]utils.Nstring{(scp.URI)}
	addedResourceUris := &[]utils.Nstring{(eth_uri.URI)}
	scope := ov.Scope{Name: new_scope, Description: "Test from script", Type: "ScopeV3", InitialScopeUris: *initialScopeUris, AddedResourceUris: *addedResourceUris}

	er := ovc.CreateScope(scope)
	if er != nil {
		fmt.Println("............... Scope Creation Failed:", er)
	} else {
		fmt.Println("# ................... Scope Created Successfully.................#")
	}

	new_scp, err := ovc.GetScopeByName(new_scope)
	if err != nil {
		fmt.Println(err)
	} else {
		new_scp.Name = upd_scope
		err = ovc.UpdateScope(new_scp)

		if err != nil {
			fmt.Println("#.................... Scope Updation failed ...........#")
			panic(err)
		} else {
			fmt.Println("#.................... Scope after Updating ...........#")
		}
	}
	up_list, err := ovc.GetScopes("", "", "", "", sort)
	for i := 0; i < len(up_list.Members); i++ {
		fmt.Println(up_list.Members[i].Name)
	}

	err = ovc.DeleteScope(upd_scope)
	if err != nil {
		panic(err)
	} else {
		fmt.Println("#...................... Deleted Scope Successfully .....#")
	}
	scp_list, err = ovc.GetScopes("", "", "", "", sort)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("# ................... Scopes List .................#")
	for i := 0; i < len(scp_list.Members); i++ {
		fmt.Println(scp_list.Members[i].Name)
	}
}
<commit_msg>gofmt fixes<commit_after>package main

import (
	"fmt"
	"github.com/HewlettPackard/oneview-golang/ov"
	"github.com/HewlettPackard/oneview-golang/utils"
	"os"
	"strconv"
)

func main() {
	var (
		ClientOV    *ov.OVClient
		scp_name    = "ScopeTest"
		new_scope   = "new-scope"
		upd_scope   = "update-scope"
		eth_network = "Auto-ethernet_network"
	)
	apiversion, _ := strconv.Atoi(os.Getenv("ONEVIEW_APIVERSION"))

	ovc := ClientOV.NewOVClient(
		os.Getenv("ONEVIEW_OV_USER"),
		os.Getenv("ONEVIEW_OV_PASSWORD"),
		os.Getenv("ONEVIEW_OV_DOMAIN"),
		os.Getenv("ONEVIEW_OV_ENDPOINT"),
		false,
		apiversion,
		"*")
	scope_test := ov.Scope{Name: scp_name, Description: "Test from script", Type: "ScopeV3"}

	er_test := ovc.CreateScope(scope_test)

	if er_test != nil {
		fmt.Println("Error Creating Scope: ", er_test)
	}

	fmt.Println("#................... Scope by Name ...............#")
	scp, scperr := ovc.GetScopeByName(scp_name)
	if scperr != nil {
		fmt.Println(scperr)
	}
	fmt.Println(scp)

	sort := "name:desc"
	scp_list, err := ovc.GetScopes("", "", "", "", sort)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("# ................... Scopes List .................#")
	for i := 0; i < len(scp_list.Members); i++ {
		fmt.Println(scp_list.Members[i].Name)
	}
	eth_uri, err := ovc.GetEthernetNetworkByName(eth_network)
	if err != nil {
		fmt.Println(err)
	}

	initialScopeUris := &[]utils.Nstring{(scp.URI)}
	addedResourceUris := &[]utils.Nstring{(eth_uri.URI)}
	scope := ov.Scope{Name: new_scope, Description: "Test from script", Type: "ScopeV3", InitialScopeUris: *initialScopeUris, AddedResourceUris: *addedResourceUris}

	er := ovc.CreateScope(scope)
	if er != nil {
		fmt.Println("............... Scope Creation Failed:", er)
	} else {
		fmt.Println("# ................... Scope Created Successfully.................#")
	}

	new_scp, err := ovc.GetScopeByName(new_scope)
	if err != nil {
		fmt.Println(err)
	} else {
		new_scp.Name = upd_scope
		err = ovc.UpdateScope(new_scp)

		if err != nil {
			fmt.Println("#.................... Scope Updation failed ...........#")
			panic(err)
		} else {
			fmt.Println("#.................... Scope after Updating ...........#")
		}
	}
	up_list, err := ovc.GetScopes("", "", "", "", sort)
	for i := 0; i < len(up_list.Members); i++ {
		fmt.Println(up_list.Members[i].Name)
	}

	err = ovc.DeleteScope(upd_scope)
	if err != nil {
		panic(err)
	} else {
		fmt.Println("#...................... Deleted Scope Successfully .....#")
	}
	scp_list, err = ovc.GetScopes("", "", "", "", sort)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("# ................... Scopes List .................#")
	for i := 0; i < len(scp_list.Members); i++ {
		fmt.Println(scp_list.Members[i].Name)
	}
}
<|endoftext|>


<commit_before>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package net

import (
	"os"
	"runtime"
	"strings"
	"testing"
)

// testableNetwork reports whether network is testable on the current
// platform configuration.
func testableNetwork(network string) bool {
	ss := strings.Split(network, ":")
	switch ss[0] {
	case "ip+nopriv":
		switch runtime.GOOS {
		case "nacl":
			return false
		}
	case "ip", "ip4", "ip6":
		switch runtime.GOOS {
		case "nacl", "plan9":
			return false
		default:
			if os.Getuid() != 0 {
				return false
			}
		}
	case "unix", "unixgram":
		switch runtime.GOOS {
		case "nacl", "plan9", "windows":
			return false
		}
		// iOS does not support unix, unixgram.
		if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
			return false
		}
	case "unixpacket":
		switch runtime.GOOS {
		case "android", "darwin", "nacl", "plan9", "windows":
			fallthrough
		case "freebsd": // FreeBSD 8 and below don't support unixpacket
			return false
		}
	}
	switch ss[0] {
	case "tcp4", "udp4", "ip4":
		if !supportsIPv4 {
			return false
		}
	case "tcp6", "udp6", "ip6":
		if !supportsIPv6 {
			return false
		}
	}
	return true
}

// testableAddress reports whether address of network is testable on
// the current platform configuration.
func testableAddress(network, address string) bool {
	switch ss := strings.Split(network, ":"); ss[0] {
	case "unix", "unixgram", "unixpacket":
		// Abstract unix domain sockets, a Linux-ism.
		if address[0] == '@' && runtime.GOOS != "linux" {
			return false
		}
	}
	return true
}

// testableListenArgs reports whether arguments are testable on the
// current platform configuration.
func testableListenArgs(network, address, client string) bool {
	if !testableNetwork(network) || !testableAddress(network, address) {
		return false
	}

	var err error
	var addr Addr
	switch ss := strings.Split(network, ":"); ss[0] {
	case "tcp", "tcp4", "tcp6":
		addr, err = ResolveTCPAddr("tcp", address)
	case "udp", "udp4", "udp6":
		addr, err = ResolveUDPAddr("udp", address)
	case "ip", "ip4", "ip6":
		addr, err = ResolveIPAddr("ip", address)
	default:
		return true
	}
	if err != nil {
		return false
	}
	var ip IP
	var wildcard bool
	switch addr := addr.(type) {
	case *TCPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	case *UDPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	case *IPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	}

	// Test wildcard IP addresses.
	if wildcard && (testing.Short() || !*testExternal) {
		return false
	}

	// Test functionality of IPv4 communication using AF_INET and
	// IPv6 communication using AF_INET6 sockets.
	if !supportsIPv4 && ip.To4() != nil {
		return false
	}
	if !supportsIPv6 && ip.To16() != nil && ip.To4() == nil {
		return false
	}
	cip := ParseIP(client)
	if cip != nil {
		if !supportsIPv4 && cip.To4() != nil {
			return false
		}
		if !supportsIPv6 && cip.To16() != nil && cip.To4() == nil {
			return false
		}
	}

	// Test functionality of IPv4 communication using AF_INET6
	// sockets.
	if !supportsIPv4map && supportsIPv4 && (network == "tcp" || network == "udp" || network == "ip") && wildcard {
		// At this point, we prefer IPv4 when ip is nil.
		// See favoriteAddrFamily for further information.
		if ip.To16() != nil && ip.To4() == nil && cip.To4() != nil { // a pair of IPv6 server and IPv4 client
			return false
		}
		if (ip.To4() != nil || ip == nil) && cip.To16() != nil && cip.To4() == nil { // a pair of IPv4 server and IPv6 client
			return false
		}
	}

	return true
}

var condFatalf = func() func(*testing.T, string, ...interface{}) {
	// A few APIs, File, Read/WriteMsg{UDP,IP}, are not
	// implemented yet on both Plan 9 and Windows.
	switch runtime.GOOS {
	case "plan9", "windows":
		return (*testing.T).Logf
	}
	return (*testing.T).Fatalf
}()
<commit_msg>net: android no longer supports unix/unixgram<commit_after>// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package net

import (
	"os"
	"runtime"
	"strings"
	"testing"
)

// testableNetwork reports whether network is testable on the current
// platform configuration.
func testableNetwork(network string) bool {
	ss := strings.Split(network, ":")
	switch ss[0] {
	case "ip+nopriv":
		switch runtime.GOOS {
		case "nacl":
			return false
		}
	case "ip", "ip4", "ip6":
		switch runtime.GOOS {
		case "nacl", "plan9":
			return false
		default:
			if os.Getuid() != 0 {
				return false
			}
		}
	case "unix", "unixgram":
		switch runtime.GOOS {
		case "android", "nacl", "plan9", "windows":
			return false
		}
		// iOS does not support unix, unixgram.
		if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
			return false
		}
	case "unixpacket":
		switch runtime.GOOS {
		case "android", "darwin", "nacl", "plan9", "windows":
			fallthrough
		case "freebsd": // FreeBSD 8 and below don't support unixpacket
			return false
		}
	}
	switch ss[0] {
	case "tcp4", "udp4", "ip4":
		if !supportsIPv4 {
			return false
		}
	case "tcp6", "udp6", "ip6":
		if !supportsIPv6 {
			return false
		}
	}
	return true
}

// testableAddress reports whether address of network is testable on
// the current platform configuration.
func testableAddress(network, address string) bool {
	switch ss := strings.Split(network, ":"); ss[0] {
	case "unix", "unixgram", "unixpacket":
		// Abstract unix domain sockets, a Linux-ism.
		if address[0] == '@' && runtime.GOOS != "linux" {
			return false
		}
	}
	return true
}

// testableListenArgs reports whether arguments are testable on the
// current platform configuration.
func testableListenArgs(network, address, client string) bool {
	if !testableNetwork(network) || !testableAddress(network, address) {
		return false
	}

	var err error
	var addr Addr
	switch ss := strings.Split(network, ":"); ss[0] {
	case "tcp", "tcp4", "tcp6":
		addr, err = ResolveTCPAddr("tcp", address)
	case "udp", "udp4", "udp6":
		addr, err = ResolveUDPAddr("udp", address)
	case "ip", "ip4", "ip6":
		addr, err = ResolveIPAddr("ip", address)
	default:
		return true
	}
	if err != nil {
		return false
	}
	var ip IP
	var wildcard bool
	switch addr := addr.(type) {
	case *TCPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	case *UDPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	case *IPAddr:
		ip = addr.IP
		wildcard = addr.isWildcard()
	}

	// Test wildcard IP addresses.
	if wildcard && (testing.Short() || !*testExternal) {
		return false
	}

	// Test functionality of IPv4 communication using AF_INET and
	// IPv6 communication using AF_INET6 sockets.
	if !supportsIPv4 && ip.To4() != nil {
		return false
	}
	if !supportsIPv6 && ip.To16() != nil && ip.To4() == nil {
		return false
	}
	cip := ParseIP(client)
	if cip != nil {
		if !supportsIPv4 && cip.To4() != nil {
			return false
		}
		if !supportsIPv6 && cip.To16() != nil && cip.To4() == nil {
			return false
		}
	}

	// Test functionality of IPv4 communication using AF_INET6
	// sockets.
	if !supportsIPv4map && supportsIPv4 && (network == "tcp" || network == "udp" || network == "ip") && wildcard {
		// At this point, we prefer IPv4 when ip is nil.
		// See favoriteAddrFamily for further information.
		if ip.To16() != nil && ip.To4() == nil && cip.To4() != nil { // a pair of IPv6 server and IPv4 client
			return false
		}
		if (ip.To4() != nil || ip == nil) && cip.To16() != nil && cip.To4() == nil { // a pair of IPv4 server and IPv6 client
			return false
		}
	}

	return true
}

var condFatalf = func() func(*testing.T, string, ...interface{}) {
	// A few APIs, File, Read/WriteMsg{UDP,IP}, are not
	// implemented yet on both Plan 9 and Windows.
	switch runtime.GOOS {
	case "plan9", "windows":
		return (*testing.T).Logf
	}
	return (*testing.T).Fatalf
}()
<|endoftext|>